<?php
include '../db.php';
session_start();

// Cek apakah admin sudah login
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Pastikan variabel koneksi database `$conn` digunakan
if (!isset($conn)) {
    die("Koneksi database tidak ditemukan.");
}

// Cek apakah data admin tersedia di sesi
$admin = isset($_SESSION['admin_data']) ? $_SESSION['admin_data'] : ['username' => 'Admin'];

// Query untuk mendapatkan status dan jumlah dari tabel `reservations`
$query = "SELECT status, COUNT(*) as count FROM reservations GROUP BY status";
$result = $conn->query($query);

// --- Hitung statistik ----------------------------------------------------
$statusCounts = [
    'Disetujui' => 0,
    'Ditolak'   => 0,
    'Pending'   => 0,
];

$statStmt = $conn->query("SELECT status, COUNT(*) AS total FROM reservations GROUP BY status");
while ($row = $statStmt->fetch_assoc()) {
    $key = ucfirst(strtolower($row['status']));
    if (isset($statusCounts[$key])) {
        $statusCounts[$key] = (int) $row['total'];
    }
}

$totalReservasi = array_sum($statusCounts);
$totalApproved  = $statusCounts['Disetujui'];
$totalRejected  = $statusCounts['Ditolak'];
$totalPending   = $statusCounts['Pending'];

$labelsJSON = json_encode(array_keys($statusCounts));
$dataJSON   = json_encode(array_values($statusCounts));

// Siapkan array untuk data status dan jumlahnya
$data = [];
$labels = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $labels[] = $row['status'];
        $data[] = $row['count'];
    }
}

// Encode data untuk digunakan di JavaScript
$labelsJSON = json_encode($labels);
$dataJSON = json_encode($data);
?>

