<?php
// Aktifkan laporan error untuk debugging jika masih ada masalah
ini_set('display_errors', 1);
error_reporting(E_ALL);

// PERBAIKAN PATH: Gunakan $_SERVER['DOCUMENT_ROOT'] dengan benar
require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/dompdf/autoload.inc.php'; 
require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/phpqrcode/qrlib.php'; // Sudah diperbaiki typo-nya
include $_SERVER['DOCUMENT_ROOT'] . '/assets/db/db.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$debug_mode = false; 

if (!isset($_GET['id'])) { die("ID tidak ditemukan."); }

$id = mysqli_real_escape_string($conn, $_GET['id']);
$query = "SELECT * FROM sertifikat_vaksin WHERE id = '$id'";
$result = $conn->query($query);
$data = $result->fetch_assoc();

if (!$data) { die("Data tidak ditemukan."); }

// PERBAIKAN PATH GAMBAR: Arahkan ke folder assets/templates
$bgPath = $_SERVER['DOCUMENT_ROOT'] . '/assets/templates/template2.png'; 
if (!file_exists($bgPath)) { die("File template tidak ditemukan di: " . $bgPath); }
$bgBase64 = 'data:image/png;base64,' . base64_encode(file_get_contents($bgPath));

// Generate QR Code
$tempDir = $_SERVER['DOCUMENT_ROOT'] . "/CRUD/temp_qr/"; // Simpan di subfolder CRUD agar aman
if (!file_exists($tempDir)) mkdir($tempDir, 0777, true);
$fileName = 'qr_'.$data['no_icv'].'.png';
$pngPath = $tempDir . $fileName;

// URL Verifikasi arahkan ke folder welcome
$urlVerifikasi = "https://sinkarkes.kemmkesgo.id/welcome/check_document.html?no=" . $data['no_icv'];
QRcode::png($urlVerifikasi, $pngPath, QR_ECLEVEL_L, 4);
$qrBase64 = 'data:image/png;base64,' . base64_encode(file_get_contents($pngPath));

$html = '
<html>
<head>
    <style>
        @page { margin: 0; }
        body { 
            margin: 0; padding: 0; font-family: "Helvetica", sans-serif;
            background-image: url("' . $bgBase64 . '");
            background-size: 100% 100%; background-repeat: no-repeat;
            width: 210mm; height: 297mm;
            color: #77777f;
        }
        .content { position: relative; width: 100%; height: 100%; }
        .debug-box { border: ' . ($debug_mode ? "1px solid red" : "none") . '; }
        
        .patient-info {
            position: absolute;
            top: 225px; left: 55px; width: 450px; 
            font-size: 14px; line-height: 1.6;
        }
        .patient-name { font-size: 18px; font-weight: bold; text-transform: uppercase; }

        .qr-header {
            position: absolute;
            top: 220px; right: 60px; width: 130px;
            text-align: center;
        }
        .icv-number-top {
            font-size: 13px; font-weight: bold; color: #77777f; margin-top: 5px;
        }

        .vaksin-table {
            position: absolute;
            top: 600px; left: 45px; width: 710px;
            border-collapse: collapse;
        }
        .vaksin-table td {
            vertical-align: top; padding: 5px;
            font-size: 10px; height: 85px; text-align: center;
        }
    </style>
</head>
<body>
    <div class="content">
        <div class="patient-info debug-box">
            <div class="patient-name">' . $data['nama_lengkap'] . '</div>
            <div>Passport ' . $data['no_paspor'] . '</div>
            <div>' . date('jS F Y', strtotime($data['tgl_lahir'])) . '</div>
        </div>

        <div class="qr-header debug-box">
            <img src="' . $qrBase64 . '" width="110">
            <div class="icv-number-top">' . $data['no_icv'] . '</div>
        </div>

        <table class="vaksin-table debug-box">
            <tr>
                <td width="22%"><strong>' . $data['vaksin_1_nama'] . '</strong></td>
                <td width="26%">' . $data['vaksin_1_batch'] . '</td>
                <td width="14%">' . date('jS F Y', strtotime($data['vaksin_1_tgl_admin'])) . '</td>
                <td width="14%">' . date('jS F Y', strtotime($data['vaksin_1_valid_sampai'])) . '</td>
                <td width="24%">' . nl2br($data['vaksin_1_faskes']) . '</td>
            </tr>';

if (!empty($data['vaksin_2_nama'])) {
    $html .= '
            <tr>
                <td><strong>' . $data['vaksin_2_nama'] . '</strong></td>
                <td>' . $data['vaksin_2_batch'] . '</td>
                <td>' . date('jS F Y', strtotime($data['vaksin_2_tgl_admin'])) . '</td>
                <td>' . date('jS F Y', strtotime($data['vaksin_2_valid_sampai'])) . '</td>
                <td>' . nl2br($data['vaksin_2_faskes']) . '</td>
            </tr>';
}

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

$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// Hapus file QR sementara setelah diproses menjadi Base64 untuk hemat ruang server
if (file_exists($pngPath)) unlink($pngPath);

$dompdf->stream("ICV_" . $data['nama_lengkap'] . ".pdf", ["Attachment" => false]);
?>