<?php
session_start();

// Periksa apakah pengguna sudah login sebagai jejaring
if (!isset($_SESSION['jejaring_logged_in']) || !$_SESSION['jejaring_logged_in']) {
    header('Location: ../../auth/jejaring_login.php'); // Arahkan kembali ke login jika belum login
    exit();
}

// Data pengguna yang login
$loggedInUsername = htmlspecialchars($_SESSION['jejaring_username']);
$loggedInUserType = htmlspecialchars($_SESSION['jejaring_user_type']);
$loggedInNamaInstansi = htmlspecialchars($_SESSION['jejaring_nama_instansi']);
$pageTitle = "Daftar Laporan Kehamilan Bulan Ini";

// ====================================================================
// PENTING: Penyesuaian PATH untuk db_connect.php
// Pastikan path ini benar dari lokasi file index.php
// ====================================================================
include_once '../../api/db_connect.php'; 

// Inisialisasi variabel untuk menyimpan data laporan
$laporan_kehamilan = [];
$error_message = '';

// ====================================================================
// Pengaturan Paginasi
// ====================================================================
$records_per_page = 10; // Jumlah data per halaman
$current_page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $records_per_page;
$total_records = 0;
$total_pages = 1;

try {
    if (!isset($pdo) || !$pdo instanceof PDO) {
        throw new PDOException("Objek PDO tidak tersedia setelah menyertakan db_connect.php.");
    }

    // Query untuk menghitung total records (penting untuk paginasi)
    $count_query = "SELECT COUNT(*) FROM laporan_kehamilan
                    WHERE sumber_laporan = :nama_instansi
                    AND YEAR(tanggal_lapor) = YEAR(CURDATE())
                    AND MONTH(tanggal_lapor) = MONTH(CURDATE())";
    $count_stmt = $pdo->prepare($count_query);
    $count_stmt->bindParam(':nama_instansi', $_SESSION['jejaring_nama_instansi'], PDO::PARAM_STR);
    $count_stmt->execute();
    $total_records = $count_stmt->fetchColumn();
    $total_pages = ceil($total_records / $records_per_page);

    // Pastikan halaman saat ini tidak kurang dari 1 atau lebih dari total halaman
    if ($current_page < 1) {
        $current_page = 1;
    } elseif ($current_page > $total_pages && $total_pages > 0) {
        $current_page = $total_pages;
        $offset = ($current_page - 1) * $records_per_page; // Sesuaikan offset
    }

    // Query untuk mengambil data laporan kehamilan dengan LIMIT dan OFFSET
    $query = "SELECT * FROM laporan_kehamilan
              WHERE sumber_laporan = :nama_instansi
              AND YEAR(tanggal_lapor) = YEAR(CURDATE())
              AND MONTH(tanggal_lapor) = MONTH(CURDATE())
              ORDER BY tanggal_lapor DESC
              LIMIT :limit OFFSET :offset";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':nama_instansi', $_SESSION['jejaring_nama_instansi'], PDO::PARAM_STR);
    $stmt->bindParam(':limit', $records_per_page, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $laporan_kehamilan = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $error_message = "Error database: " . $e->getMessage();
}

// Fungsi untuk format tanggal menjadi format Indonesia
function formatDateIndonesian($dateString) {
    if (empty($dateString) || $dateString == '0000-00-00' || $dateString == 'NULL') {
        return '-';
    }
    $timestamp = strtotime($dateString);
    if ($timestamp === false) {
        return '-';
    }

    $bulan = [
        'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
    ];
    return date('d', $timestamp) . ' ' . $bulan[date('n', $timestamp) - 1] . ' ' . date('Y', $timestamp);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - RekamSehat</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        :root {
            --primary-color: #4dab25;
            --secondary-color: #024d52;
            --bg-light: #f4f7f6;
            --text-dark: #333;
            --text-light: #fefefe;
            --border-color: #e0e0e0;
            --sidebar-width: 250px;
            --header-height: 60px;
        }

        body {
            font-family: 'Poppins', sans-serif;
            margin: 0;
            background-color: var(--bg-light);
            color: var(--text-dark);
            display: flex;
            min-height: 100vh;
            overflow-x: hidden;
        }

        /* --- Header --- */
        .header {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: var(--header-height);
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            padding: 0 0px;
            z-index: 1000;
            transition: margin-left 0.3s ease;
        }
        .header .logo {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--secondary-color);
            margin-right: auto;
        }
        .header .user-info {
            display: flex;
            align-items: center;
            font-size: 0.9rem;
            color: var(--text-dark);
        }
        .header .user-info .user-icon {
            margin-right: 8px;
            color: var(--primary-color);
        }
        .header .user-info .username {
            font-weight: 600;
            margin-right: 15px;
        }
        .header .logout-btn {
            background: none;
            border: none;
            color: var(--secondary-color);
            cursor: pointer;
            font-size: 1rem;
            padding: 5px 10px;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }
        .header .logout-btn:hover {
            background-color: rgba(0,0,0,0.05);
        }

        /* --- Sidebar --- */
        .sidebar {
            width: var(--sidebar-width);
            background: var(--secondary-color);
            color: var(--text-light);
            padding-top: var(--header-height);
            position: fixed;
            top: 0;
            left: 0;
            height: 100%;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            z-index: 999;
            transition: transform 0.3s ease;
            transform: translateX(0);
            overflow-y: auto;
        }

        /* KOREKSI: Mengganti .sidebar.hidden menjadi .sidebar.hide */
        .sidebar.hide {
            transform: translateX(calc(-1 * var(--sidebar-width)));
        }

        .sidebar-header {
            padding: 20px;
            text-align: center;
            background-color: var(--primary-color);
            color: var(--text-light);
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        .sidebar ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar ul li a {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            color: var(--text-light);
            text-decoration: none;
            font-size: 1rem;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .sidebar ul li a i {
            margin-right: 10px;
            font-size: 1.2rem;
        }

        .sidebar ul li a:hover,
        .sidebar ul li a.active {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff;
        }

        /* Dropdown Styles */
        .sidebar .dropdown-btn {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px 20px;
            color: var(--text-light);
            text-decoration: none;
            font-size: 1rem;
            transition: background-color 0.3s ease, color 0.3s ease;
            cursor: pointer;
        }

        .sidebar .dropdown-btn i {
            margin-right: 10px;
            font-size: 1.2rem;
        }

        .sidebar .dropdown-btn:hover,
        .sidebar .dropdown-btn.active {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff;
        }

        .sidebar .dropdown-container {
            display: none;
            background-color: rgba(0, 0, 0, 0.1);
            padding-left: 20px;
        }

        .sidebar .dropdown-container a {
            padding: 12px 16px;
            text-decoration: none;
            color: var(--text-light);
            display: block;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .sidebar .dropdown-container a:hover {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff;
        }

        .sidebar .dropdown-container.show {
            display: block;
        }


        /* --- Main Content Area --- */
        .main-content {
            margin-left: var(--sidebar-width);
            padding: calc(var(--header-height) + 30px) 30px 30px 30px;
            flex-grow: 1;
            transition: margin-left 0.3s ease; /* Menambahkan transisi */
            width: calc(100% - var(--sidebar-width));
        }

        .main-content.shift { /* KOREKSI: Mengganti full-width dengan shift */
            margin-left: 0;
            width: 100%;
        }

        /* --- Toggle Button --- */
        .sidebar-toggle {
            position: fixed;
            top: 15px;
            left: calc(var(--sidebar-width) + 15px);
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            padding: 8px 12px;
            cursor: pointer;
            z-index: 1001;
            transition: left 0.3s ease;
            font-size: 1.2rem;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .sidebar-toggle:hover {
            background-color: #3e8d22;
        }

        /* --- Table Styles --- */
        .table-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.08);
            margin-top: 20px;
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        .data-table th {
            background-color: var(--primary-color);
            color: var(--text-light);
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.9rem;
        }

        .data-table tbody tr:nth-child(even) {
            background-color: #f8f8f8;
        }

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

        .data-table td img {
            max-width: 80px;
            height: auto;
            border-radius: 5px;
            display: block;
            margin: 0 auto;
        }

        .no-data-message {
            text-align: center;
            padding: 30px;
            color: #777;
            font-style: italic;
        }

        /* Alert messages */
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
        }
        .alert.error-message {
            background-color: #ffe6e6;
            color: #cc0000;
            border: 1px solid #ffb3b3;
        }
        .alert.success-message {
            background-color: #e6ffe6;
            color: #008000;
            border: 1px solid #b3ffb3;
        }

        /* Report Button (the modal trigger) */
        .report-button-container {
            text-align: right;
            margin-bottom: 20px;
        }

        .report-button {
            display: inline-flex;
            align-items: center;
            background-color: var(--primary-color);
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: background-color 0.3s ease, transform 0.2s ease;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            cursor: pointer;
            font-size: 1rem;
        }

        .report-button:hover {
            background-color: #3e8d22;
            transform: translateY(-2px);
        }

        .report-button i {
            margin-right: 8px;
            font-size: 1.1rem;
        }

        /* --- Modal Styles --- */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.6);
            justify-content: center;
            align-items: center;
        }

        .modal.show-modal {
            display: flex;
        }

        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            width: 90%;
            max-width: 600px;
            position: relative;
            animation: fadeIn 0.3s ease-out;
        }

        .close-button {
            color: #aaa;
            position: absolute;
            top: 15px;
            right: 25px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: color 0.3s ease;
        }

        .close-button:hover,
        .close-button:focus {
            color: #333;
            text-decoration: none;
        }

        .modal-content h3 {
            color: var(--secondary-color);
            margin-top: 0;
            margin-bottom: 25px;
            text-align: center;
            font-size: 1.8rem;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-dark);
        }

        .form-control {
            width: calc(100% - 20px);
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 5px;
            font-size: 1rem;
            font-family: 'Poppins', sans-serif;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
            box-sizing: border-box;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(77, 171, 37, 0.2);
            outline: none;
        }

        textarea.form-control {
            resize: vertical;
            min-height: 80px;
        }

        .modal-buttons {
            text-align: right;
            margin-top: 30px;
        }

        .modal-buttons button {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: background-color 0.3s ease;
        }

        .modal-buttons .submit-btn {
            background-color: var(--primary-color);
            color: white;
            margin-left: 10px;
        }

        .modal-buttons .submit-btn:hover {
            background-color: #3e8d22;
        }

        .modal-buttons .cancel-btn {
            background-color: #ccc;
            color: var(--text-dark);
        }

        .modal-buttons .cancel-btn:hover {
            background-color: #bbb;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* KOREKSI: CSS Responsif yang Diperbarui */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(calc(-1 * var(--sidebar-width)));
                box-shadow: none;
            }
            .sidebar.show {
                transform: translateX(0);
                box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            }
            .main-content {
                margin-left: 0;
                width: 100%;
                padding: calc(var(--header-height) + 20px) 20px 20px 20px;
            }
            .sidebar-toggle {
                left: 15px;
            }
            .report-button-container {
                text-align: center;
            }
            .modal-content {
                width: 95%;
                padding: 20px;
            }
            .modal-content h3 {
                font-size: 1.5rem;
            }
            .form-control {
                width: calc(100% - 20px);
            }
        }
        @media (max-width: 500px) {
            .header {
                padding: 0 10px;
            }
            .header .logo {
                font-size: 1.3rem;
            }
            .header .user-info {
                font-size: 0.8rem;
            }
            .header .logout-btn {
                font-size: 0.9rem;
                padding: 3px 8px;
            }
            .main-content {
                padding: calc(var(--header-height) + 15px) 15px 15px 15px;
            }
            .pagination a, .pagination span {
                padding: 6px 10px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <button class="sidebar-toggle" id="sidebarToggle">
            <i class="fas fa-bars"></i>
        </button>
        <div class="logo"></div>
        <div class="user-info">
            <span class="username"><i class="fas fa-user-circle user-icon"></i> <?php echo $loggedInNamaInstansi; ?></span>
            <a href="../jejaring_logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            Menu Jejaring
        </div>
            <ul>
                <li><a href="../"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
                <li><a href="../change_password.php"><i class="fas fa-key"></i> Ubah Kata Sandi</a></li>
                <li>
                    <a href="#" class="dropdown-btn active">
                        <i class="fas fa-file-alt"></i> Laporan
                        <i class="fas fa-caret-down"></i>
                    </a>
                    <div class="dropdown-container show">
                        <a href="#"  class="active"><i class="fas fa-baby"></i> Laporan Kehamilan</a>
                        <a href="../ptm_entry.php"><i class="fas fa-heartbeat"></i> Laporan PTM</a>
                        <a href="../tb_entry.php"><i class="fas fa-lungs"></i> Entri Terduga TB</a>
                        <a href="../kb_entry.php"><i class="fas fa-restroom"></i> Entri KB</a>
                    </div>
                </li>
            </ul>
    </aside>

    <main class="main-content" id="mainContent">
        <h2><?php echo $pageTitle; ?></h2>

        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert success-message">
                <?php echo $_SESSION['success_message']; ?>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert error-message">
                <?php echo $_SESSION['error_message']; ?>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <div class="report-button-container">
            <button id="openReportModal" class="report-button">
                <i class="fas fa-plus-circle"></i> Laporkan Ibu Hamil Baru
            </button>
        </div>

        <?php if (!empty($error_message)): ?>
            <div class="alert error-message"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <div class="table-container">
            <?php if ($total_records == 0): ?>
                <p class="no-data-message">Belum ada laporan kehamilan yang tersedia untuk bulan ini.</p>
            <?php else: ?>
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>No.</th>
                            <th>Nama Ibu Hamil</th>
                            <th>NIK</th>
                            <th>Alamat</th>
                            <th>HPHT</th>
                            <th>Tidak Haid (Hari)</th>
                            <th>Tanggal Lapor</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $start_number = ($current_page - 1) * $records_per_page + 1;
                        foreach ($laporan_kehamilan as $laporan):
                        ?>
                            <tr>
                                <td><?php echo $start_number++; ?></td>
                                <td><?php echo htmlspecialchars($laporan['nama']); ?></td>
                                <td><?php echo htmlspecialchars($laporan['nik']); ?></td>
                                <td><?php echo htmlspecialchars($laporan['alamat'] . ', RT ' . $laporan['rt'] . '/RW ' . $laporan['rw'] . ', ' . $laporan['desa']); ?></td>
                                <td><?php echo formatDateIndonesian($laporan['hpht']); ?></td>
                                <td><?php echo htmlspecialchars($laporan['hari_tidak_haid'] ?? '-'); ?></td>
                                <td><?php echo formatDateIndonesian($laporan['tanggal_lapor']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div class="pagination">
                    <?php if ($current_page > 1): ?>
                        <a href="?page=<?php echo $current_page - 1; ?>">Previous</a>
                    <?php else: ?>
                        <span class="disabled">Previous</span>
                    <?php endif; ?>

                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <a href="?page=<?php echo $i; ?>" class="<?php echo ($i == $current_page) ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>

                    <?php if ($current_page < $total_pages): ?>
                        <a href="?page=<?php echo $current_page + 1; ?>">Next</a>
                    <?php else: ?>
                        <span class="disabled">Next</span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </main>

    <div id="reportModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3>Laporkan Ibu Hamil Baru</h3>
            <form action="../../api/lapor_kehamilan.php" method="POST">
                <input type="hidden" name="sumber_laporan" value="<?php echo $loggedInNamaInstansi; ?>">

                <div class="form-group">
                    <label for="tanggalLaporInput">Tanggal Lapor:</label>
                    <input type="date" id="tanggalLaporInput" name="tanggal_lapor" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                </div>
                <div class="form-group">
                    <label for="nama_ibu">Nama Ibu Hamil:</label>
                    <input type="text" id="nama" name="nama" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="namasuami">Nama Suami:</label>
                    <input type="text" id="namasuami" name="namasuami" class="form-control">
                </div>
                <div class="form-group">
                    <label for="phone_number">Nomor WA:</label>
                    <input type="text" id="phone_number" name="phone_number" class="form-control">
                </div>
                <div class="form-group">
                    <label for="nik_ibu">NIK:</label>
                    <input type="text" id="nik_ibu" name="nik_ibu" class="form-control" pattern="\d{16}" title="NIK harus 16 digit angka" required>
                </div>
                <div class="form-group">
                    <label for="alamat">Alamat:</label>
                    <textarea id="alamat" name="alamat" class="form-control" required></textarea>
                </div>
                <div class="form-group">
                    <label for="desa">Desa:</label>
                    <select id="desa" name="desa" class="form-control" required>
                        <option value="">-- Pilih Desa --</option>
                        <option value="RONDOKUNING">RONDOKUNING</option>
                        <option value="KREGENAN">KREGENAN</option>
                        <option value="SEMAMPIR">SEMAMPIR</option>
                        <option value="BULU">BULU</option>
                        <option value="SIDOMUKTI">SIDOMUKTI</option>
                        <option value="KRAKSAAN WETAN">KRAKSAAN WETAN</option>
                        <option value="RANGKANG">RANGKANG</option>
                        <option value="KANDANGJATI KULON">KANDANGJATI KULON</option>
                        <option value="KANDANGJATI WETAN">KANDANGJATI WETAN</option>
                        <option value="ALASSUMUR KULON">ALASSUMUR KULON</option>
                        <option value="SUMBERLELE">SUMBERLELE</option>
                        <option value="TAMANSARI">TAMANSARI</option>
                        <option value="ASEMBAKOR">ASEMBAKOR</option>
                        <option value="KEBONAGUNG">KEBONAGUNG</option>
                        <option value="SIDOPEKSO">SIDOPEKSO</option>
                        <option value="PATOKAN">PATOKAN</option>
                        <option value="ASEMBAGUS">ASEMBAGUS</option>
                        <option value="KALIBUNTU">KALIBUNTU</option>
                        <option value="LUAR WILAYAH">LUAR WILAYAH KRAKSAAN</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="rt">RT:</label>
                    <input type="number" id="rt" name="rt" class="form-control" min="0" required>
                </div>
                <div class="form-group">
                    <label for="rw">RW:</label>
                    <input type="number" id="rw" name="rw" class="form-control" min="0" required>
                </div>
                <div class="form-group">
                    <label for="hphtInput">HPHT (Hari Pertama Haid Terakhir):</label>
                    <input type="date" id="hphtInput" name="hpht" class="form-control" max="<?php echo date('Y-m-d'); ?>" required>
                </div>
                <div class="form-group">
                    <label>Usia Kehamilan (Otomatis):</label>
                    <span id="usiaKehamilanHariDisplay">-</span> hari
                    <input type="hidden" id="usiaKehamilanHariHidden" name="usia_kehamilan_hari">
                </div>
                <input type="hidden" name="sumber_laporan" value="<?php echo $loggedInNamaInstansi; ?>">
                <input type="hidden" name="tanggal_lapor" value="<?php echo date('Y-m-d'); ?>">

                <div class="modal-buttons">
                    <button type="button" class="cancel-btn" id="closeModalButton">Batal</button>
                    <button type="submit" class="submit-btn">Laporkan</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const sidebarToggle = document.getElementById('sidebarToggle');
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('mainContent');
            const dropdownBtn = document.querySelector('.dropdown-btn');
            const dropdownContainer = document.querySelector('.dropdown-container');

            // Modal elements
            const openReportModalBtn = document.getElementById('openReportModal');
            const reportModal = document.getElementById('reportModal');
            const closeModalBtn = document.querySelector('.close-button');
            const cancelModalBtn = document.getElementById('closeModalButton');
            const hphtInput = document.getElementById('hphtInput');
            const usiaKehamilanHariDisplay = document.getElementById('usiaKehamilanHariDisplay');
            const usiaKehamilanHariHidden = document.getElementById('usiaKehamilanHariHidden');

            // Fungsi utama untuk toggle sidebar
            function toggleSidebar() {
                if (window.innerWidth <= 768) {
                    sidebar.classList.toggle('show');
                    sidebarToggle.classList.toggle('shifted');
                } else {
                    sidebar.classList.toggle('hide');
                    mainContent.classList.toggle('shift');
                    sidebarToggle.classList.toggle('shifted');
                }
            }
            
            // Atur status awal sidebar saat halaman dimuat
            function setInitialSidebarState() {
                if (window.innerWidth > 768) {
                    sidebar.classList.remove('show');
                    sidebar.classList.remove('hide');
                    mainContent.classList.remove('shift');
                    sidebarToggle.classList.remove('shifted');
                } else {
                    sidebar.classList.add('hide');
                    sidebar.classList.remove('show');
                    mainContent.classList.add('shift');
                    sidebarToggle.classList.add('shifted');
                }
            }

            setInitialSidebarState();
            window.addEventListener('resize', setInitialSidebarState);

            sidebarToggle.addEventListener('click', toggleSidebar);

            const sidebarLinks = document.querySelectorAll('.sidebar ul li a');
            sidebarLinks.forEach(link => {
                link.addEventListener('click', function() {
                    if (window.innerWidth <= 768) {
                        if (!this.classList.contains('dropdown-btn')) {
                            sidebar.classList.remove('show');
                            sidebarToggle.classList.remove('shifted');
                        }
                    }
                });
            });

            // Dropdown Functionality
            if (dropdownBtn) {
                dropdownBtn.addEventListener('click', function(event) {
                    event.preventDefault();
                    dropdownContainer.classList.toggle('show');
                    this.classList.toggle('active');
                });
            }
            if (dropdownContainer && dropdownContainer.querySelector('a.active')) {
                dropdownContainer.classList.add('show');
                if(dropdownBtn) {
                    dropdownBtn.classList.add('active');
                }
            }


            // --- Modal Functions ---
            function openModal() {
                reportModal.classList.add('show-modal');
                calculateDaysSinceHPHT();
            }

            function closeModal() {
                reportModal.classList.remove('show-modal');
                document.querySelector('#reportModal form').reset();
                usiaKehamilanHariDisplay.textContent = "-";
                usiaKehamilanHariHidden.value = "";
            }

            // Event listeners for modal
            openReportModalBtn.addEventListener('click', openModal);
            closeModalBtn.addEventListener('click', closeModal);
            cancelModalBtn.addEventListener('click', closeModal);

            // Close modal when clicking outside of the modal content
            window.addEventListener('click', function(event) {
                if (event.target == reportModal) {
                    closeModal();
                }
            });

            // --- HPHT Calculation ---
            function calculateDaysSinceHPHT() {
                if (hphtInput.value) {
                    const hphtDate = new Date(hphtInput.value);
                    const today = new Date();
                    hphtDate.setHours(0, 0, 0, 0);
                    today.setHours(0, 0, 0, 0);

                    const diffTime = today - hphtDate;
                    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

                    if (diffDays >= 0) {
                        usiaKehamilanHariDisplay.textContent = diffDays + " hari";
                        usiaKehamilanHariHidden.value = diffDays;
                    } else {
                        usiaKehamilanHariDisplay.textContent = "HPHT tidak valid (tanggal di masa depan)";
                        usiaKehamilanHariHidden.value = "";
                    }
                } else {
                    usiaKehamilanHariDisplay.textContent = "-";
                    usiaKehamilanHariHidden.value = "";
                }
            }

            // Listen for changes on HPHT input
            hphtInput.addEventListener('change', calculateDaysSinceHPHT);
        });
    </script>
</body>
</html>