<?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');
    exit();
}

// Sertakan file koneksi database dari direktori 'api'
include_once '../api/db_connect.php';

// Data pengguna yang login
$loggedInUsername = htmlspecialchars($_SESSION['jejaring_username']);
$loggedInUserType = htmlspecialchars($_SESSION['jejaring_user_type']);
$loggedInNamaInstansi = htmlspecialchars($_SESSION['jejaring_nama_instansi']);
$pageTitle = "Dashboard " . ($loggedInUserType == 'klinik' ? 'Klinik' : ($loggedInUserType == 'dokter_praktek_mandiri' ? 'Dokter Praktik Mandiri' : 'Jejaring Kesehatan'));

$errorMessage = '';

// Inisialisasi total laporan dan data grafik
$totals = [
    'kehamilan' => 0,
    'ptm' => 0,
    'tb' => 0,
    'kb' => 0
];

$graphData = [
    'labels' => [],
    'datasets' => [
        'kehamilan' => array_fill(0, date('t'), 0),
        'ptm' => array_fill(0, date('t'), 0),
        'tb' => array_fill(0, date('t'), 0),
        'kb' => array_fill(0, date('t'), 0)
    ]
];

$currentMonth = date('m');
$currentYear = date('Y');
$daysInMonth = date('t');

// Inisialisasi label hari di bulan ini
for ($day = 1; $day <= $daysInMonth; $day++) {
    $graphData['labels'][] = sprintf('%02d', $day) . ' ' . date('M');
}

