<?php
session_start();
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru'])) {
    header("Location: index.php");
    exit;
}

include 'config.php';

$kelas = $_GET['kelas'] ?? '';
$bulan = $_GET['bulan'] ?? date('m');
$tahun = $_GET['tahun'] ?? date('Y');

// Dapatkan tanggal hari ini untuk perbandingan
$hariIni = date('d');
$bulanIni = date('m');
$tahunIni = date('Y');

// Ambil nama sekolah
$profil = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nama_sekolah, kepala_sekolah, nip_kepala FROM profil_sekolah LIMIT 1"));
$nama_sekolah = $profil['nama_sekolah'] ?? 'Nama Sekolah';

// Ambil daftar kelas - DIURUTKAN DARI YANG LEBIH KECIL
$kelasList = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa ORDER BY CAST(kelas AS UNSIGNED), kelas");

// Hitung jumlah hari dalam bulan
$jumlahHari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);

// Ambil daftar hari libur dari database
$libur = [];
$queryLibur = mysqli_query($conn, "SELECT tanggal FROM hari_libur");
while ($row = mysqli_fetch_assoc($queryLibur)) {
  $libur[] = $row['tanggal'];
}

// Ambil data wali kelas
$wali_nama = '....................................';
$wali_nip = '........................';
if ($kelas != '') {
    $qWali = mysqli_query($conn, "SELECT nama_wali, nip_wali FROM wali_kelas WHERE kelas = '$kelas' LIMIT 1");
    if ($w = mysqli_fetch_assoc($qWali)) {
        $wali_nama = $w['nama_wali'];
        $wali_nip = $w['nip_wali'];
    }
}

// Ambil daftar siswa - DIURUTKAN BERDASARKAN KELAS (KECIL KE BESAR) DAN NAMA
$sqlSiswa = "SELECT id, nis, nama, kelas FROM siswa WHERE status='aktif'";
if ($kelas != '') {
    $sqlSiswa .= " AND kelas = '$kelas'";
}
$sqlSiswa .= " ORDER BY CAST(kelas AS UNSIGNED), kelas, nama";
$siswaResult = mysqli_query($conn, $sqlSiswa);

// Ambil data absensi
$absensi = [];
$absensiQuery = "SELECT a.*, s.nis, s.nama FROM absensi a 
                 JOIN siswa s ON a.siswa_id = s.id 
                 WHERE MONTH(a.tanggal) = '$bulan' 
                   AND YEAR(a.tanggal) = '$tahun'
                   AND s.status='aktif'";
if ($kelas != '') {
  $absensiQuery .= " AND s.kelas = '$kelas'";
}
$resultAbsensi = mysqli_query($conn, $absensiQuery);

while ($row = mysqli_fetch_assoc($resultAbsensi)) {
  $sid = $row['siswa_id'];
  $tgl = (int)date('j', strtotime($row['tanggal']));
  $absensi[$sid][$tgl] = $row['status'];
}

// Hitung rekap absensi per siswa
$rekap = [];
$totalGlobal = ['H' => 0, 'I' => 0, 'S' => 0, 'A' => 0];

// Reset pointer untuk mengulang query siswa
mysqli_data_seek($siswaResult, 0);
while ($siswa = mysqli_fetch_assoc($siswaResult)) {
    $sid = $siswa['id'];
    $rekap[$sid] = [
        'nis' => $siswa['nis'],
        'nama' => $siswa['nama'],
        'kelas' => $siswa['kelas'],
        'H' => 0,
        'I' => 0,
        'S' => 0,
        'A' => 0
    ];

    // Hitung absensi berdasarkan data yang ada dan alpha otomatis
    for ($i = 1; $i <= $jumlahHari; $i++) {
        $tanggal = "$tahun-" . str_pad($bulan, 2, '0', STR_PAD_LEFT) . "-" . str_pad($i, 2, '0', STR_PAD_LEFT);
        $day = date('w', strtotime($tanggal));
        $isLibur = in_array($tanggal, $libur);
        
        // Tentukan apakah hari ini adalah hari mendatang
        $isHariMendatang = false;
        if ($tahun == $tahunIni && $bulan == $bulanIni && $i > $hariIni) {
            $isHariMendatang = true;
        } elseif ($tahun == $tahunIni && $bulan > $bulanIni) {
            $isHariMendatang = true;
        } elseif ($tahun > $tahunIni) {
            $isHariMendatang = true;
        }
        
        // Cek apakah ada data absensi untuk tanggal ini
        $val = $absensi[$sid][$i] ?? '';
        
        if ($val == '') {
            // Jika bukan hari Minggu, bukan libur, dan bukan hari mendatang = Alpha
            if ($day != 0 && !$isLibur && !$isHariMendatang) {
                $rekap[$sid]['A']++;
                $totalGlobal['A']++;
            }
        } else {
            $rekap[$sid][$val]++;
            $totalGlobal[$val]++;
        }
    }
}

