<?php
include '../includes/auth.php';
include '../includes/functions.php';

// Pastikan event_id ada
$event_id = isset($_GET['event_id']) ? (int)$_GET['event_id'] : 0;
if ($event_id <= 0) {
    die('Event ID tidak valid');
}

// Ambil data event, notulen, foto, dan undangan
$event = $conn->query("SELECT * FROM dafdir_event WHERE id_event = $event_id")->fetch_assoc();
$notulen = $conn->query("SELECT * FROM dafdir_event_notulen WHERE id_event = $event_id")->fetch_assoc();
$fotos = $conn->query("SELECT * FROM dafdir_event_foto WHERE id_event = $event_id ORDER BY urutan")->fetch_all(MYSQLI_ASSOC);
$undangan = $conn->query("SELECT * FROM dafdir_event_undangan WHERE id_event = $event_id ORDER BY created_at DESC LIMIT 1")->fetch_assoc();

// Load library DOMPDF
require_once '../vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;

// Konfigurasi DOMPDF
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$options->set('chroot', realpath(__DIR__ . '/../')); // Pastikan chroot ke direktori proyek
$options->set('dpi', 120);
$dompdf = new Dompdf($options);

// Fungsi untuk mengonversi gambar ke base64
function processImage($imagePath) {
    if (!file_exists($imagePath)) {
        // Fallback gambar transparan 1x1
        return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
    }
    $type = pathinfo($imagePath, PATHINFO_EXTENSION);
    $handle = fopen($imagePath, 'rb');
    $contents = '';
    while (!feof($handle)) {
        $contents .= fread($handle, 8192); // Baca 8KB per iterasi
    }
    fclose($handle);
    return 'data:image/' . $type . ';base64,' . base64_encode($contents);
}

