<?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 guru hanya yang aktif
    $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'];
        }
    }

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

    // Nama bulan Indonesia
    $nama_bulan = [
        1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
        5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
        9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
    ];

    // Mulai generate HTML
    $html = '
    <!DOCTYPE html>
    <html lang="id">
    <head>
      <meta charset="UTF-8">
      <title>Rekap Absensi Bulanan Guru</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 #2c3e50;
          padding-bottom: 5px;
        }
        .header h2 {
          margin: 0;
          color: #2c3e50;
          font-size: 16px;
        }
        .header p {
          margin: 2px 0;
          font-size: 12px;
        }
        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: #2c3e50; 
          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 #eee;
          font-size: 10px;
        }
        .legend {
          display: flex;
          gap: 10px;
          margin: 10px 0;
          flex-wrap: wrap;
          font-size: 9px;
        }
        .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;
        }
        .nama-sekolah {
          font-weight: bold;
          font-size: 14px;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="header">
          <div class="nama-sekolah">' . ($profil['nama_sekolah'] ?? 'SEKOLAH MENENGAH ATAS') . '</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).
        </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)</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: 80px;">NIP</th>
              <th rowspan="2" style="width: 120px;">Nama</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>{$guru['nip']}</td>";
            $html .= "<td style='text-align: left;'>{$guru['nama']}</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 style="width:100%; border:0; font-size:10px; 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%;">
                ' . date('d F Y') . '<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'
];

$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');

    $dompdf = new Dompdf($options);
    $dompdf->setPaper('A4', 'landscape');
    $dompdf->loadHtml($html);
    $dompdf->render();
    
    // Coba beberapa metode output
    $output = $dompdf->output();
    
    // Method 1: Langsung output ke browser dengan attachment
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="rekap_absen_guru_' . $bulan . '_' . $tahun . '.pdf"');
    header('Content-Length: ' . strlen($output));
    echo $output;
    
    // Method 2: Jika method 1 gagal, coba method stream
    // $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>Error generating PDF: " . htmlspecialchars($e->getMessage()) . "</h2>";
    echo "<p>Menampilkan versi HTML sebagai alternatif:</p>";
    echo generateHTMLContent($conn, $bulan, $tahun);
    echo "<script>
        setTimeout(function() {
            window.print();
        }, 1000);
    </script>";
}

exit;
?>