<?php
include 'config.php';

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

// Fungsi untuk generate HTML
function generateHTMLContent($conn, $bulan, $tahun) {
    $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'] ?? '';
    $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)));

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

    // 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
    $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';
        }
    }

    // Ambil data izin
    $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'";

    $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'];
        }
    }

    // Gabungkan data
    $absensi = $absensiIzin;
    foreach ($absensiHadir as $gid => $hari) {
        foreach ($hari as $tgl => $status) {
            if (!isset($absensi[$gid][$tgl])) {
                $absensi[$gid][$tgl] = $status;
            }
        }
    }

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

    // Nama bulan Indonesia (tetap pakai Inggris untuk konsistensi dengan cetak_absen.php)
    $nama_bulan = [
        1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
        5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August',
        9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December'
    ];

    // Mulai generate HTML
    $html = '
    <!DOCTYPE html>
    <html lang="id">
    <head>
      <meta charset="UTF-8">
      <title>Rekap Absensi Bulanan Guru - ' . $nama_sekolah . '</title>
      <style>
        @page {
          size: landscape;
          margin: 10mm;
        }
        body { 
          font-family: Arial, sans-serif; 
          font-size: 9px;
          color: #333;
          margin: 0;
          padding: 0;
        }
        .container {
          width: 100%;
        }
        .header {
          text-align: center;
          margin-bottom: 10px;
          border-bottom: 2px solid #2980b9;
          padding-bottom: 5px;
        }
        .header h1 {
          margin: 0;
          color: #2980b9;
          font-size: 18px;
        }
        .header h2 {
          margin: 2px 0;
          color: #2c3e50;
          font-size: 16px;
        }
        .header p {
          margin: 2px 0;
          font-size: 12px;
          color: #27ae60;
        }
        .header .alamat {
          color: #7f8c8d;
          font-size: 10px;
        }
        table { 
          border-collapse: collapse; 
          width: 100%; 
          font-size: 8px;
          margin-top: 5px;
        }
        th, td { 
          border: 1px solid #ddd; 
          text-align: center; 
          padding: 3px;
          height: 20px;
        }
        th { 
          background: #2980b9; 
          color: white; 
          font-weight: bold;
        }
        .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; }
        .kosong { background-color: #f9f9f9; }
        .footer {
          margin-top: 15px;
          padding-top: 10px;
          border-top: 1px solid #bdc3c7;
          font-size: 10px;
        }
        .legend {
          display: flex;
          gap: 10px;
          margin: 10px 0;
          flex-wrap: wrap;
          font-size: 9px;
          background: #f8f9fa;
          padding: 5px;
          border-radius: 3px;
        }
        .legend-item {
          display: flex;
          align-items: center;
          gap: 3px;
        }
        .legend-color {
          width: 10px;
          height: 10px;
          border-radius: 2px;
        }
        .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: 3px solid #3498db;
          padding: 5px 8px;
          margin-bottom: 8px;
          border-radius: 3px;
          font-size: 8px;
        }
        .ttd-table {
          width: 100%;
          border: 0;
          font-size: 10px;
          text-align: center;
        }
        .ttd-table td {
          border: none;
          padding: 3px;
        }
        .nama-kepsek {
          color: #2980b9;
          font-weight: bold;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="header">
          <h1>' . $nama_sekolah . '</h1>
          <div class="alamat">' . $alamat_sekolah . '</div>
          <h2>REKAPITULASI ABSENSI GURU</h2>
          <p>Bulan: ' . $nama_bulan[(int)$bulan] . ' ' . $tahun . '</p>
        </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.
        </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>

        <table>
          <thead>
            <tr>
              <th rowspan="2" style="width: 20px;">No</th>
              <th rowspan="2" style="width: 100px;">Nama</th>
              <th rowspan="2" style="width: 80px;">NIP</th>
              <th colspan="' . $jumlahHari . '">Tanggal</th>
              <th colspan="4">Rekap</th>
            </tr>
            <tr>';

    // Header tanggal
    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));
      $class = ($day == 0) ? 'minggu' : '';
      $html .= "<th class='$class' style='width: 12px;'>$i</th>";
    }

    $html .= '
              <th style="width: 15px;">H</th>
              <th style="width: 15px;">I</th>
              <th style="width: 15px;">S</th>
              <th style="width: 15px;">A</th>
            </tr>
          </thead>
          <tbody>';

    // Data absensi
    $no = 1;
    if ($guruResult) {
        mysqli_data_seek($guruResult, 0);
        while ($guru = mysqli_fetch_assoc($guruResult)) {
            $gid = $guru['id'];
            $html .= "<tr>";
            $html .= "<td>$no</td>";
            $html .= "<td style='text-align: left;'>{$guru['nama']}</td>";
            $html .= "<td>{$guru['nip']}</td>";

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

            for ($i = 1; $i <= $jumlahHari; $i++) {
                $val = isset($absensi[$gid][$i]) ? $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));

                if ($val == '') {
                    if ($day == 0) {
                        $html .= "<td class='minggu'>M</td>";
                    } elseif (in_array($tanggal, $libur)) {
                        $html .= "<td class='libur'>L</td>";
                    } else {
                        $html .= "<td class='kosong'></td>";
                    }
                } else {
                    if ($val == 'H') {
                        $html .= "<td class='hadir'>H</td>";
                        $countH++;
                    } elseif ($val == 'I') {
                        $html .= "<td class='izin'>I</td>";
                        $countI++;
                    } elseif ($val == 'S') {
                        $html .= "<td class='sakit'>S</td>";
                        $countS++;
                    } elseif ($val == 'A') {
                        $html .= "<td class='alpha'>A</td>";
                        $countA++;
                    }
                }
            }

            $html .= "<td class='hadir'>$countH</td>";
            $html .= "<td class='izin'>$countI</td>";
            $html .= "<td class='sakit'>$countS</td>";
            $html .= "<td class='alpha'>$countA</td>";
            $html .= "</tr>";
            $no++;
        }
    }

    $html .= '
          </tbody>
        </table>

        <div class="footer">
          <table class="ttd-table">
            <tr>
              <td style="width:50%;">
                Mengetahui,<br>
                Kepala Sekolah<br><br><br><br>
                <u class="nama-kepsek">' . $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>
    </body>
    </html>';

    return $html;
}

