<?php
session_start();

// Aktifkan error reporting untuk debugging
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']) {
    // Tambahkan log untuk debugging
    error_log("[AUTH_ERROR] Kader not logged in. Session kader_id: " . ($_SESSION['kader_id'] ?? 'N/A') . ", kader_logged_in: " . ($_SESSION['kader_logged_in'] ?? 'N/A'));
    header('Location: ../../auth/kader_login.php');
    exit();
}

// Sesuaikan path ke db_connect.php.
// Pastikan file ini ada dan tidak ada spasi/karakter sebelum tag <?php pembuka di db_connect.php
require_once '../../api/db_connect.php'; 

$success_message = '';
$error_message = '';
$kader_desa = isset($_SESSION['kader_desa']) ? $_SESSION['kader_desa'] : '';

// Jika kader_desa kosong setelah login, ada masalah di setup sesi atau data kader
if (empty($kader_desa)) {
    error_log("[KADER_SESSION_ERROR] kader_desa is empty for kader_id: " . ($_SESSION['kader_id'] ?? 'N/A'));
    // Redirect dengan pesan error yang lebih jelas
    header('Location: ../../auth/kader_login.php?error=desa_not_set'); 
    exit();
}


// --- Handle AJAX Fetch for Map Data (for modal) ---
// Bagian ini akan merespons permintaan AJAX dari JavaScript untuk mendapatkan detail lokasi satu ibu hamil
if (isset($_GET['fetch_map_data'])) {
    $ibu_id = (int)$_GET['fetch_map_data'];
    try {
        // Mengambil data dari laporan_kehamilan jika verif = 1
        // Pastikan nama kolom di DB Anda adalah 'nama', 'alamat', 'latitude', 'longitude', 'desa', 'verif'
        $stmt = $pdo->prepare("SELECT nama AS nama, alamat, latitude, longitude FROM laporan_kehamilan WHERE id = :id AND desa = :desa AND verif = 1");
        $stmt->bindParam(':id', $ibu_id, PDO::PARAM_INT);
        $stmt->bindParam(':desa', $kader_desa, PDO::PARAM_STR);
        $stmt->execute();
        $ibu_data = $stmt->fetch(PDO::FETCH_ASSOC);

        // Penting: Pastikan tidak ada spasi, baris kosong, atau karakter lain sebelum header() atau echo
        header('Content-Type: application/json');
        if ($ibu_data) {
            // Pastikan latitude dan longitude di-cast ke float jika disimpan sebagai string/teks di DB
            $ibu_data['latitude'] = (float)$ibu_data['latitude'];
            $ibu_data['longitude'] = (float)$ibu_data['longitude'];
            echo json_encode(['success' => true, 'data' => $ibu_data]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Data ibu hamil tidak ditemukan atau belum diverifikasi.']);
        }
    } catch (PDOException $e) {
        // Tangani error database saat fetch data peta
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan database: ' . $e->getMessage()]);
        error_log("[IBU_HAMIL_MAP_FETCH_ERROR] " . $e->getMessage());
    }
    exit(); // Sangat penting untuk keluar setelah mengirim respons JSON
}

// --- Fetch All Ibu Hamil for current kader's desa ---
// Bagian ini akan mengisi tabel daftar ibu hamil
$ibu_hamil_list = [];
try {
    // Mengambil semua ibu hamil dari laporan_kehamilan yang verif = 1 dan desanya sesuai
    $stmt = $pdo->prepare("SELECT id, nama AS nama, alamat, latitude, longitude FROM laporan_kehamilan WHERE desa = :desa AND verif = 1 ORDER BY nama ASC");
    $stmt->bindParam(':desa', $kader_desa, PDO::PARAM_STR);
    $stmt->execute();
    $ibu_hamil_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = "Gagal memuat daftar ibu hamil: " . $e->getMessage();
    error_log("[IBU_HAMIL_FETCH_ERROR] " . $e->getMessage());
}

// Check for messages from URL parameters (e.g., after delete or add/edit redirect)
$clear_url_params = false;
if (isset($_GET['status']) && isset($_GET['message'])) {
    if ($_GET['status'] == 'success') {
        $success_message = htmlspecialchars($_GET['message']);
    } else {
        $error_message = htmlspecialchars($_GET['message']);
    }
    $clear_url_params = true;
}
?>

<!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>Daftar Ibu Hamil - 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">
    
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>

    <link rel="stylesheet" href="../../css/style_kader_dashboard.css"> 

    <style>
        /* Reused Modal Styling from jadwal page */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            justify-content: center;
            align-items: center;
            z-index: 1000;
            overflow-y: auto;
            padding: 20px;
            box-sizing: border-box;
        }

        .modal-content {
            background-color: #fff;
            padding: 10px;
            border-radius: 10px;
            width: 100%;
            max-width: 700px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            position: relative;
            animation: fadeIn 0.3s ease-out;
            max-height: 90vh;
            overflow-y: auto;
            flex-shrink: 0;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
            margin-bottom: 20px;
            position: sticky;
            top: 0;
            background-color: #fff;
            z-index: 10;
            margin-left: -30px; 
            margin-right: -30px; 
            padding-left: 30px; 
            padding-right: 30px; 
        }

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

        .modal-close-btn {
            font-size: 2rem;
            cursor: pointer;
            color: #888;
            transition: color 0.2s ease;
        }

        .modal-close-btn:hover {
            color: #333;
        }

        /* --- Standard table styling with font/padding adjustments --- */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
            border-radius: 8px;
            overflow: hidden;
            background-color: #fff;
        }

        .data-table thead {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }

        .data-table th {
            padding: 10px 12px; /* Smaller padding */
            text-align: left;
            font-weight: 600;
            color: #333;
            font-size: 0.7rem; /* Slightly smaller font for header */
            border-bottom: 1px solid #dee2e6;
        }

        .data-table tbody tr {
            border-bottom: 1px solid #e9ecef;
        }

        .data-table tbody tr:last-child {
            border-bottom: none;
        }

        .data-table tbody tr:hover {
            background-color: #f1f7fe;
        }

        .data-table td {
            padding: 8px 12px; /* Smaller padding for cells */
            vertical-align: top; /* Align content to top */
            color: #495057;
            font-size: 0.7rem; /* Smaller font for cell content */
            display: table-cell; /* Ensure it behaves like a table cell */
        }

        .data-table td.action-buttons {
            text-align: center; /* Center the icon */
            white-space: nowrap; /* Keep buttons on one line */
            padding: 5px 12px; /* Adjust padding specifically for action column */
            align-items: center; /* Vertically center the content */
            justify-content: center; /* Horizontally center the content */
            height: 100%; /* Ensure flex container takes full height of row */
        }

        .data-table .action-btn {
            background: none;
            border: none;
            color: #007bff;
            cursor: pointer;
            font-size: 1rem; /* Slightly smaller icon size */
            margin: 0; /* Remove margin to rely on parent padding */
            transition: color 0.2s ease, transform 0.2s ease;
            padding: 0; /* Remove internal padding to align icon */
            border-radius: 4px;
            align-items: center;
            justify-content: center;
        }

        .data-table .action-btn:hover {
            color: #0056b3;
            transform: scale(1.1);
        }

        .data-table .action-btn .fa-map-marker-alt {
            color: #28a745; /* Warna ikon peta */
        }
        .data-table .action-btn .fa-map-marker-alt:hover {
            color: #218838;
        }
        .data-table .action-btn.disabled { /* Style for disabled map button */
            color: #6c757d;
            cursor: not-allowed;
            opacity: 0.7;
        }
        .data-table .action-btn.disabled:hover {
            transform: none;
            color: #6c757d;
            background: none;
        }

        /* Ensure .table-responsive is working */
        .table-responsive {
            overflow-x: auto; /* Enables horizontal scrolling for tables */
            -webkit-overflow-scrolling: touch; /* Improves scrolling on iOS */
        }

        /* Styling for the Leaflet map container */
        #mapid {
            height: 350px; /* Adjust height as needed */
            width: 100%;
            background-color: #f0f0f0; /* Fallback background */
            border-radius: 8px;
            margin-top: 15px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    
