<?php
session_start();
date_default_timezone_set('Asia/Jakarta');
include 'koneksi.php';

// LOGIN
if(isset($_POST['login'])){
    if($_POST['user']=='admin' && $_POST['pass']=='123'){
        $_SESSION['login'] = true;
    }else{
        $error = "Username / Password salah";
    }
}

// LOGOUT
if(isset($_GET['logout'])){
    session_destroy();
    header("Location: login.php");
    exit;
}

// FILTER
$dari   = $_GET['dari'] ?? date('Y-m-01');
$sampai = $_GET['sampai'] ?? date('Y-m-d');

// PAGE SWITCH
$page = $_GET['page'] ?? 'dashboard';
?>

<!DOCTYPE html>

<html>
<head>
<title>Admin Panel</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>

<style>
body{
    background:#f4f6f9;
    overflow-x:hidden;
}

/* SIDEBAR */
.sidebar{
    width:220px;
    height:100vh;
    position:fixed;
    background:#1e293b;
    padding:20px;
    transition:0.3s;
    z-index:999;
}

.sidebar a{
    display:flex;
    align-items:center;
    gap:10px;
    color:#cbd5e1;
    padding:12px;
    border-radius:10px;
    text-decoration:none;
    margin-bottom:30px;
    transition:0.3s;
}

.sidebar a:hover{
    background:#334155;
    color:white;
}

.sidebar a.active{
    background:#3b82f6;
    color:white;
}

.sidebar.collapsed{
    width:70px;
}

.sidebar.collapsed span{
    display:none;
}

.content{
    margin-left:220px;
    padding:20px;
    transition:0.3s;
}

.content.expanded{
    margin-left:70px;
}

.toggle-btn{
    position:fixed;
    top:15px;
    left:230px;
    z-index:1000;
    transition:0.3s;
}

.sidebar.collapsed ~ .toggle-btn{
    left:80px;
}

.card{
    border:none;
    border-radius:15px;
}

/* MOBILE */
@media(max-width:768px){

.sidebar{
    left:-220px;
}

.sidebar.show{
    left:0;
}

.content{
    margin-left:0;
}

.content.expanded{
    margin-left:0;
}

.toggle-btn{
    left:10px !important;
}

}

/* ========================= */
/* PREMIUM UI */
/* ========================= */

*{
    transition:0.2s ease;
}

.card{
    border:none;
    border-radius:18px;
    box-shadow:0 4px 20px rgba(0,0,0,0.06);
}

.card:hover{
    transform:translateY(-2px);
    box-shadow:0 8px 25px rgba(0,0,0,0.08);
}

.sidebar{
    background:linear-gradient(180deg,#0f172a,#1e293b);
}

.sidebar a.active{
    background:#3b82f6;
    box-shadow:0 4px 15px rgba(59,130,246,0.4);
}

.btn{
    border-radius:12px;
    font-weight:600;
}

canvas{
    max-width:100% !important;
    animation:fadein .5s ease;
}

.chart-container{
    position:relative;
    height:850px;
}

@media(max-width:768px){

.chart-container{
    height:420px;
}

.content{
    padding:12px;
}

.card{
    border-radius:14px;
}

h3{
    font-size:22px;
}

h5{
    font-size:16px;
}

}

@keyframes fadein{
from{
opacity:0;
transform:translateY(10px);
}
to{
opacity:1;
transform:translateY(0);
}
}

::-webkit-scrollbar{
    width:8px;
}

::-webkit-scrollbar-thumb{
    background:#94a3b8;
    border-radius:10px;
}

::-webkit-scrollbar-track{
    background:#e2e8f0;
}

#overlay{
    position:fixed;
    inset:0;
    background:rgba(0,0,0,0.4);
    z-index:998;
    display:none;
}

#overlay.show{
    display:block;
}

</style>

</head>

<body>

<?php if(!isset($_SESSION['login'])): ?>


<!-- LOGIN -->

<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-4">

<div class="card p-4 shadow-sm">
<h4 class="text-center mb-3">🔐 Login Admin</h4>

<?php if(isset($error)): ?>

<div class="alert alert-danger"><?=$error?></div>
<?php endif; ?>

<form method="POST">
<input type="text" name="user" class="form-control mb-2" placeholder="Username">
<input type="password" name="pass" class="form-control mb-3" placeholder="Password">