// Buat konten HTML
$html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Notulen dan Dokumentasi - ' . htmlspecialchars($event['nama_event']) . '</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; font-size: 13px; }
        .header { text-align: center; margin-bottom: 30px; }
        .judul { font-size: 18px; font-weight: bold; margin-bottom: 5px; }
        .subjudul { font-size: 16px; margin-bottom: 5px; }
        .tanggal { font-size: 14px; margin-bottom: 20px; }
        .section { margin-bottom: 20px; }
        .section-title { font-size: 16px; font-weight: bold; margin-bottom: 10px; border-bottom: 1px solid #000; padding-bottom: 3px; }
        .notulen-content { margin-bottom: 30px; white-space: pre-line; }
        .foto-container { margin: 15px auto; text-align: center; }
        .foto-desc { font-size: 14px; margin-bottom: 10px; }
        .foto-img { max-width: 100%; max-height: 500px; }
        .undangan-img { max-width: 100%; max-height: 800px; margin-bottom: 20px; }
        .ttd-nama { margin-top: 60px; font-weight: bold; }
        .ttd-nip { font-weight: light; }
        .page-break { page-break-after: always; }
        .foto-page { margin-top: 20px; }
        .foto-table { width: 100%; border-collapse: collapse; }
        .foto-table td { width: 50%; padding: 10px; vertical-align: top; }
        @media print {
            .page-break-before { page-break-before: always; }
            .avoid-break { page-break-inside: avoid; }
        }

        .ttd {
                width: 100%;
                margin-top: 60px;
            }
        .ttd td {
            width: 50%;
            vertical-align: top;
        }
        .ttd-line {
            margin-top: 60px;
            border-top: 1px solid #000;
            width: 200px;
        }
        .right {
            text-align: right;
        }
        .ttd-container {
            margin-top: 30px;
            font-family: "Times New Roman", Times, serif;
            font-size: 12pt;
        }
        .ttd-row {
            display: flex;
            justify-content: space-between;
        }
        .ttd-table {
            width: 100%;
            -layout: fixed;
        }
        .ttd-table td {
            padding: 0 10px;
            vertical-align: top;
        }
        .ttd-column {
            text-align: left;
            vertical-align: top;
            width: 40%;
            padding-left: 20px;
        }
        .ttd-line {
            margin-top: 60px;
            widh: 200px;
        }
        p {
            margin: 2px 0;
        }
        .ttd-label {
                margin-top: 2px;
            font-family: "Times New Roman", Times, serif;
            font-size: 12pt;
        }
        .ttd-space {
            height: 30px;
        }
        .undangan-container {
            text-align: center;
            margin-bottom: 30px;
        }
        .undangan-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>';

// Halaman Undangan (jika ada)
if (!empty($undangan)) {
    $undangan_path = realpath(__DIR__ . '/../uploads/event_undangan/' . $undangan['nama_file']);
    $undangan_base64 = processImage($undangan_path);
    
    $html .= '
    <div class="undangan-container">
        <div class="undangan-title">UNDANGAN KEGIATAN</div>
        <img src="' . $undangan_base64 . '" class="undangan-img" />
        <div>' . htmlspecialchars($undangan['deskripsi'] ?? '') . '</div>
    </div>
    <div class="page-break"></div>';
}

// Halaman Notulen
$html .= '
    <div class="section">
        <div class="header">
            <div class="judul">NOTULEN KEGIATAN</div>
            <div class="subjudul">' . htmlspecialchars($event['nama_event']) . '</div>
            <div class="tanggal">Tanggal: ' . date('d F Y', strtotime($event['tanggal_event'])) . '</div>
        </div>

        <div class="section-title">CATATAN KEGIATAN</div>
        <div class="notulen-content">' . 
            (!empty($notulen['isi_notulen']) ? nl2br(htmlspecialchars($notulen['isi_notulen'])) : 'Tidak ada notulen tersedia') . 
        '</div>

        <div class="ttd">
            <table class="ttd-table">
                <tr>
                    <td class="ttd-column" style="text-align: center;">
                        <div style="display: inline-block; transform: translateX(-50px);">
                            <div>Mengetahui,</div>
                            <div>' . htmlspecialchars($event['jabatan'] ?? '') . '</div>

                            <div class="ttd-nama">' . htmlspecialchars($event['pengesah']) . '</div>
                            <div class="ttd-nip">NIP. ' . htmlspecialchars($event['nip']) . '</div>
                        </div>
                    </td>
                    <td class="ttd-column" style="text-align: center;">
                        <div>Notulen</div>
                        <div>' . htmlspecialchars($notulen['jabatan'] ?? '').'</div>
    
                        <div class="ttd-nama">'.htmlspecialchars($notulen['pembuat'] ?? '').'</div>
                        <div class="ttd-nip">'.htmlspecialchars($notulen['nip'] ?? '').'</div>
                    </td>
                </tr>
            </table>
        </div>
    </div>';

$html .= '<div class="page-break"></div>';

// Halaman Foto hanya ditambahkan jika ada foto
if (!empty($fotos)) {
    $html .= '
    <div class="foto-page page-break-before">
        <div class="header">
            <div class="judul">DOKUMENTASI KEGIATAN</div>
            <div class="subjudul">' . htmlspecialchars($event['nama_event']) . '</div>
            <div class="tanggal">Tanggal: ' . date('d F Y', strtotime($event['tanggal_event'])) . '</div>
        </div>
        <table class="foto-table">';

    $i = 1;
    foreach ($fotos as $index => $foto) {
        $foto_path = realpath(__DIR__ . '/../uploads/event_foto/' . $foto['nama_file']);
        $base64 = processImage($foto_path);
        if ($i % 2 == 1) {
            $html .= '<tr class="avoid-break">';
        }
        $html .= '
            <td>
                <div class="foto-container">
                    <img src="' . $base64 . '" class="foto-img" />
                    <div class="foto-desc">Dokumentasi ' . ($index + 1) . ': ' . htmlspecialchars($foto['deskripsi'] ?? '') . '</div>
                </div>
            </td>';
        if ($i % 2 == 0 || $i == count($fotos)) {
            if ($i == count($fotos) && $i % 2 == 1) {
                $html .= '<td></td>'; // Sel kosong untuk jumlah ganjil
            }
            $html .= '</tr>';
        }
        $i++;
    }

    $html .= '
        </table>
    </div>';
}

$html .= '
</body>
</html>';

// Load HTML ke DOMPDF
$dompdf->loadHtml($html);

// Set ukuran dan orientasi kertas
$dompdf->setPaper('A4', 'portrait');

// Render PDF
$dompdf->render();

// Output PDF
$dompdf->stream('notulen_' . preg_replace('/[^a-z0-9]/i', '_', strtolower($event['nama_event'])) . '.pdf', [
    'Attachment' => false
]);
?>