<?php
// Proteksi Admin Superadmin + Operator
require_once "../includes/header_admin.php";
?>
<link rel="stylesheet" href="/presensi_v1/assets/css/style.css">

<div class="container-fluid dashboard-wrapper">

    <!-- ========================== TOP STAT CARDS ========================== -->
    <div class="row g-4 mb-4">

        <div class="col-6 col-md-3">
            <div class="matrix-card matrix-blue shadow-sm">
                <div class="matrix-icon"><i class="bi bi-people"></i></div>
                <small class="text-muted">Total Siswa</small>
                <h3 id="card-total" class="mb-0">0</h3>
            </div>
        </div>

        <div class="col-6 col-md-3">
            <div class="matrix-card matrix-green shadow-sm">
                <div class="matrix-icon"><i class="bi bi-check2-circle"></i></div>
                <small class="fw-bold text-success">Hadir</small>
                <h3 id="card-hadir" class="mb-0 text-success">0</h3>
                <small id="card-hadir-persen" class="text-muted"></small>
            </div>
        </div>

        <div class="col-6 col-md-3">
            <div class="matrix-card matrix-orange shadow-sm">
                <div class="matrix-icon"><i class="bi bi-alarm"></i></div>
                <small class="fw-bold text-warning">Terlambat</small>
                <h3 id="card-telat" class="mb-0 text-warning">0</h3>
                <small id="card-telat-persen" class="text-muted"></small>
            </div>
        </div>

        <div class="col-6 col-md-3">
            <div class="matrix-card matrix-red shadow-sm">
                <div class="matrix-icon"><i class="bi bi-x-circle"></i></div>
                <small class="fw-bold text-danger">Alpha</small>
                <h3 id="card-alpha" class="mb-0 text-danger">0</h3>
                <small id="card-alpha-persen" class="text-muted"></small>
            </div>
        </div>

    </div>


    <!-- ========================== GRAPH 7 HARI + CALENDAR ========================== -->
    <div class="row g-4 mb-4">

        <div class="col-md-7">
            <div class="card shadow-sm p-4 chart-box-wide matrix-panel">
                <h5 class="fw-semibold mb-3">Rekap 7 Hari</h5>
                <canvas id="chart7"></canvas>
            </div>
        </div>

        <div class="col-md-5">
            <div class="card shadow-sm p-4 calendar-card matrix-panel">
                <div id="calendar-container"></div>
                <div class="tooltip-mini" id="calendar-tooltip"></div>
            </div>
        </div>

    </div>


    <!-- ========================== GRAPH 30 HARI + RECENT ========================== -->
    <div class="row g-4 mb-4">

        <div class="col-md-7">
            <div class="card shadow-sm p-4 chart-box-wide matrix-panel">
                <h5 class="fw-semibold mb-3">Rekap 30 Hari</h5>
                <canvas id="chart30"></canvas>
            </div>
        </div>

        <div class="col-md-5">
            <div class="card shadow-sm p-4 matrix-panel">
                <h5 class="fw-semibold mb-3">Presensi Terbaru</h5>
                <ul id="recent-list" class="list-group list-group-flush small"></ul>
            </div>
        </div>

    </div>

</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
/* ======================================================
   GLOBAL CHART VAR
====================================================== */
let chart7 = null;
let chart30 = null;

