<?php
include 'config.php';

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

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

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

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

// Ambil data absensi guru dari API (HADIR)
$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)
$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 untuk tanda tangan
$kepala_sekolah = $profil['kepala_sekolah'] ?? '....................................';
$nip_kepala = $profil['nip_kepala'] ?? '........................';

// Ambil nama kota/kabupaten dari alamat sekolah
$kota = '';
if (!empty($alamat_sekolah)) {
    $alamat_parts = explode(',', $alamat_sekolah);
    $kota = trim(end($alamat_parts));
}
if (empty($kota)) {
    $kota = '....................';
}

// Tanggal terakhir bulan ini untuk TTD
$tanggal_ttd = $kota . ', ' . date('d F Y', strtotime("$tahun-$bulan-" . cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun)));

// Ambil informasi hari kerja (opsional)
$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 - <?= $nama_sekolah ?></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: 5px;
      padding-bottom: 5px;
    }
    .subtitle {
      text-align: center;
      color: #7f8c8d;
      margin-bottom: 20px;
      font-size: 14px;
    }
    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: flex-end;
    }
    .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-bottom: 20px;
      flex-wrap: wrap;
    }
    .btn {
      padding: 8px 15px;
      border-radius: 4px;
      text-decoration: none;
      display: inline-block;
      font-weight: bold;
      transition: all 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;
      transform: translateY(-2px);
    }
    .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;
      background: #f8f9fa;
      padding: 10px;
      border-radius: 5px;
    }
    .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;
    }
    .ttd-table {
      width: 100%;
      border: 0;
      font-size: 14px;
      text-align: center;
    }
    .ttd-table td {
      border: none;
      padding: 5px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2><?= $nama_sekolah ?></h2>
    <?php if (!empty($alamat_sekolah)): ?>
      <div class="subtitle"><?= $alamat_sekolah ?></div>
    <?php endif; ?>
    <h2>Rekap Absensi Bulanan Guru</h2>
    <div class="subtitle">Bulan: <?= date('F Y', strtotime("$tahun-$bulan-01")) ?></div>

    <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 / Simpan PDF</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">Nama</th>
            <th rowspan="2">NIP</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 style='text-align:left'>{$guru['nama']}</td>";
            echo "<td>{$guru['nip']}</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

              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
                  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 class="ttd-table">
        <tr>
          <td style="width:50%;">
            Mengetahui,<br>
            Kepala Sekolah<br><br><br><br>
            <u><?= $kepala_sekolah ?></u><br>
            NIP. <?= $nip_kepala ?>
          </td>
          <td style="width:50%;">
            <?= $tanggal_ttd ?><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>