// Hitung total hari aktif (hari dengan absensi)
$qHari = mysqli_query($conn, "SELECT COUNT(DISTINCT tanggal) as jml 
    FROM absensi 
    WHERE MONTH(tanggal) = '$bulan' 
    AND YEAR(tanggal) = '$tahun'");
$jmlHari = mysqli_fetch_assoc($qHari)['jml'] ?? 0;

// Tanggal terakhir bulan ini
$tanggal_terakhir = date("j F Y", strtotime("$tahun-$bulan-" . cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun)));

// Hitung total kehadiran keseluruhan
$totalHadirGlobal = $totalGlobal['H'];
$totalIzinGlobal = $totalGlobal['I'];
$totalSakitGlobal = $totalGlobal['S'];
$totalAlphaGlobal = $totalGlobal['A'];
$totalAbsenGlobal = $totalHadirGlobal + $totalIzinGlobal + $totalSakitGlobal + $totalAlphaGlobal;
$persentaseGlobal = $totalAbsenGlobal > 0 ? round(($totalHadirGlobal / $totalAbsenGlobal) * 100, 1) : 0;

// Hitung persentase per kelas
$persentasePerKelas = [];
foreach ($rekap as $r) {
    $kelasSiswa = $r['kelas'];
    if (!isset($persentasePerKelas[$kelasSiswa])) {
        $persentasePerKelas[$kelasSiswa] = ['totalHadir' => 0, 'totalAbsen' => 0];
    }
    $totalHadirSiswa = $r['H'];
    $totalAbsenSiswa = $r['H'] + $r['I'] + $r['S'] + $r['A'];
    $persentasePerKelas[$kelasSiswa]['totalHadir'] += $totalHadirSiswa;
    $persentasePerKelas[$kelasSiswa]['totalAbsen'] += $totalAbsenSiswa;
}