/* ======================================================
   BUILD CALENDAR
====================================================== */
function buildCalendar(year, month, holidays) {
    const container = document.getElementById("calendar-container");
    const tooltip = document.getElementById("calendar-tooltip");
    container.innerHTML = "";

    const date = new Date(year, month, 1);
    const monthName = date.toLocaleString('id-ID', { month: 'long', year: 'numeric' });

    const header = `
        <div class="calendar-header">
            <button class="btn-cal-nav" onclick="navCalendar(-1)">‹</button>
            <strong>${monthName}</strong>
            <button class="btn-cal-nav" onclick="navCalendar(1)">›</button>
        </div>
    `;
    container.insertAdjacentHTML("beforeend", header);

    const grid = document.createElement("div");
    grid.className = "full-calendar";

    const weekdayGrid = document.createElement("div");
    weekdayGrid.className = "calendar-grid";

    ["Min","Sen","Sel","Rab","Kam","Jum","Sab"].forEach((d,i)=>{
        const el=document.createElement("div");
        el.className="calendar-day-name " + (i===0?"calendar-sunday":"");
        el.innerText=d;
        weekdayGrid.appendChild(el);
    });

    grid.appendChild(weekdayGrid);

    const monthGrid = document.createElement("div");
    monthGrid.className = "calendar-grid";

    const firstDay = new Date(year, month, 1).getDay();
    const lastDate = new Date(year, month+1, 0).getDate();
    const todayStr = new Date().toISOString().slice(0,10);

    for (let i=0; i<firstDay; i++){
        monthGrid.appendChild(document.createElement("div"));
    }

    for (let d=1; d<=lastDate; d++){
        const fullDate = `${year}-${String(month+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
        const weekday = new Date(fullDate).getDay();
        const holiday = holidays.find(h => h.date === fullDate);

        const cell = document.createElement("div");
        cell.className = "calendar-day";
        if (weekday === 0) cell.classList.add("calendar-sunday");
        if (fullDate === todayStr) cell.classList.add("calendar-today");
        if (holiday) cell.classList.add("calendar-holiday");

        cell.innerText = d;

        cell.addEventListener("mouseenter", ()=>{
            if (holiday){
                tooltip.innerText = holiday.name;
                tooltip.style.display="block";
                tooltip.style.left = (cell.getBoundingClientRect().left)+"px";
                tooltip.style.top = (cell.getBoundingClientRect().top-20)+"px";
            }
        });
        cell.addEventListener("mouseleave", ()=> tooltip.style.display="none");

        monthGrid.appendChild(cell);
    }

    grid.appendChild(monthGrid);
    container.appendChild(grid);
}

let calYear  = new Date().getFullYear();
let calMonth = new Date().getMonth();
let holidaysCache = [];

function navCalendar(offset){
    calMonth += offset;
    if (calMonth < 0){ calMonth = 11; calYear--; }
    if (calMonth > 11){ calMonth = 0; calYear++; }
    buildCalendar(calYear, calMonth, holidaysCache);
}

/* ======================================================
   REFRESH DASHBOARD DATA (AJAX)
====================================================== */
async function refreshDashboard(){
    try {
        const res = await fetch("/presensi_v1/ajax/dashboard_data.php");
        const data = await res.json();

        // UPDATE CARD
        document.getElementById("card-total").innerText  = data.total;
        document.getElementById("card-hadir").innerText  = data.today.H;
        document.getElementById("card-telat").innerText  = data.today.T;
        document.getElementById("card-alpha").innerText  = data.today.alpha;

        const total = data.total;
        document.getElementById("card-hadir-persen").innerText =
            total ? ((data.today.H / total) * 100).toFixed(1) + "%" : "0%";

        document.getElementById("card-telat-persen").innerText =
            total ? ((data.today.T / total) * 100).toFixed(1) + "%" : "0%";

        document.getElementById("card-alpha-persen").innerText =
            total ? ((data.today.alpha / total) * 100).toFixed(1) + "%" : "0%";

        // CHART 7 DAYS
        if (chart7) chart7.destroy();
        chart7 = new Chart(document.getElementById("chart7"), {
            type:'line',
            data:{
                labels:data.trend7.labels,
                datasets:[
                    {label:"Hadir", data:data.trend7.hadir, borderColor:"#28a745", tension:0.35},
                    {label:"Terlambat", data:data.trend7.telat, borderColor:"#fd7e14", tension:0.35},
                    {label:"Alpha", data:data.trend7.alpha, borderColor:"#dc3545", tension:0.35}
                ]
            }
        });

        // CHART 30 DAYS
        if (chart30) chart30.destroy();
        chart30 = new Chart(document.getElementById("chart30"), {
            type:'line',
            data:{
                labels:data.trend30.labels,
                datasets:[
                    {label:"Hadir", data:data.trend30.hadir, borderColor:"#28a745", tension:0.35},
                    {label:"Terlambat", data:data.trend30.telat, borderColor:"#fd7e14", tension:0.35},
                    {label:"Alpha", data:data.trend30.alpha, borderColor:"#dc3545", tension:0.35}
                ]
            }
        });

        // RECENT
        const ul = document.getElementById("recent-list");
        ul.innerHTML = "";
        data.recent.forEach(r=>{
            ul.innerHTML += `
                <li class="list-group-item d-flex justify-content-between align-items-start">
                    <div>
                        <strong>${r.nama ?? 'UID:'+r.uid}</strong><br>
                        <small class="text-muted">NIS: ${r.nis ?? '-'} • ${r.tanggal} ${r.waktu}</small>
                    </div>
                    <span class="badge ${
                        r.keterangan==='H'?'bg-success':
                        (r.keterangan==='T'?'bg-warning text-dark':'bg-danger')
                    }">${r.keterangan}</span>
                </li>
            `;
        });

        holidaysCache = data.holidays;
        buildCalendar(calYear, calMonth, holidaysCache);

    }catch(e){
        console.error(e);
    }
}

refreshDashboard();
setInterval(refreshDashboard, 3000);
</script>

<?php require_once "../includes/footer.php"; ?>