// Cek DomPDF
$dompdfPaths = [
    'dompdf/autoload.inc.php',
    'vendor/dompdf/dompdf/autoload.inc.php', 
    '../dompdf/autoload.inc.php',
    '../../dompdf/autoload.inc.php'
];

$dompdfLoaded = false;
foreach ($dompdfPaths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $dompdfLoaded = true;
        break;
    }
}

// Jika DomPDF tidak ditemukan, tampilkan HTML
if (!$dompdfLoaded) {
    header('Content-Type: text/html; charset=utf-8');
    echo generateHTMLContent($conn, $bulan, $tahun);
    exit;
}

// Jika DomPDF ditemukan, coba buat PDF
use Dompdf\Dompdf;
use Dompdf\Options;

try {
    $html = generateHTMLContent($conn, $bulan, $tahun);
    
    $options = new Options();
    $options->set('isRemoteEnabled', true);
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isFontSubsettingEnabled', true);
    $options->set('defaultFont', 'Arial');
    $options->set('isPhpEnabled', false);
    $options->set('isJavascriptEnabled', false);

    $dompdf = new Dompdf($options);
    $dompdf->setPaper('A4', 'landscape');
    $dompdf->loadHtml($html);
    $dompdf->render();
    
    // Output PDF
    $dompdf->stream('rekap_absen_guru_' . $bulan . '_' . $tahun . '.pdf', ['Attachment' => 1]);
    
} catch (Exception $e) {
    // Fallback: Tampilkan HTML jika PDF gagal
    header('Content-Type: text/html; charset=utf-8');
    echo "<h2 style='color: #e74c3c;'>Error generating PDF: " . htmlspecialchars($e->getMessage()) . "</h2>";
    echo "<p style='color: #2980b9;'>Menampilkan versi HTML sebagai alternatif:</p>";
    echo generateHTMLContent($conn, $bulan, $tahun);
    echo "<script>
        setTimeout(function() {
            window.print();
        }, 1000);
    </script>";
}

exit;
?>