<button name="login" class="btn btn-success w-100 mb-2">Login</button> <a href="hal_kehadiran.php" class="btn btn-danger w-100">Kembali</a>

</form>

</div>

</div>
</div>
</div>

<?php else: ?>

<!-- SIDEBAR -->

<div id="sidebar" class="sidebar">

<h4 class="text-white mb-4">
<i class="fa fa-chart-line"></i> <span>Admin</span>
</h4>

<a href="login.php?page=export" class="<?= $page=='export'?'active':'' ?>">
<i class="fa fa-file-export"></i> <span>Absensi</span>
</a>

<a href="login.php?page=persentase" class="<?= $page=='persentase'?'active':'' ?>">
<i class="fa fa-chart-pie"></i> <span>Persentase</span>
</a>

<a href="login.php?page=grafik.kehadiran" class="<?= $page=='grafik.kehadiran'?'active':'' ?>">
<i class="fa fa-chart-column"></i> <span>Grafik Kehadiran</span>
</a>

<a href="login.php?page=grafik.keterlambatan" class="<?= $page=='grafik.keterlambatan'?'active':'' ?>">
<i class="fa fa-chart-column"></i> <span>Grafik Keterlambatan</span>
</a>

<hr style="border-color:#475569;">

<a href="?logout=1" class="text-danger">
<i class="fa fa-sign-out-alt"></i> <span>Logout</span>
</a>

</div>

<button id="toggleBtn" class="btn btn-primary toggle-btn">
<i class="fa fa-bars"></i>
</button>


<!-- CONTENT -->

<div id="content" class="content">

<?php if($page=='dashboard'): ?>

<h3 class="mb-4">Dashboard Admin</h3>

<div class="row">

<?php
$total_siswa = $koneksi->query("SELECT COUNT(*) as j FROM data_siswa")->fetch_assoc()['j'];
$total_hadir = $koneksi->query("SELECT COUNT(*) as j FROM kehadiran")->fetch_assoc()['j'];
$total_telat = $koneksi->query("SELECT COUNT(*) as j FROM keterlambatan")->fetch_assoc()['j'];
?>

<div class="col-md-4 mb-4">
<div class="card shadow-sm p-4 bg-primary text-white">
<h5>Total Siswa</h5>
<h2><?= $total_siswa ?></h2>
</div>
</div>

<div class="col-md-4 mb-4">
<div class="card shadow-sm p-4 bg-success text-white">
<h5>Total Kehadiran</h5>
<h2><?= $total_hadir ?></h2>
</div>
</div>

<div class="col-md-4 mb-4">
<div class="card shadow-sm p-4 bg-danger text-white">
<h5>Total Keterlambatan</h5>
<h2><?= $total_telat ?></h2>
</div>
</div>

</div>

<?php endif; ?>

<?php if($page=='export'): ?>

<h4 class="mb-4">Absensi</h4>

<div class="card shadow-sm p-4 mb-4">
<form method="GET" class="row g-3">

<input type="hidden" name="page" value="export">

<div class="col-md-4">
<label class="form-label">Dari Tanggal</label>
<input type="date" name="dari" value="<?=$dari?>" class="form-control">
</div>

<div class="col-md-4">
<label class="form-label">Sampai Tanggal</label>
<input type="date" name="sampai" value="<?=$sampai?>" class="form-control">
</div>

<div class="col-md-4 d-flex align-items-end">
<button class="btn btn-primary w-100">
<i class="fa fa-filter"></i> Filter
</button>
</div>

</form>
</div>

<a href="export_kehadiran.php?dari=<?=$dari?>&sampai=<?=$sampai?>" class="btn btn-success mb-4">
<i class="fa fa-file-excel"></i> Export Kehadiran
</a>

<a href="export_keterlambatan.php?dari=<?=$dari?>&sampai=<?=$sampai?>" class="btn btn-danger mb-4">
<i class="fa fa-file-excel"></i> Export Keterlambatan
</a>