<header class="main-header">
    <div class="header-left">
        <a href="../kader_dashboard.php"><i class="fas fa-arrow-left"></i></a>
        <div class="profile-icon">
            <i class="fas fa-user-circle"></i>
        </div>
        <div class="user-info">
            <p>Halo, <span id="username">Kader Posyandu</span></p>
            <p class="role-text">
                Kader Posyandu (Desa: <?php echo htmlspecialchars($kader_desa); ?>)
                <i class="fas fa-check-circle verified-icon"></i>
            </p>
        </div>
    </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 daftar-ibu-hamil-page">
    <section class="form-card">
        <h2>Daftar Ibu Hamil</h2>
        <p>Lihat dan kelola data ibu hamil yang sudah diverifikasi di desa Anda.</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 } ?>

        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Nama Ibu</th>
                        <th>Alamat</th>
                        <th style="width: 100px; text-align: center;">Lokasi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($ibu_hamil_list) > 0): ?>
                        <?php foreach ($ibu_hamil_list as $ibu): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($ibu['nama']); ?></td>
                                <td><?php echo htmlspecialchars($ibu['alamat']); ?></td>
                                <td class="action-buttons">
                                    <?php 
                                    // Memastikan latitude dan longitude adalah angka dan tidak nol
                                    $has_valid_coords = !empty($ibu['latitude']) && !empty($ibu['longitude']) && 
                                                        is_numeric($ibu['latitude']) && is_numeric($ibu['longitude']) &&
                                                        (float)$ibu['latitude'] != 0 && (float)$ibu['longitude'] != 0;
                                    ?>
                                    <?php if ($has_valid_coords): ?>
                                        <button class="action-btn" onclick="openMapModal(<?php echo $ibu['id']; ?>)" title="Lihat Peta">
                                            <i class="fas fa-map-marker-alt"></i>
                                        </button>
                                    <?php else: ?>
                                        <button class="action-btn disabled" disabled title="Lokasi tidak tersedia">
                                            <i class="fas fa-map-marker-alt"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="3" style="text-align: center;">Belum ada data ibu hamil yang terverifikasi untuk desa ini.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>
