<?php
include 'config.php';

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

$jumlahHari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);

// Ambil guru hanya yang aktif
$guruQuery = "SELECT * FROM guru WHERE status='aktif' ORDER BY nama";
$guruResult = mysqli_query($conn, $guruQuery);

// Ambil data absensi guru dari API (HADIR) - pastikan tabelnya ada
$absensiHadir = [];
$absensiQuery = "SELECT a.*, g.nip, g.nama FROM absensi_guru a 
                 JOIN guru g ON a.guru_id = g.id 
                 WHERE MONTH(a.tanggal) = '$bulan' 
                   AND YEAR(a.tanggal) = '$tahun'
                   AND g.status='aktif'";
$resultAbsensi = mysqli_query($conn, $absensiQuery);

if ($resultAbsensi) {
    while ($row = mysqli_fetch_assoc($resultAbsensi)) {
        $gid = $row['guru_id'];
        $tgl = (int)date('j', strtotime($row['tanggal']));
        $absensiHadir[$gid][$tgl] = 'H'; // Hadir dari API
    }
}

// Ambil data izin/sakit/alpha dari input_izin_guru (I/S/A) - pastikan tabelnya ada
$absensiIzin = [];
$izinQuery = "SELECT i.*, g.nip, g.nama FROM izin_guru i 
              JOIN guru g ON i.guru_id = g.id 
              WHERE MONTH(i.tanggal) = '$bulan' 
                AND YEAR(i.tanggal) = '$tahun'
                AND g.status='aktif'
                AND i.status = 'disetujui'"; // Hanya yang disetujui

$resultIzin = mysqli_query($conn, $izinQuery);

if ($resultIzin) {
    while ($row = mysqli_fetch_assoc($resultIzin)) {
        $gid = $row['guru_id'];
        $tgl = (int)date('j', strtotime($row['tanggal']));
        $absensiIzin[$gid][$tgl] = $row['jenis_izin']; // I/S/A dari input manual
    }
}

// Gabungkan data - data izin memiliki prioritas lebih tinggi daripada data hadir
$absensi = $absensiIzin; // Mulai dengan data izin

// Tambahkan data hadir hanya untuk tanggal yang tidak ada di data izin
foreach ($absensiHadir as $gid => $hari) {
    foreach ($hari as $tgl => $status) {
        if (!isset($absensi[$gid][$tgl])) {
            $absensi[$gid][$tgl] = $status;
        }
    }
}

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

// Ambil data profil sekolah
$profil = [];
$profilQuery = mysqli_query($conn, "SELECT kepala_sekolah, nip_kepala FROM profil_sekolah LIMIT 1");
if ($profilQuery) {
    $profil = mysqli_fetch_assoc($profilQuery);
}

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