<!-- EXPORT -->
<?php
$sakit = $koneksi->query("SELECT COUNT(*) as j FROM kehadiran WHERE tanggal BETWEEN '$dari' AND '$sampai' AND keterangan='Sakit'")->fetch_assoc()['j'] ?? 0;
$alpha = $koneksi->query("SELECT COUNT(*) as j FROM kehadiran WHERE tanggal BETWEEN '$dari' AND '$sampai' AND keterangan='Alpha'")->fetch_assoc()['j'] ?? 0;
$izin = $koneksi->query("SELECT COUNT(*) as j FROM kehadiran WHERE tanggal BETWEEN '$dari' AND '$sampai' AND keterangan='Izin'")->fetch_assoc()['j'] ?? 0;
$telat = $koneksi->query("SELECT COUNT(*) as j FROM keterlambatan WHERE tanggal BETWEEN '$dari' AND '$sampai'")->fetch_assoc()['j'] ?? 0;
?>

<div class="row">
<div class="col-md-3 mb-3">
<div class="card shadow-sm p-4 bg-warning text-white">
<h5>Sakit</h5>
<h2><?=$sakit?></h2>
</div>
</div>

<div class="col-md-3 mb-3">
<div class="card shadow-sm p-4 bg-danger text-white">
<h5>Alpha</h5>
<h2><?=$alpha?></h2>
</div>
</div>

<div class="col-md-3 mb-3">
<div class="card shadow-sm p-4 bg-info text-white">
<h5>Izin</h5>
<h2><?=$izin?></h2>
</div>
</div>

<div class="col-md-3 mb-3">
<div class="card shadow-sm p-4 bg-dark text-white">
<h5>Telat</h5>
<h2><?=$telat?></h2>
</div>
</div>
</div>

<?php endif; ?>


<!-- PERSENTASE -->

<?php if($page=='persentase'): ?>

<h3 class="mb-4">
    <i class="fa fa-chart-pie"></i>
    Persentase Kehadiran Jurusan
</h3>

<div class="d-flex gap-2 flex-wrap mb-4">

    <button class="btn btn-success shadow-sm px-4 py-2 rounded-3"
            onclick="exportSemuaGrafik()">

        <i class="bi bi-download"></i>
        Export Semua Grafik

    </button>

</div>

<?php

// DATA PERSENTASE JURUSAN
$jurusan = [];
$persentase = [];

$total_persen = 0;
$total_jurusan = 0;

$jurusan_terbaik = '-';
$jurusan_terendah = '-';

$nilai_terbaik = 0;
$nilai_terendah = 100;