<!DOCTYPE html>
<html lang="id" data-bs-theme="light">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Dashboard Admin</title>
    <!-- Google Font & Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet" />
    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="icon" href="../assets/img/logotng.png" type="image/x-icon" />
    <style>
        :root {
            --navy: #002147;
            --navy-dark: #001531;
            --accent: #f0ad4e;
            --sidebar-width: 260px;
            --sidebar-collapsed: 80px;
            --navbar-height: 56px;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: #f4f6fb;
            overflow-x: hidden;
            transition: margin-left .3s;
        }

        /* ----- Sidebar ------ */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: var(--sidebar-width);
            background: linear-gradient(180deg, var(--navy)0%, var(--navy-dark)100%);
            color: #fff;
            padding: 20px 0;
            transition: width .3s;
        }

        .sidebar.collapsed {
            width: var(--sidebar-collapsed)
        }

        .sidebar h5 {
            font-weight: 600;
            text-align: center;
            margin-bottom: 1.5rem;
            transition: opacity .3s
        }

        .sidebar.collapsed h5 {
            opacity: 0
        }

        .sidebar a {
            color: #fff;
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 22px;
            border-radius: 6px;
            text-decoration: none !important;
            margin: 4px 8px;
            font-weight: 500;
            white-space: nowrap;
            transition: background .2s
        }

        .sidebar a i {
            min-width: 22px;
            text-decoration: none !important;
            text-align: center;
            font-size: 1rem
        }

        .sidebar.collapsed a span {
            display: none
        }

        .sidebar a.active,
        .sidebar a:hover {
            background-color: rgba(240, 173, 78, .18);
            text-decoration: none
        }

        /* ----- Navbar ------ */
        .navbar {
            background: var(--navy);
            padding: .5rem 1rem;
            height: var(--navbar-height);
            transition: margin-left .3s
        }

        .navbar .nav-link {
            color: #fff;
            font-weight: 500
        }

        .navbar .nav-link:hover {
            color: var(--accent)
        }

        /* ----- Content ------ */
        .content {
            margin-left: var(--sidebar-width);
            padding: calc(var(--navbar-height) + 1.5rem) 2rem 4rem;
            transition: margin-left .3s;
        }

        body.sidebar-collapsed .navbar {
            margin-left: var(--sidebar-collapsed)
        }

        body.sidebar-collapsed .content {
            margin-left: var(--sidebar-collapsed)
        }

        .card-shadow {
            border: none;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, .05)
        }

        .chart-wrapper {
            position: relative;
            height: 360px
        }

        @media(max-width:768px) {
            .sidebar {
                left: -260px
            }

            .sidebar.collapsed {
                left: 0
            }

            .navbar,
            .content {
                margin-left: 0
            }

            body.sidebar-collapsed .navbar {
                margin-left: 0
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <aside id="sidebar" class="sidebar">
        <h5><i class="fas fa-building me-1"></i><span class="sidebar-title"></span></h5>
        <a href="dashboard_admin.php" class="active"><i class="fas fa-home"></i> <span>Dashboard</span></a>
        <a href="kelola_reserv.php"><i class="fas fa-table"></i> <span>Data Reservasi</span></a>
        <a href="kelola_tempat.php"><i class="fas fa-map-marker-alt"></i> <span>Kelola Tempat</span></a>
        <a href="calendar.php"><i class="fas fa-calendar"></i> <span>Kalender</span></a>
        <a href="logout_admin.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
    </aside>

    <!-- Navbar -->
    <nav class="navbar fixed-top navbar-dark shadow-sm">
        <div class="container-fluid px-3">
            <!-- Icon buttons on the right -->
            <div class="d-flex align-items-center gap-2 ms-auto">
                <button id="sidebarToggle" class="btn btn-outline-light btn-sm" title="Menu"><i class="fas fa-bars"></i></button>
                <button id="fullscreenToggle" class="btn btn-outline-light btn-sm" title="Fullscreen"><i class="fas fa-expand"></i></button>
                <!-- <a href="dashboard_admin.php" class="btn btn-outline-light btn-sm" title="Back"><i class="fas fa-arrow-left"></i></a> -->
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="content">
        <div class="row g-4">
            <!-- Widget Cards -->
            <div class="col-md-4">
                <div class="card card-shadow text-center py-4">
                    <div class="card-body">
                        <i class="fas fa-users fa-2x text-primary mb-3"></i>
                        <h5 class="card-title">Total Reservasi</h5>
                        <h2 class="fw-bold mb-0"><?= $totalReservasi; ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card card-shadow text-center py-4">
                    <div class="card-body">
                        <i class="fas fa-check-circle fa-2x text-success mb-3"></i>
                        <h5 class="card-title">Disetujui</h5>
                        <h2 class="fw-bold mb-0"><?= $totalApproved; ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card card-shadow text-center py-4">
                    <div class="card-body">
                        <i class="fas fa-times-circle fa-2x text-danger mb-3"></i>
                        <h5 class="card-title">Ditolak</h5>
                        <h2 class="fw-bold mb-0"><?= $totalRejected; ?></h2>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chart Card -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card card-shadow">
                    <div class="card-header bg-white fw-semibold">Statistik Reservasi (Persentase)</div>
                    <div class="card-body chart-wrapper">
                        <canvas id="reservChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0"></script>
    <script>
        // Sidebar toggle
        const sidebar = document.getElementById('sidebar');
        document.getElementById('sidebarToggle').addEventListener('click', () => {
            sidebar.classList.toggle('collapsed');
            document.body.classList.toggle('sidebar-collapsed');
        });

        // Fullscreen toggle
        const fsBtn = document.getElementById('fullscreenToggle');
        fsBtn.addEventListener('click', () => {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen();
                fsBtn.innerHTML = '<i class="fas fa-compress"></i>';
            } else {
                document.exitFullscreen();
                fsBtn.innerHTML = '<i class="fas fa-expand"></i>';
            }
        });

        // Data PHP ke JS
        const labels = <?= $labelsJSON; ?>; // ['Disetujui','Ditolak','Pending']
        const dataStatus = <?= $dataJSON; ?>; // [10,5,3]

        // Generate colors with opacity
        const bgColors = [
            'rgba(0, 166, 90, 0.7)',
            'rgba(245, 105, 84, 0.7)',
            'rgba(0, 192, 239, 0.7)'
        ];

        const ctx = document.getElementById('reservChart');
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: dataStatus,
                    backgroundColor: bgColors,
                    hoverOffset: 6,
                    borderWidth: 1,
                    borderColor: '#fff',
                }]
            },
            options: {
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 18,
                            usePointStyle: true,
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: context => `${context.label}: ${context.formattedValue} reservasi`
                        }
                    }
                },
                animation: {
                    animateScale: true
                }
            }
        });
    </script>
</body>

</html>