</main>

<nav class="nav1">
    <ul class="nav-content1">
        <li class="nav-list1">
            <a href="../kader_dashboard.php" class="link-item1"> <i class='bx bx-home-alt link-icon1'></i> <span class="link-text1">Beranda</span>
            </a>
        </li>
        <li class="nav-list1">
            <a href="daftar_ibu_hamil.php" class="link-item1 active"> <i class='bx bx-group link-icon1'></i> <span class="link-text1">Ibu Hamil</span>
            </a>
        </li>
        <li class="nav-list1">
            <a href="../verifikasi_laporan.php" class="link-item1"> <i class='bx bx-check-double link-icon1'></i> <span class="link-text1">Verifikasi</span>
            </a>
        </li>
        <li class="nav-list1">
            <a href="../jadwal/kelola_jadwal_posyandu.php" class="link-item1"> <i class='bx bx-calendar link-icon1'></i> <span class="link-text1">Jadwal</span>
            </a>
        </li>
        <li class="nav-list1">
            <a href="../profil_kader.php" class="link-item1"> <i class='bx bx-user-circle link-icon1'></i> <span class="link-text1">Profil</span>
            </a>
        </li>
    </ul>
</nav>

<div id="mapModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h6 id="mapModalTitle"></h6>
            <span class="modal-close-btn" onclick="closeMapModal()">&times;</span>
        </div>
        <div id="mapid">
            <p style="text-align: center; padding: 20px;">Memuat peta...</p> 
        </div>
        <p id="mapCoordinates" style="margin-top: 5px; font-size: 0.9em; color: #666; text-align: center;"></p>
        <p style="margin-top: 15px; font-size: 0.8em; color: #999;">
            Powered by OpenStreetMap & Leaflet.
        </p>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
    const mapModal = document.getElementById('mapModal');
    const mapModalTitle = document.getElementById('mapModalTitle');
    const mapDiv = document.getElementById('mapid'); // Menggunakan mapid untuk konsistensi Leaflet
    const mapCoordinates = document.getElementById('mapCoordinates');

    let currentMap = null; // Variabel untuk menyimpan instance peta Leaflet

    // Flag dari PHP untuk membersihkan parameter URL
    const clearUrlParams = <?php echo json_encode($clear_url_params ?? false); ?>; 

    /**
     * Membuka modal peta dan memuat data lokasi.
     * @param {number} ibuId - ID ibu hamil.
     */
    async function openMapModal(ibuId) {
        mapModalTitle.innerText = 'Memuat Lokasi...';
        mapDiv.innerHTML = '<p style="text-align: center; padding: 20px;">Memuat peta...</p>'; // Teks loading
        mapCoordinates.innerText = '';
        mapModal.style.display = 'flex'; // Tampilkan modal

        // Pastikan peta sebelumnya dihapus jika ada
        if (currentMap) {
            currentMap.remove();
            currentMap = null;
        }

        try {
            // Log URL yang di-fetch untuk debugging
            const fetchUrl = `index.php?fetch_map_data=${ibuId}`;
            console.log("Fetching map data from:", fetchUrl);

            const response = await fetch(fetchUrl);
            
            // Log the raw response text for debugging, BEFORE .json()
            const responseText = await response.text(); 
            console.log("Raw response from fetch_map_data:", responseText);

            let result;
            try {
                result = JSON.parse(responseText); // Manual parse to catch malformed JSON better
            } catch (e) {
                // Tangani kasus di mana respons bukan JSON yang valid
                throw new Error("Failed to parse JSON response. Raw response: " + responseText.substring(0, 200) + "..."); // Potong respons jika terlalu panjang
            }
            

            if (result.success) {
                const data = result.data;
                mapModalTitle.innerText = ` ${data.nama}`;
                
                // Pastikan lat dan lon adalah angka
                const lat = parseFloat(data.latitude);
                const lon = parseFloat(data.longitude);

                if (isNaN(lat) || isNaN(lon) || (lat === 0 && lon === 0)) {
                    mapDiv.innerHTML = '<div class="alert alert-warning text-center">Koordinat lokasi tidak valid atau kosong.</div>';
                    mapCoordinates.innerText = 'Tidak ada koordinat yang valid.';
                    console.error('Koordinat tidak valid:', data.latitude, data.longitude);
                    return;
                }

                // Inisialisasi peta Leaflet
                // Penting: Kosongkan mapDiv sebelum inisialisasi untuk mencegah duplikasi peta
                mapDiv.innerHTML = ''; 
                currentMap = L.map(mapDiv).setView([lat, lon], 15); // Inisialisasi peta di div mapid

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

                L.marker([lat, lon]).addTo(currentMap)
                    .bindPopup('<b>' + data.nama + '</b><br>' + data.alamat)
                    .openPopup();

                mapCoordinates.innerText = `Lat: ${lat.toFixed(6)}, Long: ${lon.toFixed(6)}`;

                // Memastikan peta di-render ulang dengan ukuran yang benar setelah modal terlihat
                setTimeout(() => {
                    if (currentMap) { // Pastikan peta masih ada sebelum invalidateSize
                        currentMap.invalidateSize();
                    }
                }, 100);

            } else {
                mapModalTitle.innerText = 'Error Memuat Lokasi';
                mapDiv.innerHTML = `<div class="alert alert-danger text-center">${result.message}</div>`;
                mapCoordinates.innerText = '';
                console.error('Error fetching map data (backend message):', result.message);
            }
        } catch (error) {
            mapModalTitle.innerText = 'Terjadi Kesalahan';
            mapDiv.innerHTML = `<div class="alert alert-danger text-center">Gagal memuat data peta: ${error.message}. Silakan coba lagi.</div>`;
            mapCoordinates.innerText = '';
            console.error('Fetch or JSON parsing error:', error);
        }
    }

    /**
     * Menutup modal peta.
     */
    function closeMapModal() {
        mapModal.style.display = 'none';
        if (currentMap) {
            currentMap.remove(); // Hapus instance peta Leaflet
            currentMap = null; // Setel ulang variabel
        }
        mapDiv.innerHTML = '<p style="text-align: center; padding: 20px;">Memuat peta...</p>'; // Bersihkan konten peta saat ditutup
        mapCoordinates.innerText = '';
    }

    // --- Event listener saat DOM sudah dimuat ---
    document.addEventListener('DOMContentLoaded', function() {
        // Hapus parameter URL setelah menampilkan pesan (jika ada)
        if (clearUrlParams) {
            const url = new URL(window.location.href);
            url.searchParams.delete('status');
            url.searchParams.delete('message');
            window.history.replaceState({}, document.title, url.toString());
        }

        // --- Event listener untuk menutup modal jika klik di luar konten modal ---
        mapModal.addEventListener('click', function(event) {
            if (event.target === mapModal) {
                closeMapModal();
            }
        });
    });
</script>
</body>
</html>