$q = $koneksi->query("

SELECT

s.jurusan,

COUNT(DISTINCT s.id) as total_siswa,

COUNT(DISTINCT CASE
WHEN k.keterangan='Alpha'
THEN s.id
END) as alpha,

COUNT(DISTINCT CASE
WHEN k.keterangan='Sakit'
THEN s.id
END) as sakit,

COUNT(DISTINCT CASE
WHEN k.keterangan='Izin'
THEN s.id
END) as izin,

COUNT(DISTINCT CASE
WHEN k.keterangan IN ('Alpha','Sakit','Izin')
THEN s.id
END) as tidak_hadir

FROM data_siswa s

LEFT JOIN kehadiran k
ON s.id = k.siswa_id
AND k.tanggal BETWEEN '$dari' AND '$sampai'
GROUP BY s.jurusan

ORDER BY s.jurusan ASC

");

$data_jurusan = [];

while($d = $q->fetch_assoc()){

    $tidak_hadir = $d['tidak_hadir'];

    $hadir =
        $d['total_siswa']
        - $tidak_hadir;

    $persen = 0;

    if($d['total_siswa'] > 0){
        $persen =
        ($hadir / $d['total_siswa']) * 100;
    }

    $persen = round($persen,1);

    $jurusan[] = $d['jurusan'];
    $persentase[] = $persen;

    $total_persen += $persen;
    $total_jurusan++;

    if($persen > $nilai_terbaik){
        $nilai_terbaik = $persen;
        $jurusan_terbaik = $d['jurusan'];
    }

    if($persen < $nilai_terendah){
        $nilai_terendah = $persen;
        $jurusan_terendah = $d['jurusan'];
    }

    $data_jurusan[] = [
        'jurusan' => $d['jurusan'],
        'persen' => $persen
    ];
}

$rata_sekolah = 0;

if($total_jurusan > 0){
    $rata_sekolah =
    round($total_persen / $total_jurusan,1);
}

// SORT RANKING
usort($data_jurusan, function($a,$b){
    return $b['persen'] <=> $a['persen'];
});

?>

<!-- CARD STATISTIK -->

<div class="row mb-4">

    <div class="col-md-4 mb-3">
        <div class="card shadow-sm p-4 bg-primary text-white">
            <h6>Rata-rata Sekolah</h6>
            <h2><?= $rata_sekolah ?>%</h2>
        </div>
    </div>

    <div class="col-md-4 mb-3">
        <div class="card shadow-sm p-4 bg-success text-white">
            <h6>Jurusan Terbaik</h6>
            <h2><?= $jurusan_terbaik ?></h2>
            <small><?= $nilai_terbaik ?>%</small>
        </div>
    </div>

    <div class="col-md-4 mb-3">
        <div class="card shadow-sm p-4 bg-danger text-white">
            <h6>Jurusan Terendah</h6>
            <h2><?= $jurusan_terendah ?></h2>
            <small><?= $nilai_terendah ?>%</small>
        </div>
    </div>

</div>

<div class="row">

<!-- GRAFIK -->

<div class="col-md-7 mb-4">

<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
    <i class="fa fa-chart-bar"></i>
    Grafik Persentase Kehadiran Jurusan
</h5>

<canvas id="grafikPersentase"></canvas>

</div>

</div>

<!-- RANKING -->

<div class="col-md-5 mb-4">

<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
    <i class="fa fa-ranking-star"></i>
    Ranking Jurusan
</h5>

<?php
$no = 1;

foreach($data_jurusan as $r):

$badge = 'bg-success';

if($r['persen'] < 90){
    $badge = 'bg-warning';
}

if($r['persen'] < 75){
    $badge = 'bg-danger';
}
?>

<div class="d-flex
justify-content-between
align-items-center
mb-3">

<div>
    <b>#<?= $no++ ?></b>
    <?= $r['jurusan'] ?>
</div>

<span class="badge <?= $badge ?> p-2">
    <?= $r['persen'] ?>%
</span>

</div>

<?php endforeach; ?>

</div>

</div>

</div>

<!-- DETAIL PROGRESS -->

<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
    <i class="fa fa-layer-group"></i>
    Detail Persentase Jurusan
</h5>

<?php foreach($data_jurusan as $d):

$warna = 'bg-success';

if($d['persen'] < 90){
    $warna = 'bg-warning';
}

if($d['persen'] < 75){
    $warna = 'bg-danger';
}
?>

<div class="mb-4">

<label class="fw-bold mb-2">
    <?= $d['jurusan'] ?>
</label>

<div class="progress"
style="height:28px; border-radius:12px;">

<div class="progress-bar <?= $warna ?>"
style="width:<?= $d['persen'] ?>%; border-radius:12px;">

<?= $d['persen'] ?>%

</div>

</div>

</div>

<?php endforeach; ?>

</div>

<script>

new Chart(document.getElementById('grafikPersentase'), {

type:'bar',

data:{

labels: <?= json_encode($jurusan) ?>,

datasets:[{

label:'Persentase Kehadiran',

data: <?= json_encode($persentase) ?>,

backgroundColor:[
'#3b82f6',
'#10b981',
'#f59e0b',
'#ef4444',
'#8b5cf6',
'#06b6d4'
],

borderRadius:10

}]

},

options:{

responsive:true,

plugins:{
legend:{display:false}
},

scales:{
y:{
beginAtZero:true,
max:100
}
}

}

});

</script>

<?php endif; ?>


<!-- ========================= -->
<!-- GRAFIK KEHADIRAN -->
<!-- ========================= -->

<?php if($page=='grafik.kehadiran'): ?>

<h3 class="mb-4">
<i class="fa fa-chart-column"></i> Grafik Kehadiran
</h3>

<div class="d-flex gap-2 flex-wrap mb-4">

    <button class="btn btn-success shadow-sm px-4 py-2 rounded-3"
            onclick="exportSemuaGrafik()">

        <i class="bi bi-download"></i>
        Export Semua Grafik

    </button>

</div>

<?php

// STATISTIK
$sakit = $koneksi->query("
SELECT COUNT(*) as j
FROM kehadiran
WHERE tanggal BETWEEN '$dari' AND '$sampai'
AND keterangan='Sakit'
")->fetch_assoc()['j'];

$izin = $koneksi->query("
SELECT COUNT(*) as j
FROM kehadiran
WHERE tanggal BETWEEN '$dari' AND '$sampai'
AND keterangan='Izin'
")->fetch_assoc()['j'];

$alpha = $koneksi->query("
SELECT COUNT(*) as j
FROM kehadiran
WHERE tanggal BETWEEN '$dari' AND '$sampai'
AND keterangan='Alpha'
")->fetch_assoc()['j'];

$total_hadir =
$koneksi->query("
SELECT COUNT(*) as j
FROM data_siswa
")->fetch_assoc()['j']
- ($sakit + $izin + $alpha);

?>

<!-- STATISTIK -->

<div class="row mb-4">

<div class="col-lg-3 col-md-4 col-6 mb-3">
<div class="card shadow-sm p-3 bg-success text-white">
<h6>Total Hadir</h6>
<h3><?= $total_hadir ?></h3>
</div>
</div>

<div class="col-lg-3 col-md-4 col-6 mb-3">
<div class="card shadow-sm p-3 bg-danger text-white">
<h6>Alpha</h6>
<h3><?= $alpha ?></h3>
</div>
</div>

<div class="col-lg-3 col-md-4 col-6 mb-3">
<div class="card shadow-sm p-3 bg-warning text-white">
<h6>Sakit</h6>
<h3><?= $sakit ?></h3>
</div>
</div>

<div class="col-lg-3 col-md-4 col-6 mb-3">
<div class="card shadow-sm p-3 bg-info text-white">
<h6>Izin</h6>
<h3><?= $izin ?></h3>
</div>
</div>

</div>

<!-- FILTER -->

<div class="card shadow-sm p-4 mb-4">
<form method="GET" class="row g-3 align-items-end">

<input type="hidden" name="page" value="grafik.kehadiran">

<div class="col-md-4">
<label class="form-label fw-bold">Dari Tanggal</label>
<input type="date" name="dari" class="form-control" value="<?= $dari ?>">
</div>

<div class="col-md-4">
<label class="form-label fw-bold">Sampai Tanggal</label>
<input type="date" name="sampai" class="form-control" value="<?= $sampai ?>">
</div>

<div class="col-md-4">
<button class="btn btn-primary w-100">
<i class="fa fa-filter"></i> Filter Grafik
</button>
</div>

</form>
</div>

<?php

// GRAFIK KELAS
$kelas = [];
$total_kelas = [];

$q = $koneksi->query("
SELECT
CONCAT(s.tingkat,' ',s.jurusan,' ',s.rombel) as kelas,
(
COUNT(DISTINCT s.id)
- SUM(CASE WHEN k.keterangan='Sakit' THEN 1 ELSE 0 END)
- SUM(CASE WHEN k.keterangan='Izin' THEN 1 ELSE 0 END)
- SUM(CASE WHEN k.keterangan='Alpha' THEN 1 ELSE 0 END)
) as total

FROM data_siswa s

LEFT JOIN kehadiran k
ON s.id = k.siswa_id
AND k.tanggal BETWEEN '$dari' AND '$sampai'

GROUP BY s.tingkat, s.jurusan, s.rombel

ORDER BY
s.tingkat ASC,
s.jurusan ASC,
s.rombel ASC
");

while($d = $q->fetch_assoc()){

$kelas[] = $d['kelas'];
$total_kelas[] = $d['total'];

}

// GRAFIK JURUSAN
$jurusan = [];
$total_jurusan = [];

$q2 = $koneksi->query("
SELECT 
s.jurusan,

(
COUNT(DISTINCT s.id)
- SUM(CASE WHEN k.keterangan='Sakit' THEN 1 ELSE 0 END)
- SUM(CASE WHEN k.keterangan='Izin' THEN 1 ELSE 0 END)
- SUM(CASE WHEN k.keterangan='Alpha' THEN 1 ELSE 0 END)
) as total

FROM data_siswa s

LEFT JOIN kehadiran k 
ON s.id = k.siswa_id
AND k.tanggal BETWEEN '$dari' AND '$sampai'

GROUP BY s.jurusan

ORDER BY s.jurusan ASC
");

while($d2 = $q2->fetch_assoc()){

$jurusan[] = $d2['jurusan'];
$total_jurusan[] = $d2['total'];

}

?>

<div class="row">

<!-- GRAFIK KELAS -->

<div class="col-md-12 mb-4">
<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
<i class="fa fa-school"></i> Grafik Kehadiran Per-Kelas
</h5>

<div style="height:800px; overflow-y:auto;">
<canvas id="grafikKelas"></canvas>
</div>

</div>
</div>

<!-- GRAFIK JURUSAN -->

<div class="col-md-6 mb-4">
<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
<i class="fa fa-graduation-cap"></i> Grafik Kehadiran Per-Jurusan
</h5>

<canvas id="grafikJurusan"></canvas>

</div>
</div>

<!-- RANKING -->

<div class="col-md-6 mb-4">
<div class="card shadow-sm p-4" style="max-height:350px; overflow-y:auto;">

<h5 class="mb-4">
<i class="fa fa-ranking-star"></i> Ranking Kehadiran
</h5>

<?php

$ranking = $koneksi->query("
SELECT 
CONCAT(s.tingkat,' ',s.jurusan,' ',s.rombel) as kelas,

(
COUNT(DISTINCT s.id)
- SUM(CASE WHEN k.keterangan='Sakit' THEN 1 ELSE 0 END)
- SUM(CASE WHEN k.keterangan='Izin' THEN 1 ELSE 0 END)
- SUM(CASE WHEN k.keterangan='Alpha' THEN 1 ELSE 0 END)
) as total

FROM data_siswa s

LEFT JOIN kehadiran k 
ON s.id = k.siswa_id
AND k.tanggal BETWEEN '$dari' AND '$sampai'

GROUP BY s.tingkat, s.jurusan, s.rombel

ORDER BY total DESC
");

$no = 1;

while($r = $ranking->fetch_assoc()):
?>

<div class="d-flex justify-content-between align-items-center mb-3">

<div>
<b>#<?= $no++ ?></b>
<?= $r['kelas'] ?>
</div>

<span class="badge bg-primary p-2">
<?= $r['total'] ?> Kehadiran
</span>

</div>

<?php endwhile; ?>

</div>
</div>

</div>

<script>

// GRAFIK KELAS
new Chart(document.getElementById('grafikKelas'), {

type:'bar',

data:{
labels: <?= json_encode($kelas) ?>,

datasets:[{
label:'Jumlah Kehadiran',
data: <?= json_encode($total_kelas) ?>,
backgroundColor:'#3b82f6',
borderRadius:8,
barThickness:18
}]
},

options:{
indexAxis:'y',
responsive:true,
maintainAspectRatio:false,

plugins:{
legend:{display:false}
},

scales:{
x:{beginAtZero:true},
y:{grid:{display:false}}
}
}

});

// GRAFIK JURUSAN
new Chart(document.getElementById('grafikJurusan'), {

type:'doughnut',

data:{

labels: <?= json_encode($jurusan) ?>,

datasets:[{
data: <?= json_encode($total_jurusan) ?>,

backgroundColor:[
'#3b82f6',
'#10b981',
'#f59e0b',
'#ef4444',
'#8b5cf6',
'#06b6d4'
],

borderWidth:0
}]
},

options:{
responsive:true,
cutout:'65%'
}

});

</script>

<?php endif; ?>



<!-- ========================= -->
<!-- GRAFIK KETERLAMBATAN -->
<!-- ========================= -->

<!-- GRAFIK KETERLAMBATAN PER-KELAS -->
<?php if($page=='grafik.keterlambatan'): ?>

<h3 class="mb-4">
<i class="fa fa-clock"></i> Grafik Keterlambatan
</h3>

<div class="d-flex gap-2 flex-wrap mb-4">

    <button class="btn btn-success shadow-sm px-4 py-2 rounded-3"
            onclick="exportSemuaGrafik()">

        <i class="bi bi-download"></i>
        Export Semua Grafik

    </button>

</div>

<?php

$telat = $koneksi->query("
SELECT COUNT(*) as j
FROM keterlambatan
WHERE tanggal BETWEEN '$dari' AND '$sampai'
")->fetch_assoc()['j'];

?>

<div class="row mb-4">

<div class="col-lg-3 col-md-4 col-6 mb-3">
<div class="card shadow-sm p-3 bg-danger text-white">
<h6>Total Telat</h6>
<h3><?= $telat ?></h3>
</div>
</div>
</div>


<!-- FILTER -->

<div class="card shadow-sm p-4 mb-4">

<form method="GET" class="row g-3 align-items-end">

<input type="hidden" name="page" value="grafik.keterlambatan">

<div class="col-md-4">
<label class="form-label fw-bold">Dari Tanggal</label>
<input type="date" name="dari" class="form-control" value="<?= $dari ?>">
</div>

<div class="col-md-4">
<label class="form-label fw-bold">Sampai Tanggal</label>
<input type="date" name="sampai" class="form-control" value="<?= $sampai ?>">
</div>

<div class="col-md-4">
<button class="btn btn-primary w-100">
<i class="fa fa-filter"></i> Filter Grafik
</button>
</div>

</form>
</div>

<!-- GRAFIK TELAT PER JURUSAN -->
<div class="row mb-4">
<div class="col-md-6 mb-4">

<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
<i class="fa fa-graduation-cap"></i> Grafik Keterlambatan Per-Jurusan
</h5>

<canvas id="grafikJurusanTelat"></canvas>

</div>
</div>

<!-- RANKING KETERLAMBATAN -->

<div class="col-md-6 mb-4">

<div class="card shadow-sm p-4" style="max-height:400px; overflow-y:auto;">

<h5 class="mb-4">
<i class="fa fa-ranking-star"></i> Ranking Keterlambatan
</h5>

<?php

$ranking_telat = $koneksi->query("
SELECT

CONCAT(s.tingkat,' ',s.jurusan,' ',s.rombel) as kelas,
COUNT(k.id) as total

FROM data_siswa s

LEFT JOIN keterlambatan k
ON s.id = k.siswa_id
AND k.tanggal BETWEEN '$dari' AND '$sampai'

GROUP BY s.tingkat, s.jurusan, s.rombel

ORDER BY total DESC
");

$no = 1;

while($rt = $ranking_telat->fetch_assoc()):

?>

<div class="d-flex justify-content-between align-items-center mb-3">

<div>
<b>#<?= $no++ ?></b>
<?= $rt['kelas'] ?>
</div>

<span class="badge bg-danger p-2">
<?= $rt['total'] ?> Telat
</span>

</div>

<?php endwhile; ?>

</div>
</div>

<?php

//GRAFIK KETERLAMBATAN PER-KELAS
$total_telat_kelas = [];
$kelas = [];

$q_telat = $koneksi->query("
SELECT

CONCAT(s.tingkat,' ',s.jurusan,' ',s.rombel) as kelas,
COUNT(k.id) as total

FROM data_siswa s

LEFT JOIN keterlambatan k
ON s.id = k.siswa_id
AND k.tanggal BETWEEN '$dari' AND '$sampai'

GROUP BY s.tingkat, s.jurusan, s.rombel

ORDER BY
s.tingkat ASC,
s.jurusan ASC,
s.rombel ASC
");

while($t = $q_telat->fetch_assoc()){

$kelas[] = $t['kelas'];
$total_telat_kelas[] = $t['total'];

}

$jurusan_telat = [];
$total_jurusan_telat = [];

$q_jurusan_telat = $koneksi->query("
SELECT

s.jurusan,
COUNT(k.id) as total

FROM data_siswa s

LEFT JOIN keterlambatan k
ON s.id = k.siswa_id
AND k.tanggal BETWEEN '$dari' AND '$sampai'

GROUP BY s.jurusan

ORDER BY total DESC
");

while($jt = $q_jurusan_telat->fetch_assoc()){

$jurusan_telat[] = $jt['jurusan'];
$total_jurusan_telat[] = $jt['total'];

}
?>

<div class="row">

<div class="col-md-12 mb-4">
<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
<i class="fa fa-clock"></i> Grafik Keterlambatan Per-Kelas
</h5>

<div style="height:800px; overflow-y:auto;">
<canvas id="grafikTelat"></canvas>
</div>

</div>
</div>

</div>

<!-- GRAFIK PER HARI -->
<div class="row">
<div class="col-md-12 mb-4">

<div class="card shadow-sm p-4 grafik-export">

<h5 class="mb-4">
<i class="fa fa-calendar-day"></i> Grafik Keterlambatan Per Hari
</h5>

<canvas id="grafikHari"></canvas>
</div>
</div>
</div>

<?php
// GRAFIK TELAT PER HARI
$hari = [];
$total_hari = [];

$q_hari = $koneksi->query("
SELECT
hari,
COUNT(*) as total

FROM (

SELECT
CASE DAYOFWEEK(tanggal)

WHEN 2 THEN 'Senin'
WHEN 3 THEN 'Selasa'
WHEN 4 THEN 'Rabu'
WHEN 5 THEN 'Kamis'
WHEN 6 THEN 'Jumat'
WHEN 7 THEN 'Sabtu'
WHEN 1 THEN 'Minggu'

END as hari,

CASE DAYOFWEEK(tanggal)

WHEN 2 THEN 1
WHEN 3 THEN 2
WHEN 4 THEN 3
WHEN 5 THEN 4
WHEN 6 THEN 5
WHEN 7 THEN 6
WHEN 1 THEN 7

END as urutan

FROM keterlambatan

WHERE tanggal BETWEEN '$dari' AND '$sampai'

) as x

GROUP BY hari, urutan

ORDER BY urutan ASC
");

while($h = $q_hari->fetch_assoc()){

$hari[] = $h['hari'];
$total_hari[] = $h['total'];

}
?>

<script>

new Chart(document.getElementById('grafikTelat'), {

type:'bar',

data:{

labels: <?= json_encode($kelas) ?>,

datasets:[{
label:'Jumlah Telat',
data: <?= json_encode($total_telat_kelas) ?>,
backgroundColor:'#ef4444',
borderRadius:8,
barThickness:18
}]
},

options:{
indexAxis:'y',
responsive:true,
maintainAspectRatio:false,

plugins:{
legend:{display:false}
},

scales:{
x:{beginAtZero:true},
y:{grid:{display:false}}
}
}

});

// GRAFIK TELAT PER JURUSAN

new Chart(document.getElementById('grafikJurusanTelat'), {

type:'doughnut',

data:{

labels: <?= json_encode($jurusan_telat) ?>,

datasets:[{

data: <?= json_encode($total_jurusan_telat) ?>,

backgroundColor:[
'#ef4444',
'#f59e0b',
'#3b82f6',
'#10b981',
'#8b5cf6',
'#06b6d4'
],

borderWidth:0

}]

},

options:{
responsive:true,
cutout:'65%'
}

});

// GRAFIK PER HARI

new Chart(document.getElementById('grafikHari'), {

type:'line',

data:{

labels: <?= json_encode($hari) ?>,

datasets:[{

label:'Jumlah Telat',

data: <?= json_encode($total_hari) ?>,

borderColor:'#ef4444',

backgroundColor:'rgba(239,68,68,0.2)',

fill:true,

tension:0.4

}]

},

options:{
responsive:true
}

});

</script>

<?php endif; ?>

</div>

<script>

async function exportSemuaGrafik() {

    const grafikList = document.querySelectorAll('.grafik-export');

    for(let i = 0; i < grafikList.length; i++) {

        const grafik = grafikList[i];

        const canvas = await html2canvas(grafik, {
            backgroundColor: null,
            scale: 3
        });

        let link = document.createElement('a');

        let judul =
            grafik.querySelector('h5')?.innerText ||
            'grafik';

        judul = judul.replace(/\s+/g, '-').toLowerCase();

        link.download = judul + '.png';

        link.href = canvas.toDataURL('image/png');

        link.click();
    }

}

</script>

<script>
const sidebar = document.getElementById('sidebar');
const content = document.getElementById('content');
const toggleBtn = document.getElementById('toggleBtn');
const overlay = document.getElementById('overlay');

toggleBtn.onclick = ()=>{

    sidebar.classList.toggle('collapsed');
    content.classList.toggle('expanded');
    sidebar.classList.toggle('show');

    if(window.innerWidth <= 768){
        overlay.classList.toggle('show');
    }

}

overlay.onclick = ()=>{

    sidebar.classList.remove('show');
    overlay.classList.remove('show');

}
</script>

<?php endif; ?>
<div id="overlay"></div>
</body>
</html>
