<?php
// Pastikan sesi dimulai untuk mengakses user_id
session_start();

// Redirect jika belum login
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../auth/login.php'); // Sesuaikan path ke halaman login Anda
    exit();
}

require_once '../../api/db_connect.php'; // Sesuaikan path ke file db_connect.php Anda

$userProfile = null;

try {
    $userId = $_SESSION['user_id'];

    // Query untuk mengambil SEMUA data profil berdasarkan user_id
    $stmt = $pdo->prepare("SELECT 
                                full_name, 
                                phone_number, 
                                address, 
                                village, 
                                rt, 
                                rw, 
                                coordinates, 
                                date_of_birth, 
                                nik, 
                                profile_picture_url 
                            FROM users 
                            WHERE id = :id");
    $stmt->execute([':id' => $userId]);
    $userProfile = $stmt->fetch(PDO::FETCH_ASSOC);

    // Jika userProfile kosong, kemungkinan user_id di sesi tidak valid atau data tidak ditemukan
    if (!$userProfile) {
        // Hapus sesi dan redirect ke login
        session_unset();
        session_destroy();
        header('Location: ../auth/login.php?error=profil_not_found');
        exit();
    }

    // Format tanggal lahir agar sesuai dengan input type="date" (YYYY-MM-DD)
    if (isset($userProfile['date_of_birth']) && $userProfile['date_of_birth']) {
        $userProfile['date_of_birth'] = (new DateTime($userProfile['date_of_birth']))->format('Y-m-d');
    } else {
        $userProfile['date_of_birth'] = ''; // Pastikan kosong jika null dari DB
    }

} catch (PDOException $e) {
    error_log("Error fetching profile data for edit: " . $e->getMessage());
    echo "Terjadi kesalahan saat memuat data profil. Silakan coba lagi nanti.";
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ubah Akun</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    
    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <link rel="stylesheet" href="../../css/style.css"> 

    <style>
        /* CSS tambahan jika belum ada di style.css untuk menangani gambar profil */
        .profile-pic-preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
        }
        .profile-pic-icon.hidden,
        .profile-pic-preview.hidden {
            display: none;
        }
        /* Style untuk pesan sukses/error (jika belum ada) */
        .message-area {
            padding: 10px;
            margin-top: 15px;
            border-radius: 5px;
            font-size: 0.9em;
            text-align: center;
        }
        .message-area.hidden {
            display: none;
        }
        .success-message {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error-message {
        background-color: #d7f8e5;
        color: #2a721c;
            border: 1px solid #d7f8e5;
        }
        /* Style untuk loading overlay (jika belum ada) */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .loading-overlay.hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="page-header edit-profile-header">
        <a href="../" class="back-btn"><i class="fas fa-arrow-left"></i></a> <h1>Ubah Akun</h1>
    </div>

    <div class="main-content-area edit-profile-page-content">
        <div class="profile-picture-section">
            <div class="profile-picture-circle">
                <img id="profilePicPreview" 
                     src="<?php echo htmlspecialchars($userProfile['profile_picture_url'] ? '../../' . $userProfile['profile_picture_url'] : ''); ?>" 
                     alt="Foto Profil" 
                     class="profile-pic-preview <?php echo $userProfile['profile_picture_url'] ? '' : 'hidden'; ?>">
                <i class='bx bx-user-circle profile-pic-icon <?php echo $userProfile['profile_picture_url'] ? 'hidden' : ''; ?>' id="profilePicPlaceholder"></i>
                <a href="#" class="camera-icon-overlay" id="uploadPicTrigger">
                    <i class='bx bx-camera'></i>
                </a>
                <input type="file" id="profilePicInput" accept="image/*" style="display: none;">
            </div>
        </div>

        <div class="info-profile-card">
            <div class="card-header-edit">
                <h2>Info Profil</h2>
                <button id="editInfoBtn" class="btn-edit-info">
                    Ubah <i class='bx bx-edit-alt'></i>
                </button>
            </div>
            <form id="profileInfoForm">
                <div class="info-row">
                    <span class="info-label">Kewarganegaraan</span>
                    <input type="text" id="kewarganegaraan" name="kewarganegaraan" value="Warga Negara Indonesia" readonly>
                </div>
                <div class="info-row">
                    <span class="info-label">Nama Lengkap</span>
                    <input type="text" id="namaLengkap" name="full_name" value="<?php echo htmlspecialchars($userProfile['full_name'] ?? ''); ?>" readonly>
                </div>
                <div class="info-row">
                    <span class="info-label">Nomor HP/WA</span>
                    <input class="form-control" type="tel" id="nomorHpWa" name="phone_number" value="<?php echo htmlspecialchars($userProfile['phone_number'] ?? ''); ?>" readonly> 
                </div>
                <div class="info-row">
                    <span class="info-label">Alamat</span>
                    <input type="text" id="alamat" name="address" value="<?php echo htmlspecialchars($userProfile['address'] ?? ''); ?>" readonly> 
                </div>
                <div class="info-row">
                    <span class="info-label">Desa</span>
                    <input type="text" id="desa" name="village" value="<?php echo htmlspecialchars($userProfile['village'] ?? ''); ?>" readonly> 
                </div>
                <div class="info-row">
                    <span class="info-label">RT</span>
                    <input type="text" id="rt" name="rt" value="<?php echo htmlspecialchars($userProfile['rt'] ?? ''); ?>" maxlength="3" readonly> 
                </div>
                <div class="info-row">
                    <span class="info-label">RW</span>
                    <input type="text" id="rw" name="rw" value="<?php echo htmlspecialchars($userProfile['rw'] ?? ''); ?>" maxlength="3" readonly> 
                </div>
                <div class="info-row">
                    <span class="info-label">Koordinat</span>
                    <div class="input-with-button">
                        <input type="text" id="koordinat" name="coordinates" value="<?php echo htmlspecialchars($userProfile['coordinates'] ?? ''); ?>" placeholder="Contoh: -7.xxxx, 112.yyyy" readonly>
                    <button type="button" id="getCoordinatesBtn" class="btn btn-primary btn-sm" style="width: auto; padding: 0.375rem 0.75rem; margin-top: 10px;"><i class="fas fa-map-marker-alt mr-1"></i>Ambil</button>
                    </div>
                </div>
                
                <div class="modal fade" id="mapModal" tabindex="-1" role="dialog" aria-labelledby="mapModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="mapModalLabel">Pilih Lokasi Anda</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div id="map" style="height: 400px; width: 100%;"></div> <div class="mt-3">
                                    <strong>Koordinat Terpilih:</strong> <span id="selectedCoordinates"></span>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" id="cancelMapModalBtn">Batal</button>
                                <button type="button" class="btn btn-primary" id="saveMapCoordinates">Simpan Koordinat</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="info-row">
                    <span class="info-label">Tanggal Lahir</span>
                    <input class="form-control" type="date" id="tanggalLahir" name="date_of_birth" value="<?php echo htmlspecialchars($userProfile['date_of_birth'] ?? ''); ?>" readonly> 
                </div>
                <div class="info-row">
                    <span class="info-label">NIK</span>
                    <input type="text" id="nik" name="nik" value="<?php echo htmlspecialchars($userProfile['nik'] ?? ''); ?>" readonly> 
                </div>

                <button type="submit" id="saveInfoBtn" class="btn-save-info d-none">Simpan Perubahan</button>
                <button type="button" id="cancelEditBtn" class="btn-cancel-edit d-none">Batal</button>
                
                <div id="profileMessage" class="message-area hidden"></div>
            </form>
        </div>
    </div>

    <div id="loadingOverlay" class="loading-overlay hidden">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>



<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="../../js/script.js"></script> 
    </body>
</html>