<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Cek apakah kader sudah login
if (!isset($_SESSION['kader_id']) || !$_SESSION['kader_logged_in']) {
    header('Location: ../../auth/kader_login.php'); 
    exit();
}

require_once '../../api/db_connect.php'; 

$success_message = '';
$error_message = '';
$kader_desa = isset($_SESSION['kader_desa']) ? htmlspecialchars($_SESSION['kader_desa']) : '';
$kader_full_name = isset($_SESSION['kader_full_name']) ? htmlspecialchars($_SESSION['kader_full_name']) : 'Tidak Diketahui'; 

$initialLat = isset($_POST['latitude']) && $_POST['latitude'] !== '' ? (float)$_POST['latitude'] : null;
$initialLng = isset($_POST['longitude']) && $_POST['longitude'] !== '' ? (float)$_POST['longitude'] : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama = htmlspecialchars(trim($_POST['nama']));
    $nik = !empty($_POST['nik']) ? htmlspecialchars(trim($_POST['nik'])) : NULL;
    $alamat = htmlspecialchars(trim($_POST['alamat']));
    $desa = htmlspecialchars(trim($_POST['desa']));
    $rt = !empty($_POST['rt']) ? htmlspecialchars(trim($_POST['rt'])) : NULL;
    $rw = !empty($_POST['rw']) ? htmlspecialchars(trim($_POST['rw'])) : NULL;
    $hpht = !empty($_POST['hpht']) ? htmlspecialchars(trim($_POST['hpht'])) : NULL;
    $hari_tidak_haid = !empty($_POST['hari_tidak_haid']) ? (int)$_POST['hari_tidak_haid'] : NULL;
    $ada_bukti = htmlspecialchars(trim($_POST['ada_bukti']));
    $latitude = isset($_POST['latitude']) && $_POST['latitude'] !== '' ? (float)$_POST['latitude'] : NULL;
    $longitude = isset($_POST['longitude']) && $_POST['longitude'] !== '' ? (float)$_POST['longitude'] : NULL;
    $bukti_foto = NULL;
    $type_sumber = "kader";
    $sumber_laporan_kader = $kader_full_name;

    if (empty($nama) || empty($alamat) || empty($desa) || empty($ada_bukti)) {
        $error_message = "Kolom Nama, Alamat, Desa, dan Ada Bukti Kehamilan wajib diisi.";
    } elseif (!empty($hari_tidak_haid) && (!filter_var($hari_tidak_haid, FILTER_VALIDATE_INT) || $hari_tidak_haid <= 0)) {
        $error_message = "Hari Tidak Haid harus angka positif jika diisi.";
    } elseif ($ada_bukti == 'ya' && (empty($_FILES['bukti_foto']['name']) || $_FILES['bukti_foto']['error'] != UPLOAD_ERR_OK)) {
        $error_message = "Silakan unggah bukti foto jika 'Ada Bukti Kehamilan' dipilih 'Ya'.";
    } else {
        if ($ada_bukti == 'ya' && isset($_FILES['bukti_foto']) && $_FILES['bukti_foto']['error'] == UPLOAD_ERR_OK) {
            $target_dir = "../../uploads/bukti_laporan/";
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
            $file_extension = pathinfo($_FILES['bukti_foto']['name'], PATHINFO_EXTENSION);
            $new_file_name = uniqid('bukti_') . '.' . $file_extension;
            $target_file = $target_dir . $new_file_name;
            $imageFileType = strtolower($file_extension);

            $check = getimagesize($_FILES['bukti_foto']['tmp_name']);
            if($check === false) {
                $error_message = "File bukan gambar.";
            }
            if ($_FILES['bukti_foto']['size'] > 5000000) {
                $error_message = "Maaf, ukuran file terlalu besar (maks 5MB).";
            }
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
                $error_message = "Maaf, hanya file JPG, JPEG, PNG & GIF yang diizinkan.";
            }

            if (empty($error_message)) {
                if (move_uploaded_file($_FILES['bukti_foto']['tmp_name'], $target_file)) {
                    $bukti_foto = $new_file_name;
                } else {
                    $error_message = "Gagal mengunggah foto. Silakan coba lagi.";
                }
            }
        }

        if (empty($error_message)) {
            try {
                $pdo->beginTransaction();

                $stmt = $pdo->prepare("INSERT INTO laporan_kehamilan (user_id, nama, nik, alamat, desa, rt, rw, latitude, longitude, hpht, hari_tidak_haid, ada_bukti, bukti_foto, type_sumber, sumber_laporan) VALUES (:user_id, :nama, :nik, :alamat, :desa, :rt, :rw, :latitude, :longitude, :hpht, :hari_tidak_haid, :ada_bukti, :bukti_foto, :type_sumber, :sumber_laporan)");

                $user_id_for_report = NULL; 

                $stmt->bindParam(':user_id', $user_id_for_report, PDO::PARAM_INT);
                $stmt->bindParam(':nama', $nama, PDO::PARAM_STR);
                $stmt->bindParam(':nik', $nik, PDO::PARAM_STR);
                $stmt->bindParam(':alamat', $alamat, PDO::PARAM_STR);
                $stmt->bindParam(':desa', $desa, PDO::PARAM_STR);
                $stmt->bindParam(':rt', $rt, PDO::PARAM_STR);
                $stmt->bindParam(':rw', $rw, PDO::PARAM_STR);
                $stmt->bindParam(':latitude', $latitude, $latitude === NULL ? PDO::PARAM_NULL : PDO::PARAM_STR);
                $stmt->bindParam(':longitude', $longitude, $longitude === NULL ? PDO::PARAM_NULL : PDO::PARAM_STR);
                $stmt->bindParam(':hpht', $hpht, $hpht === NULL ? PDO::PARAM_NULL : PDO::PARAM_STR);
                $stmt->bindParam(':hari_tidak_haid', $hari_tidak_haid, $hari_tidak_haid === NULL ? PDO::PARAM_NULL : PDO::PARAM_INT);
                $stmt->bindParam(':ada_bukti', $ada_bukti, PDO::PARAM_STR);
                $stmt->bindParam(':bukti_foto', $bukti_foto, PDO::PARAM_STR);
                $stmt->bindParam(':type_sumber', $type_sumber, PDO::PARAM_STR);
                $stmt->bindParam(':sumber_laporan', $sumber_laporan_kader, PDO::PARAM_STR);

                $stmt->execute();
                
                $pdo->commit();

                // --- FITUR BARU: KIRIM NOTIFIKASI WA KE BIDAN DESA ---
                $stmtFonnte = $pdo->query("SELECT api_key FROM fonnte_api_keys LIMIT 1");
                $fonnteData = $stmtFonnte->fetch(PDO::FETCH_ASSOC);
                $apiKey = $fonnteData['api_key'] ?? null;

                if ($apiKey) {
                    $stmtBidan = $pdo->prepare("SELECT phone_number FROM users_laporan_bumil WHERE desa = :desa AND role = 'bidan_desa' LIMIT 1"); 
                    $stmtBidan->bindParam(':desa', $desa);
                    $stmtBidan->execute();
                    $bidanData = $stmtBidan->fetch(PDO::FETCH_ASSOC);
                    
                    $nomorBidan = $bidanData['phone_number'] ?? null;

                    if ($nomorBidan) {
                        // Perubahan utama di sini: Menambahkan detail laporan ke dalam pesan.
                        $message = "🔔 *LAPORAN KEHAMILAN BARU* 🔔\n\n"
                                 . "Halo, Bidan Desa " . $desa . ".\n\n"
                                 . "Ada laporan kehamilan baru yang dilaporkan oleh kader atas nama:\n\n"
                                 . "Nama Ibu Hamil: *" . $nama . "*\n"
                                 . "NIK: " . ($nik ?? 'Tidak ada data') . "\n"
                                 . "Alamat: " . $alamat . "\n"
                                 . "Desa: " . $desa . "\n"
                                 . "RT/RW: " . ($rt ?? '-') . "/" . ($rw ?? '-') . "\n\n"
                                 . "HPHT: " . ($hpht ?? 'Tidak ada data') . "\n"
                                 . "Hari tidak haid: " . ($hari_tidak_haid ?? 'Tidak ada data') . "\n\n"
                                 . "Mohon segera ditindaklanjuti dalam 3x24 jam.\n\n"
                                 . "Terima kasih.";

                        $data = [
                            'target' => $nomorBidan,
                            'message' => $message,
                        ];

                        $curl = curl_init();
                        curl_setopt_array($curl, [
                            CURLOPT_URL => 'https://api.fonnte.com/send',
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_ENCODING => '',
                            CURLOPT_MAXREDIRS => 10,
                            CURLOPT_TIMEOUT => 0,
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            CURLOPT_CUSTOMREQUEST => 'POST',
                            CURLOPT_POSTFIELDS => $data,
                            CURLOPT_HTTPHEADER => [
                                'Authorization: ' . $apiKey
                            ],
                        ]);

                        $response = curl_exec($curl);
                        $err = curl_error($curl);
                        curl_close($curl);

                        if ($err) {
                            error_log("cURL Error (Kader): " . $err);
                        } else {
                            error_log("Fonnte Response (Kader): " . $response);
                        }
                    } else {
                        error_log("Bidan desa tidak ditemukan untuk desa: " . $desa);
                    }
                } else {
                    error_log("Fonnte API Key tidak ditemukan di database.");
                }
                
                $success_message = "Data laporan ibu hamil berhasil ditambahkan.";

                $_POST = array();
                $_POST['desa'] = $kader_desa;
                $initialLat = null;
                $initialLng = null;

            } catch (PDOException $e) {
                $pdo->rollBack();
                $error_message = "Terjadi kesalahan database: " . $e->getMessage();
                error_log("[LAPOR_BUMIL_ERROR] Database Error: " . $e->getMessage());
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lapor Ibu Hamil Baru - Posyandu</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <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 rel="stylesheet" href="../../css/style_kader_dashboard.css"> 

    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />

    <style>
        /* Gaya untuk modal peta (sudah ada di kode Anda, ini untuk memastikan) */
        .map-modal {
            display: none; /* Hidden by default */
            position: fixed; /* Stay in place */
            z-index: 1000; /* Sit on top */
            left: 0;
            top: 0;
            width: 100%; /* Full width */
            height: 100%; /* Full height */
            overflow: auto; /* Enable scroll if needed */
            background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
            justify-content: center; /* Center horizontally */
            align-items: center; /* Center vertically */
        }

        .map-modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 90%;
            /* BATASAN LEBAR MODAL DIUBAH DI SINI */
            max-width: 900px; /* Tingkatkan lebar maksimum untuk modal */
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            position: relative;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .map-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .map-modal-header h3 {
            margin: 0;
            font-size: 1.2rem;
            color: #333;
        }

        .close-button {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close-button:hover,
        .close-button:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        #map {
            height: 400px; /* Tinggi peta */
            width: 100%; /* Ini sudah 100% dari parent-nya */
            border-radius: 8px;
            border: 1px solid #ddd;
        }

        .selected-coords {
            font-size: 0.95rem;
            color: #555;
            text-align: center;
            padding: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
        }

        .map-modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .map-modal-actions button {
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        /* Tambahan styling untuk memastikan input koordinat terlihat sama */
        .form-group .input-coords-display {
            background-color: #e9ecef; /* Sama dengan readonly input */
            cursor: default;
            padding: 12px;
            border: 1px solid #ced4da;
            border-radius: 8px;
            font-size: 0.9rem; /* Sama dengan font input lainnya */
            color: #495057;
            box-sizing: border-box;
            margin-bottom: 15px; /* Sesuaikan dengan margin-bottom form-group */
            display: block; /* Pastikan mengambil seluruh lebar */
        }

        /* Styling untuk tombol "Pilih dari Peta" */
        .btn-ambil-koordinat {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 10px 15px;
            background-color: #007bff; /* Warna biru */
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9rem;
            margin-top: 10px;
            margin-bottom: 5px; /* Sedikit spasi ke bawah */
            transition: background-color 0.3s ease;
        }

        .btn-ambil-koordinat:hover {
            background-color: #0056b3;
        }

        .btn-ambil-koordinat i {
            margin-right: 8px;
        }
    </style>
</head>
<body>
    
<header class="main-header">
    <div class="header-left">
    <a href="../"><i class="fas fa-arrow-left"></i></a>
    </div>
    <div class="header-right">
        <a href="#" title="Notifikasi"><i class="far fa-bell"></i></a> 
        <a href="../../auth/kader_logout.php" title="Logout"><i class="fas fa-sign-out-alt"></i></a> 
    </div>
</header>

<main class="main-content-area lapor-bumil-page">
    <section class="form-card">
        <h2>Lapor Ibu Hamil Baru</h2>
        <p>Isi formulir di bawah ini untuk melaporkan data ibu hamil baru.</p>

        <?php if (!empty($success_message)) { ?>
            <div class="alert alert-success"><?php echo $success_message; ?></div>
        <?php } ?>
        <?php if (!empty($error_message)) { ?>
            <div class="alert alert-danger"><?php echo $error_message; ?></div>
        <?php } ?>

        <form action="" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label for="nama" class="required">Nama Lengkap Ibu Hamil:</label>
                <input type="text" id="nama" name="nama" value="<?php echo htmlspecialchars($_POST['nama'] ?? ''); ?>" required>
            </div>

            <div class="form-group">
                <label for="nik">NIK (Nomor Induk Kependudukan):</label>
                <input type="text" id="nik" name="nik" maxlength="16" value="<?php echo htmlspecialchars($_POST['nik'] ?? ''); ?>">
                <small class="form-text text-muted">Opsional, bisa dikosongkan.</small>
            </div>

            <div class="form-group">
                <label for="alamat" class="required">Alamat Lengkap:</label>
                <textarea id="alamat" name="alamat" rows="3" required><?php echo htmlspecialchars($_POST['alamat'] ?? ''); ?></textarea>
            </div>

            <div class="form-group">
                <label for="desa" class="required">Desa/Kelurahan:</label>
                <input type="text" id="desa" name="desa" value="<?php echo $kader_desa; ?>" readonly required>
                <small class="form-text text-muted">Desa/kelurahan otomatis terisi sesuai desa kader.</small>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="rt">RT:</label>
                        <input type="text" id="rt" name="rt" maxlength="5" value="<?php echo htmlspecialchars($_POST['rt'] ?? ''); ?>">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="rw">RW:</label>
                        <input type="text" id="rw" name="rw" maxlength="5" value="<?php echo htmlspecialchars($_POST['rw'] ?? ''); ?>">
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label for="koordinat_display">Koordinat (Latitude, Longitude):</label>
                <div id="koordinat_display" class="input-coords-display">
                    <?php 
                    $displayLat = isset($_POST['latitude']) ? htmlspecialchars($_POST['latitude']) : '';
                    $displayLon = isset($_POST['longitude']) ? htmlspecialchars($_POST['longitude']) : '';
                    echo (!empty($displayLat) && !empty($displayLon)) ? "$displayLat, $displayLon" : "Belum dipilih";
                    ?>
                </div>
                <input type="hidden" id="latitude" name="latitude" value="<?php echo htmlspecialchars($_POST['latitude'] ?? ''); ?>">
                <input type="hidden" id="longitude" name="longitude" value="<?php echo htmlspecialchars($_POST['longitude'] ?? ''); ?>">
                
                <button type="button" class="btn-ambil-koordinat" onclick="openMapModal()">
                    <i class="fas fa-map-marker-alt"></i> Pilih dari Peta
                </button>
                <small class="form-text text-muted">Klik untuk memilih lokasi dari peta.</small>
            </div>

            <div class="form-group">
                <label for="hpht">HPHT (Hari Pertama Haid Terakhir):</label> <input type="date" id="hpht" name="hpht" value="<?php echo htmlspecialchars($_POST['hpht'] ?? ''); ?>"> <small class="form-text text-muted">Pilih tanggal hari pertama haid terakhir ibu hamil.</small>
            </div>

            <div class="form-group">
                <label for="hari_tidak_haid">Sudah Berapa Hari Tidak Haid?</label> <input type="number" id="hari_tidak_haid" name="hari_tidak_haid" min="1" value="<?php echo htmlspecialchars($_POST['hari_tidak_haid'] ?? ''); ?>"> <small class="form-text text-muted">Masukkan jumlah hari sejak HPHT.</small>
            </div>

            <div class="form-group">
                <label for="ada_bukti" class="required">Ada Bukti Kehamilan?</label>
                <select id="ada_bukti" name="ada_bukti" required onchange="toggleBuktiFoto()">
                    <option value="">Pilih</option>
                    <option value="ya" <?php echo (isset($_POST['ada_bukti']) && $_POST['ada_bukti'] == 'ya') ? 'selected' : ''; ?>>Ya</option>
                    <option value="tidak" <?php echo (isset($_POST['ada_bukti']) && $_POST['ada_bukti'] == 'tidak') ? 'selected' : ''; ?>>Tidak</option>
                </select>
            </div>

            <div class="form-group" id="bukti_foto_group" style="display: <?php echo (isset($_POST['ada_bukti']) && $_POST['ada_bukti'] == 'ya') ? 'block' : 'none'; ?>;">
                <label for="bukti_foto">Unggah Bukti Foto:</label>
                <input type="file" id="bukti_foto" name="bukti_foto" accept="image/*">
                <small class="form-text text-muted">Contoh: Foto hasil test pack, buku KIA, atau surat keterangan dokter. Maks 5MB (JPG, JPEG, PNG, GIF).</small>
            </div>

            <div class="form-actions">
                <button type="button" class="btn-secondary" onclick="window.location.href='../kader_dashboard.php'">Batal</button>
                <button type="submit" class="btn-primary">Laporkan</button>
            </div>
        </form>
    </section>
</main>

<div id="mapModal" class="map-modal">
    <div class="map-modal-content">
        <div class="map-modal-header">
            <h3>Pilih Lokasi Ibu Hamil</h3>
            <span class="close-button" onclick="closeMapModal()">&times;</span>
        </div>
        <div id="map"></div>
        <div class="selected-coords">
            Koordinat Terpilih: <span id="displaySelectedCoords">Belum dipilih</span>
        </div>
        <div class="map-modal-actions">
            <button type="button" class="btn btn-secondary" onclick="closeMapModal()">Batal</button>
            <button type="button" class="btn btn-primary" onclick="saveMapCoords()">Simpan Koordinat</button>
        </div>
    </div>
</div>

<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="https://unpkg.com/leaflet/dist/leaflet.js"></script>

<script>
    function toggleBuktiFoto() {
        var adaBuktiSelect = document.getElementById('ada_bukti');
        var buktiFotoGroup = document.getElementById('bukti_foto_group');
        if (adaBuktiSelect.value === 'ya') {
            buktiFotoGroup.style.display = 'block';
        } else {
            buktiFotoGroup.style.display = 'none';
            document.getElementById('bukti_foto').value = ''; 
        }
    }

    document.addEventListener('DOMContentLoaded', toggleBuktiFoto);

    let map;
    let marker;
    let currentLat = document.getElementById('latitude').value ? parseFloat(document.getElementById('latitude').value) : null;
    let currentLng = document.getElementById('longitude').value ? parseFloat(document.getElementById('longitude').value) : null;

    function updateDisplayCoords() {
        if (currentLat !== null && currentLng !== null) {
            document.getElementById('koordinat_display').innerText = `${currentLat.toFixed(6)}, ${currentLng.toFixed(6)}`;
        } else {
            document.getElementById('koordinat_display').innerText = "Belum dipilih";
        }
    }
    
    document.addEventListener('DOMContentLoaded', updateDisplayCoords);

    function openMapModal() {
        document.getElementById('mapModal').style.display = 'flex';
        setTimeout(() => {
            if (!map) {
                let defaultLat = -7.771726;  
                let defaultLng = 113.409562; 

                map = L.map('map').setView([defaultLat, defaultLng], 15);

                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                }).addTo(map);

                if (currentLat !== null && currentLng !== null) {
                    marker = L.marker([currentLat, currentLng]).addTo(map);
                    map.setView([currentLat, currentLng], 17);
                    document.getElementById('displaySelectedCoords').innerText = `${currentLat.toFixed(6)}, ${currentLng.toFixed(6)}`;
                } else {
                    if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition((position) => {
                            const lat = position.coords.latitude;
                            const lng = position.coords.longitude;
                            map.setView([lat, lng], 17);
                            if (marker) map.removeLayer(marker);
                            marker = L.marker([lat, lng]).addTo(map);
                            document.getElementById('displaySelectedCoords').innerText = `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
                            currentLat = lat; 
                            currentLng = lng;
                        }, (error) => {
                            console.warn('ERROR(' + error.code + '): ' + error.message);
                            document.getElementById('displaySelectedCoords').innerText = `Belum dipilih (Gagal deteksi lokasi)`;
                            alert("Gagal mendapatkan lokasi saat ini. Silakan pilih secara manual atau izinkan akses lokasi browser Anda.");
                        });
                    } else {
                        document.getElementById('displaySelectedCoords').innerText = `Belum dipilih (Geolocation tidak didukung)`;
                        alert("Geolocation tidak didukung oleh browser Anda. Silakan pilih lokasi secara manual di peta.");
                    }
                }

                map.on('click', function(e) {
                    if (marker) {
                        map.removeLayer(marker);
                    }
                    marker = L.marker(e.latlng).addTo(map);
                    currentLat = e.latlng.lat; 
                    currentLng = e.latlng.lng;
                    document.getElementById('displaySelectedCoords').innerText = `${currentLat.toFixed(6)}, ${currentLng.toFixed(6)}`;
                });
            }
            
            if (map) {
                map.invalidateSize();
                if (currentLat !== null && currentLng !== null) {
                    map.setView([currentLat, currentLng], map.getZoom() || 17); 
                } else {
                    map.setView([-7.771726, 113.409562], 15);  
                }
            }

        }, 300);
    }

    function closeMapModal() {
        document.getElementById('mapModal').style.display = 'none';
    }

    function saveMapCoords() {
        if (currentLat !== null && currentLng !== null) {
            document.getElementById('latitude').value = currentLat.toFixed(6);
            document.getElementById('longitude').value = currentLng.toFixed(6);
            document.getElementById('koordinat_display').innerText = `${currentLat.toFixed(6)}, ${currentLng.toFixed(6)}`;
            closeMapModal();
        } else {
            alert("Silakan pilih lokasi di peta terlebih dahulu.");
        }
    }
</script>
</body>
</html>