// Urutkan persentase per kelas berdasarkan kelas (dari kecil ke besar)
uksort($persentasePerKelas, function($a, $b) {
    return intval($a) - intval($b);
});
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Rekap Absensi Bulanan</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    h2 { text-align: center; margin-bottom: 5px; }
    form { text-align: center; margin-bottom: 20px; }
    select, input, button { padding: 5px; margin: 3px; }
    table { border-collapse: collapse; width: 100%; font-size: 14px; }
    th, td { border: 1px solid #ddd; padding: 6px; text-align: center; }
    th { background: #f4f4f4; }
    .summary { display: flex; justify-content: center; margin: 20px 0; gap: 20px; flex-wrap: wrap; }
    .box { padding: 10px 20px; border-radius: 8px; font-weight: bold; font-size: 16px; min-width: 120px; text-align: center; }
    .hadir { background: #dff0d8; color: #2e7d32; }
    .izin { background: #e3f2fd; color: #1565c0; }
    .sakit { background: #fff8e1; color: #ef6c00; }
    .alpha { background: #ffebee; color: #c62828; }
    .global { background: #e0e0e0; color: #333; }
    .kelas { background: #f3e5f5; color: #6a1b9a; }
    .predikat { font-weight: bold; padding: 3px 6px; border-radius: 4px; display: inline-block; }
    .sangatbaik { background: #c8e6c9; color: #256029; }
    .baik { background: #bbdefb; color: #0d47a1; }
    .cukup { background: #fff9c4; color: #f57f17; }
    .kurang { background: #ffe0b2; color: #e65100; }
    .libur { background-color: #fff0f0; }
    .hari-mendatang { background-color: #f9f9f9; color: #ccc; }
    .alpa { color: red; font-weight: bold; }
    .minggu { color: red; }
    .dot-red { color: red; font-weight: bold; }
</style>
</head>
<body>

<h2><?= $nama_sekolah ?><br>
Rekap Absensi Bulanan - <?= date('F Y', strtotime("$tahun-$bulan-01")) ?><br>
<?= $kelas == '' ? 'Semua Kelas' : "Kelas $kelas" ?></h2>

<!-- Form filter -->
<form method="get">
    <label>Kelas:
      <select name="kelas">
        <option value="">Semua</option>
        <?php mysqli_data_seek($kelasList, 0);
        while ($k = mysqli_fetch_assoc($kelasList)) {
          $sel = ($k['kelas'] == $kelas) ? 'selected' : '';
          echo "<option $sel value='{$k['kelas']}'>{$k['kelas']}</option>";
        } ?>
      </select>
    </label>

    <label>Bulan:
      <select name="bulan">
        <?php for ($b = 1; $b <= 12; $b++) {
          $sel = ($b == $bulan) ? 'selected' : '';
          echo "<option $sel value='$b'>" . date('F', mktime(0, 0, 0, $b, 10)) . "</option>";
        } ?>
      </select>
    </label>

    <label>Tahun:
      <input type="number" name="tahun" value="<?= $tahun ?>" style="width:80px;">
    </label>

    <button type="submit">Tampilkan</button>
    <a href="cetak_absen.php?kelas=<?= $kelas ?>&bulan=<?= $bulan ?>&tahun=<?= $tahun ?>" target="_blank" style="padding:5px 10px; background:#28a745; color:#fff; text-decoration:none; border-radius:4px;">Cetak / Simpan PDF</a>
    <a href="dashboard.php" 
       style="padding:5px 10px; background:#6c757d; color:#fff; 
              text-decoration:none; border-radius:4px; margin-left:10px;">
       ⬅ Kembali ke Dashboard
    </a>
</form>

<!-- Ringkasan -->
<div class="summary">
    <div class="box hadir"><?= $totalHadirGlobal ?> <br>Total Hadir</div>
    <div class="box izin"><?= $totalIzinGlobal ?> <br>Total Izin</div>
    <div class="box sakit"><?= $totalSakitGlobal ?> <br>Total Sakit</div>
    <div class="box alpha"><?= $totalAlphaGlobal ?> <br>Total Alpha</div>
</div>

<!-- Ringkasan Persentase Kehadiran -->
<div class="summary">
    <div class="box global"><?= $persentaseGlobal ?>% <br>Persentase Global</div>
    <?php if ($kelas == ''): ?>
        <?php foreach ($persentasePerKelas as $kel => $data): ?>
            <?php $persen = $data['totalAbsen'] > 0 ? round(($data['totalHadir'] / $data['totalAbsen']) * 100, 1) : 0; ?>
            <div class="box kelas"><?= $persen ?>% <br>Kelas <?= $kel ?></div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="box kelas"><?= $persentaseGlobal ?>% <br>Kelas <?= $kelas ?></div>
    <?php endif; ?>
</div>

<!-- Tabel absensi -->
<table>
    <tr>
        <th>No</th>
        <th>NIS</th>
        <th>Nama Siswa</th>
        <th>Kelas</th>
        <th>Hadir</th>
        <th>Izin</th>
        <th>Sakit</th>
        <th>Alpha</th>
        <th>Persentase & Predikat</th>
    </tr>
    <?php
    $no = 1;
    foreach ($rekap as $r) {
        $totalHadir = $r['H'];
        $izin = $r['I'];
        $sakit = $r['S'];
        $alpha = $r['A'];
        $totalAbsen = $totalHadir + $izin + $sakit + $alpha;

        $persen = $totalAbsen > 0 ? round(($totalHadir / $totalAbsen) * 100, 1) : 0;

        // Tentukan predikat
        if ($persen == 100) {
            $predikat = "<span class='predikat sangatbaik'>100% Sangat Baik</span>";
        } elseif ($persen >= 90) {
            $predikat = "<span class='predikat baik'>{$persen}% Baik</span>";
        } elseif ($persen >= 80) {
            $predikat = "<span class='predikat cukup'>{$persen}% Cukup</span>";
        } else {
            $predikat = "<span class='predikat kurang'>{$persen}% Kurang</span>";
        }

        echo "<tr>
            <td>$no</td>
            <td>{$r['nis']}</td>
            <td style='text-align:left'>{$r['nama']}</td>
            <td>{$r['kelas']}</td>
            <td>{$totalHadir}</td>
            <td>{$izin}</td>
            <td>{$sakit}</td>
            <td>{$alpha}</td>
            <td>$predikat</td>
        </tr>";
        $no++;
    }
    ?>
</table>

<br><br>
<table style="width:100%; border:0; font-size:14px; text-align:center;">
    <tr>
      <td style="width:50%;">
        Mengetahui,<br>
        Kepala Sekolah<br><br><br><br>
        <u><?= $profil['kepala_sekolah'] ?? '....................................' ?></u><br>
        NIP. <?= $profil['nip_kepala'] ?? '........................' ?>
      </td>
      <td style="width:50%;">
        <?= $tanggal_terakhir ?><br>
        Wali Kelas <?= $kelas != '' ? $kelas : '(Semua Kelas)' ?><br><br><br><br>
        <u><?= $wali_nama ?></u><br>
        NIP. <?= $wali_nip ?>
      </td>
    </tr>
</table>

</body>
</html>