// Ambil informasi hari kerja (opsional, jika ada tabel jadwal)
$hariKerja = [];
$jadwalQuery = mysqli_query($conn, "SELECT DISTINCT DAYOFWEEK(tanggal) as hari FROM jadwal_guru");
if ($jadwalQuery && mysqli_num_rows($jadwalQuery) > 0) {
    while ($row = mysqli_fetch_assoc($jadwalQuery)) {
        $hariKerja[] = $row['hari']; // 1=Minggu, 2=Senin, ..., 7=Sabtu
    }
} else {
    // Default: Senin-Jumat (2-6) sebagai hari kerja
    $hariKerja = [2, 3, 4, 5, 6];
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Rekap Absensi Bulanan Guru</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body { 
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
      padding: 20px; 
      background-color: #f5f5f5;
      color: #333;
    }
    .container {
      max-width: 100%;
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h2 {
      color: #2c3e50;
      text-align: center;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #eee;
    }
    table { 
      border-collapse: collapse; 
      width: 100%; 
      font-size: 12px; 
      margin-top: 15px;
    }
    th, td { 
      border: 1px solid #ddd; 
      text-align: center; 
      padding: 5px; 
    }
    th { 
      background: #2c3e50; 
      color: white; 
      font-weight: bold;
    }
    tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    tr:hover {
      background-color: #f1f1f1;
    }
    select, input, button { 
      padding: 8px; 
      margin: 5px 0; 
      border: 1px solid #ddd;
      border-radius: 4px;
    }
    button {
      background: #3498db;
      color: white;
      border: none;
      cursor: pointer;
      transition: background 0.3s;
    }
    button:hover {
      background: #2980b9;
    }
    .filter-container {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 5px;
      margin-bottom: 20px;
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      align-items: center;
    }
    .filter-item {
      display: flex;
      flex-direction: column;
    }
    .filter-item label {
      font-weight: bold;
      margin-bottom: 5px;
      color: #2c3e50;
    }
    .action-buttons {
      display: flex;
      gap: 10px;
      margin-top: 10px;
    }
    .btn {
      padding: 8px 15px;
      border-radius: 4px;
      text-decoration: none;
      display: inline-block;
      font-weight: bold;
      transition: background 0.3s;
    }
    .btn-primary {
      background: #3498db;
      color: white;
    }
    .btn-success {
      background: #28a745;
      color: white;
    }
    .btn-secondary {
      background: #6c757d;
      color: white;
    }
    .btn:hover {
      opacity: 0.9;
    }
    .minggu { 
      color: #e74c3c; 
      font-weight: bold;
    }
    .libur { 
      color: #e74c3c; 
      font-weight: bold;
    }
    .hadir {
      color: #27ae60;
      font-weight: bold;
    }
    .izin {
      color: #f39c12;
      font-weight: bold;
    }
    .sakit {
      color: #9b59b6;
      font-weight: bold;
    }
    .alpha {
      color: #e74c3c;
      font-weight: bold;
    }
    .footer {
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #eee;
    }
    .legend {
      display: flex;
      gap: 15px;
      margin: 15px 0;
      flex-wrap: wrap;
    }
    .legend-item {
      display: flex;
      align-items: center;
      gap: 5px;
    }
    .legend-color {
      width: 15px;
      height: 15px;
      border-radius: 3px;
    }
    .legend-hadir { background: #27ae60; }
    .legend-izin { background: #f39c12; }
    .legend-sakit { background: #9b59b6; }
    .legend-alpha { background: #e74c3c; }
    .legend-minggu { background: #e74c3c; }
    .legend-libur { background: #e74c3c; }
    .info-box {
      background: #e7f4ff;
      border-left: 4px solid #3498db;
      padding: 10px 15px;
      margin-bottom: 15px;
      border-radius: 4px;
    }
    .kosong {
      background-color: #f9f9f9;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>Rekap Absensi Bulanan Guru</h2>

    <div class="info-box">
      <strong>Info:</strong> Data ini menggabungkan informasi dari sistem absensi (H) dan input izin manual (I/S/A).
      Data izin manual memiliki prioritas lebih tinggi. Alpha (A) hanya ditampilkan jika diinput manual.
    </div>

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

      <div class="filter-item">
        <label for="tahun">Tahun:</label>
        <input type="number" name="tahun" id="tahun" value="<?= $tahun ?>" style="width: 80px;">
      </div>

      <div class="filter-item">
        <label>&nbsp;</label>
        <button type="button" onclick="filterData()">Tampilkan</button>
      </div>
    </div>

    <div class="action-buttons">
      <a href="cetak_absen_guru.php?bulan=<?= $bulan ?>&tahun=<?= $tahun ?>" target="_blank" class="btn btn-success">Cetak</a>
      <a href="input_izin_guru.php" class="btn btn-primary">Input Izin / Sakit</a>
      <a href="dashboard.php" class="btn btn-secondary">Kembali ke Dashboard</a>
    </div>

    <div class="legend">
      <div class="legend-item">
        <div class="legend-color legend-hadir"></div>
        <span>Hadir (H)</span>
      </div>
      <div class="legend-item">
        <div class="legend-color legend-izin"></div>
        <span>Izin (I)</span>
      </div>
      <div class="legend-item">
        <div class="legend-color legend-sakit"></div>
        <span>Sakit (S)</span>
      </div>
      <div class="legend-item">
        <div class="legend-color legend-alpha"></div>
        <span>Alpha (A) - Manual</span>
      </div>
      <div class="legend-item">
        <div class="legend-color legend-minggu"></div>
        <span>Minggu</span>
      </div>
      <div class="legend-item">
        <div class="legend-color legend-libur"></div>
        <span>Libur</span>
      </div>
    </div>

    <div style="overflow-x: auto;">
      <table>
        <thead>
          <tr>
            <th rowspan="2">No</th>
            <th rowspan="2">NIP</th>
            <th rowspan="2">Nama</th>
            <th colspan="<?= $jumlahHari ?>">Tanggal</th>
            <th colspan="4">Rekap</th>
          </tr>
          <tr>
            <?php
            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)); // 0 = Minggu
              $class = ($day == 0) ? 'minggu' : '';
              echo "<th class='$class'>$i</th>";
            }
            ?>
            <th>H</th><th>I</th><th>S</th><th>A</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $no = 1;
          mysqli_data_seek($guruResult, 0); // Reset pointer to beginning
          while ($guru = mysqli_fetch_assoc($guruResult)) {
            $gid = $guru['id'];
            echo "<tr>";
            echo "<td>$no</td>";
            echo "<td>{$guru['nip']}</td>";
            echo "<td>{$guru['nama']}</td>";

            $countH = $countI = $countS = $countA = 0;

            for ($i = 1; $i <= $jumlahHari; $i++) {
              $val = $absensi[$gid][$i] ?? '';
              $tanggal = "$tahun-" . str_pad($bulan, 2, '0', STR_PAD_LEFT) . "-" . str_pad($i, 2, '0', STR_PAD_LEFT);
              $day = date('w', strtotime($tanggal)); // 0 = Minggu, 1 = Senin, ..., 6 = Sabtu
              $dayOfWeek = $day + 1; // Konversi ke format MySQL (1=Minggu, 2=Senin, ..., 7=Sabtu)

              if ($val == '') {
                if ($day == 0) {
                  echo "<td class='minggu'>M</td>";
                } elseif (in_array($tanggal, $libur)) {
                  echo "<td class='libur'>L</td>";
                } else {
                  // Kosong jika tidak ada data dan bukan hari libur/minggu
                  // Tidak otomatis dianggap Alpha karena guru tidak punya jadwal setiap hari
                  echo "<td class='kosong'></td>";
                }
              } else {
                if ($val == 'H') {
                  echo "<td class='hadir'>H</td>";
                  $countH++;
                } elseif ($val == 'I') {
                  echo "<td class='izin'>I</td>";
                  $countI++;
                } elseif ($val == 'S') {
                  echo "<td class='sakit'>S</td>";
                  $countS++;
                } elseif ($val == 'A') {
                  echo "<td class='alpha'>A</td>";
                  $countA++;
                } else {
                  echo "<td>$val</td>";
                }
              }
            }

            echo "<td class='hadir'>$countH</td>";
            echo "<td class='izin'>$countI</td>";
            echo "<td class='sakit'>$countS</td>";
            echo "<td class='alpha'>$countA</td>";
            echo "</tr>";
            $no++;
          }
          ?>
        </tbody>
      </table>
    </div>

    <div class="footer">
      <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>
            Koordinator Kepegawaian<br><br><br><br>
            <u>....................................</u><br>
            NIP. ........................
          </td>
        </tr>
      </table>
    </div>
  </div>

  <script>
    function filterData() {
      const bulan = document.getElementById('bulan').value;
      const tahun = document.getElementById('tahun').value;
      window.location.href = `rekap_bulanan_guru.php?bulan=${bulan}&tahun=${tahun}`;
    }
  </script>
</body>
</html>