try {
    if (!isset($pdo) || !$pdo instanceof PDO) {
        throw new PDOException("Koneksi database (PDO) tidak tersedia. Periksa db_connect.php.");
    }

    // --- FUNGSI UNTUK MENGAMBIL DATA HARIAN UNTUK GRAFIK ---
    function fetchDailyData($pdo, $table, $loggedInNamaInstansi, $currentYear, $currentMonth, $dateColumn, $sumberColumn = 'sumber_laporan') {
        $query = "SELECT DAY($dateColumn) as hari, COUNT(*) as jumlah
                  FROM $table
                  WHERE $sumberColumn = :sumber_laporan
                  AND YEAR($dateColumn) = :tahun
                  AND MONTH($dateColumn) = :bulan
                  GROUP BY hari";
        
        $stmt = $pdo->prepare($query);
        $stmt->bindValue(':sumber_laporan', $loggedInNamaInstansi, PDO::PARAM_STR);
        $stmt->bindValue(':tahun', $currentYear, PDO::PARAM_INT);
        $stmt->bindValue(':bulan', $currentMonth, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Ambil data untuk setiap tabel dan isi array grafik, dengan nama kolom yang berbeda
    $dailyKehamilan = fetchDailyData($pdo, 'laporan_kehamilan', $loggedInNamaInstansi, $currentYear, $currentMonth, 'tanggal_lapor', 'sumber_laporan');
    foreach ($dailyKehamilan as $data) {
        $graphData['datasets']['kehamilan'][$data['hari'] - 1] = (int)$data['jumlah'];
    }

    $dailyPTM = fetchDailyData($pdo, 'ptm', $loggedInNamaInstansi, $currentYear, $currentMonth, 'tanggal_pemeriksaan');
    foreach ($dailyPTM as $data) {
        $graphData['datasets']['ptm'][$data['hari'] - 1] = (int)$data['jumlah'];
    }

    $dailyTB = fetchDailyData($pdo, 'terduga_tb', $loggedInNamaInstansi, $currentYear, $currentMonth, 'tanggal');
    foreach ($dailyTB as $data) {
        $graphData['datasets']['tb'][$data['hari'] - 1] = (int)$data['jumlah'];
    }

    $dailyKB = fetchDailyData($pdo, 'laporan_kb', $loggedInNamaInstansi, $currentYear, $currentMonth, 'tanggal_kb');
    foreach ($dailyKB as $data) {
        $graphData['datasets']['kb'][$data['hari'] - 1] = (int)$data['jumlah'];
    }

    // --- PENGHITUNGAN TOTAL LAPORAN (Perlu juga disesuaikan kolom tanggalnya jika perlu) ---
    $queryKehamilan = "SELECT COUNT(*) FROM laporan_kehamilan WHERE type_sumber = 'jejaring' AND sumber_laporan = :sumber_laporan";
    $stmt = $pdo->prepare($queryKehamilan);
    $stmt->bindParam(':sumber_laporan', $loggedInNamaInstansi);
    $stmt->execute();
    $totals['kehamilan'] = $stmt->fetchColumn();

    $queryPTM = "SELECT COUNT(*) FROM ptm WHERE sumber_laporan = :sumber_laporan";
    $stmt = $pdo->prepare($queryPTM);
    $stmt->bindParam(':sumber_laporan', $loggedInNamaInstansi);
    $stmt->execute();
    $totals['ptm'] = $stmt->fetchColumn();

    $queryTB = "SELECT COUNT(*) FROM terduga_tb WHERE sumber_laporan = :sumber_laporan";
    $stmt = $pdo->prepare($queryTB);
    $stmt->bindParam(':sumber_laporan', $loggedInNamaInstansi);
    $stmt->execute();
    $totals['tb'] = $stmt->fetchColumn();

    $queryKB = "SELECT COUNT(*) FROM laporan_kb WHERE sumber_laporan = :sumber_laporan";
    $stmt = $pdo->prepare($queryKB);
    $stmt->bindParam(':sumber_laporan', $loggedInNamaInstansi);
    $stmt->execute();
    $totals['kb'] = $stmt->fetchColumn();

} catch (PDOException $e) {
    $errorMessage = "Terjadi kesalahan database: " . $e->getMessage();
    $totals = array_fill_keys(array_keys($totals), "N/A");
    $graphData = ['labels' => [], 'datasets' => []];
}

$jsonData = json_encode($graphData);

// Konten untuk bagian home dashboard
ob_start();
?>
    <h2>Selamat Datang, <?php echo $loggedInNamaInstansi; ?>!</h2>
    <p>Ini adalah halaman dashboard Anda. Anda login sebagai <strong><?php echo ucfirst(str_replace('_', ' ', $loggedInUserType)); ?></strong>.</p>
    <p>Gunakan menu di samping untuk navigasi.</p>

    <?php if (!empty($errorMessage)): ?>
        <div style="background-color: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
            <?php echo $errorMessage; ?>
        </div>
    <?php endif; ?>

    <div class="card-container">
        <div class="card" style="border-left-color: #ff6384;">
            <h3>Laporan Kehamilan</h3>
            <p class="card-value"><?php echo $totals['kehamilan']; ?></p>
            <p class="card-desc">Total Laporan</p>
        </div>
        <div class="card" style="border-left-color: #36a2eb;">
            <h3>Laporan PTM</h3>
            <p class="card-value"><?php echo $totals['ptm']; ?></p>
            <p class="card-desc">Total Laporan</p>
        </div>
        <div class="card" style="border-left-color: #ffcd56;">
            <h3>Laporan Terduga TB</h3>
            <p class="card-value"><?php echo $totals['tb']; ?></p>
            <p class="card-desc">Total Laporan</p>
        </div>
        <div class="card" style="border-left-color: #4bc0c0;">
            <h3>Laporan KB</h3>
            <p class="card-value"><?php echo $totals['kb']; ?></p>
            <p class="card-desc">Total Laporan</p>
        </div>
    </div>
    
    <div class="card full-width-card" style="grid-column: 1 / -1; border-left: none;">
        <h3>Grafik Laporan Harian Bulan Ini</h3>
        <div style="width: 100%; height: 350px;">
            <canvas id="dailyReportChart"></canvas>
        </div>
    </div>
<?php
$mainContent = ob_get_clean();
?>

<!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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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 {
            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;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
            z-index: 1000;
        }
        .header .logo {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--secondary-color);
        }
        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .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;
        }
        .sidebar.hide {
            transform: translateX(calc(-1 * var(--sidebar-width)));
        }
        .sidebar.show {
            transform: translateX(0);
        }
        .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;
        }
        .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 {
            margin-left: var(--sidebar-width);
            padding: calc(var(--header-height) + 30px) 30px 30px 30px;
            flex-grow: 1;
            transition: margin-left 0.3s ease;
            width: calc(100% - var(--sidebar-width));
        }
        .main-content.shift {
            margin-left: 0;
            width: 100%;
        }
        .sidebar-toggle {
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            padding: 8px 12px;
            cursor: pointer;
            z-index: 1001;
            font-size: 1.2rem;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .sidebar-toggle:hover {
            background-color: #3e8d22;
        }
        /* Menggunakan Grid untuk desktop */
        .card-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }
        .card {
            background-color: #fff;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.08);
            text-align: center;
            border-left: 5px solid var(--primary-color);
        }
        .card h3 {
            margin-top: 0;
            color: var(--secondary-color);
            font-size: 1.2rem;
            font-weight: 600;
        }
        .card-value {
            font-size: 2.5rem;
            font-weight: 700;
            color: var(--primary-color);
            margin: 10px 0;
        }
        .card-desc {
            font-size: 0.9rem;
            color: #777;
        }
        .full-width-card {
            margin-top: 20px;
        }
        /* Responsiveness */
        @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;
            }
            .main-content.shift {
                margin-left: 0;
            }
            .header {
                justify-content: space-between;
                padding: 0 15px;
            }
            .header .logo {
                display: none;
            }
            .header-right {
                order: 2;
            }
            .sidebar-toggle {
                order: 1;
            }

            /* Perbaikan untuk Mobile: Card */
            .card-container {
                display: grid;
                grid-template-columns: repeat(2, 1fr); /* Tampilkan 2 card per baris */
                gap: 15px;
                margin-top: 20px;
            }
            .card h3 {
                font-size: 1rem;
            }
            .card-value {
                font-size: 2rem;
            }
            .card-desc {
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <button class="sidebar-toggle" id="sidebarToggle">
            <i class="fas fa-bars"></i>
        </button>
        <div class="header-right">
            <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>
    </div>
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            Menu Jejaring
        </div>
            <ul>
                <li><a href="#" class="active"><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">
                        <i class="fas fa-file-alt"></i> Laporan
                        <i class="fas fa-caret-down"></i>
                    </a>
                    <div class="dropdown-container">
                        <a href="kehamilan/"><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">
        <?php echo $mainContent; ?>
    </main>
    <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');

            function toggleSidebar() {
                if (window.innerWidth <= 768) {
                    sidebar.classList.toggle('show');
                } else {
                    sidebar.classList.toggle('hide');
                    mainContent.classList.toggle('shift');
                }
            }
            
            function setInitialSidebarState() {
                if (window.innerWidth > 768) {
                    sidebar.classList.remove('show');
                    sidebar.classList.remove('hide');
                    mainContent.classList.remove('shift');
                } else {
                    sidebar.classList.remove('show');
                    sidebar.classList.add('hide'); 
                    mainContent.classList.remove('shift');
                }
            }

            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');
                        }
                    }
                });
            });

            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');
                }
            }
            
            const graphData = <?php echo $jsonData; ?>;

            if (graphData.labels && graphData.labels.length > 0) {
                const ctx = document.getElementById('dailyReportChart').getContext('2d');
                const datasets = [
                    {
                        label: 'Laporan Kehamilan',
                        data: graphData.datasets.kehamilan,
                        backgroundColor: '#ff6384',
                        borderColor: '#ff6384',
                        borderWidth: 1,
                        type: 'line',
                        fill: false
                    },
                    {
                        label: 'Laporan PTM',
                        data: graphData.datasets.ptm,
                        backgroundColor: '#36a2eb',
                        borderColor: '#36a2eb',
                        borderWidth: 1,
                        type: 'line',
                        fill: false
                    },
                    {
                        label: 'Laporan Terduga TB',
                        data: graphData.datasets.tb,
                        backgroundColor: '#ffcd56',
                        borderColor: '#ffcd56',
                        borderWidth: 1,
                        type: 'line',
                        fill: false
                    },
                    {
                        label: 'Laporan KB',
                        data: graphData.datasets.kb,
                        backgroundColor: '#4bc0c0',
                        borderColor: '#4bc0c0',
                        borderWidth: 1,
                        type: 'line',
                        fill: false
                    }
                ];

                const dailyReportChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: graphData.labels,
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Jumlah Laporan'
                                },
                                ticks: {
                                    stepSize: 1
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: 'Tanggal'
                                }
                            }
                        },
                        plugins: {
                            title: {
                                display: true,
                                text: 'Grafik Laporan Harian Bulan Ini',
                                font: {
                                    size: 16
                                }
                            }
                        }
                    }
                });
            } else {
                const chartContainer = document.getElementById('dailyReportChart').parentNode;
                chartContainer.innerHTML = '<p style="text-align: center; color: #777; margin-top: 50px;">Tidak ada data laporan untuk bulan ini.</p>';
            }
        });
    </script>
</body>
</html>