<?php
// 1. Pengaturan Header JSON & Output Buffering
header('Content-Type: application/json');
ini_set('display_errors', 0);
ob_start();

// 2. Hubungkan ke Database
$path_db = $_SERVER['DOCUMENT_ROOT'] . '/db.php';

if (file_exists($path_db)) {
    require_once $path_db;
} else {
    ob_clean();
    echo json_encode(['result' => 'error', 'message' => 'Koneksi sistem terputus (Database Error).']);
    exit;
}

require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/phpqrcode/qrlib.php';

// ==========================================
// CONFIG DEBUG MODE
$debug_mode = false; 
// ==========================================

// 3. Tangkap data dari AJAX
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);
$no_dokumen = isset($input['no_dokumen']) ? mysqli_real_escape_string($conn, $input['no_dokumen']) : '';

if (empty($no_dokumen)) {
    ob_clean();
    echo json_encode(['result' => 'error', 'message' => 'Nomor dokumen tidak valid.']);
    exit;
}

// 4. Cari data di Database
$query = "SELECT * FROM sertifikat_vaksin WHERE no_icv = '$no_dokumen' LIMIT 1";
$result = $conn->query($query);

if ($result && $result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $tgl_lahir = ($row['tgl_lahir']) ? date('jS F Y', strtotime($row['tgl_lahir'])) : '-';

    // GENERATE QR CODE
    $urlVerifikasi = "https://sinkarkes.citra-telematika.my.id/check_document.html?no=" . $row['no_icv'];
    ob_start();
    QRcode::png($urlVerifikasi, null, QR_ECLEVEL_L, 4);
    $imageString = base64_encode(ob_get_contents());
    ob_end_clean();
    $qrBase64 = 'data:image/png;base64,' . $imageString;

    // 5. Susun HTML
    $html = '
    <style>
        /* --- [1] STYLE DEFAULT UNTUK HANDPHONE (Mobile) --- */
        .digital-certificate {
            position: relative;
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
            background-image: url("template3.png");
            background-size: 100% 100%;
            background-repeat: no-repeat;
            aspect-ratio: 210 / 297; 
            color: #77777f;
            font-family: "Helvetica", Arial, sans-serif;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            border-radius: 10px;
            overflow: hidden;
        }

        .debug-line { outline: ' . ($debug_mode ? "1px solid red" : "none") . '; }

        /* Judul Mobile */
        .header-title { position: absolute; top: 18%; left: 50%; transform: translateX(-50%); width: 65%; text-align: center; line-height: 1.1; }
        .title-en { font-size: 3.8vw; font-weight: bold; display: block; margin-bottom: 2px; }
        .title-fr { font-size: 3vw; font-style: italic; display: block; }
        
        /* Identitas Mobile */
        .txt-name { position: absolute; top: 28%; left: 7.5%; width: 55%; font-weight: bold; font-size: 3.5vw; text-transform: uppercase; text-align: left; }
        .txt-passport { position: absolute; top: 31%; left: 7.5%; width: 40%; font-size: 3vw; text-align: left; }
        .txt-dob { position: absolute; top: 34%; left: 7.5%; width: 40%; font-size: 3vw; text-align: left; }
        
        /* Teks IHR - KHUSUS MOBILE */
        .txt-ihr { 
            position: absolute; 
            top: 37.5%; 
            left: 7.5%; 
            width: 80%; 
            font-size: 2.2vw; 
            line-height: 1.2; 
            text-align: left; 
        }

        /* QR Mobile */
        .qr-wrap { position: absolute; top: 27%; right: 7%; width: 20%; text-align: center; }
        .qr-wrap img { width: 85%; height: auto; }
        .icv-no { font-size: 2vw; font-weight: bold; margin-top: 2px; }

        /* Label Kolom Tabel */
        .vaccine-label-mobile { position: absolute; top: 42%; left: 5%; width: 20%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: center; }
        .batch-label-mobile { position: absolute; top: 42%; left: 26%; width: 20%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: center; }
        .date-label-mobile { position: absolute; top: 42%; left: 45%; width: 14%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: center; }
        .valid-label-mobile { position: absolute; top: 42%; left: 59%; width: 13%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: center; }
        .admin-label-mobile { position: absolute; top: 42%; left: 74%; width: 20%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: center; }

        /* Tabel Riwayat */
        .table-wrap { position: absolute; top: 52.5%; left: 5%; width: 90%; }
        .m-table { width: 100%; border-collapse: collapse; font-size: 2.1vw; color: #77777f; table-layout: fixed; }
        .m-table td { vertical-align: top; padding: 4px 2px; height: 12.5vw; text-align: center; }

        /* Label Bawah */
        .bottom-label-common { position: absolute; top: 72%; font-size: 1.7vw; font-weight: bold; line-height: 1.2; text-align: center; }
        .txt-disease { left: 5.5%; width: 15%; }
        .txt-date-bottom { left: 21%; width: 5%; }
        .txt-batch-bottom { left: 26%; width: 40%; }
        .txt-booster-bottom { left: 60%; width: 12%; }
        .txt-stamp-bottom { left: 73%; width: 22%; }

        /* Footer Section - KHUSUS MOBILE */
        .cert-footer { 
            position: absolute; 
            bottom: 5%; 
            left: 0; 
            width: 100%; 
            text-align: center; 
            line-height: 1.3; 
            color: #77777f; 
        }
        .footer-disclaimer { font-size: 2vw; margin-bottom: 5px; }
        .footer-issuer { font-size: 2.2vw; font-weight: bold; }
        .footer-issuer-fr { font-size: 2vw; font-style: italic; font-weight: normal; }

        /* --- [2] STYLE KHUSUS DESKTOP --- */
        @media (min-width: 600px) {
            .digital-certificate { max-width: 600px; background-image: url("template1.png"); }
            .header-title { top: 14%; width: 90%; }
            .title-en { font-size: 18px; }
            .title-fr { font-size: 14px; }
            .txt-name { font-size: 22px; top: 22%; left: 8%; }
            .txt-passport { font-size: 16px; top: 24.5%; left: 8%; }
            .txt-dob { font-size: 16px; top: 27.5%; left: 8%; }
            
            /* Sembunyikan elemen mobile di desktop */
            .txt-ihr { display: none; }
            .vaccine-label-mobile, .batch-label-mobile, .date-label-mobile, 
            .valid-label-mobile, .admin-label-mobile, .bottom-label-common { display: none; }
            
            /* SEMBUNYIKAN FOOTER DI DESKTOP */
            .cert-footer { display: none; }

            .qr-wrap { top: 20%; right: 8%; width: 115px; }
            .icv-no { font-size: 12px; }
            .m-table td { height: 75px; text-align: center; font-size: 12px; }
            .table-wrap { top: 52.5%; left: 5%; }
        }
    </style>

    <div class="digital-certificate animated fadeIn">
        <div class="header-title debug-line">
            <span class="title-en">International Certificate of Vaccination (Prophylaxis)</span>
            <span class="title-fr">Certificat International de Vaccination atau de Prophylaxie</span>
        </div>

        <div class="txt-name debug-line">' . $row['nama_lengkap'] . '</div>
        <div class="txt-passport debug-line">Passport ' . $row['no_paspor'] . '</div>
        <div class="txt-dob debug-line">' . $tgl_lahir . '</div>
        
        <div class="txt-ihr debug-line">
            In accordance with the International Health Regulations<br>
            <span style="font-style:italic;">comportement au Reglement sanitaire international</span>
        </div>

        <div class="qr-wrap debug-line">
            <img src="' . $qrBase64 . '">
            <div class="icv-no debug-line">' . $row['no_icv'] . '</div>
        </div>

        <div class="vaccine-label-mobile debug-line">Vaccine or Prophylaxis<br><span style="font-style:italic; font-weight:normal;">Vaccin ou agent prophylactique</span></div>
        <div class="batch-label-mobile debug-line">Manufacturer and Batch no.<br><span style="font-style:italic; font-weight:normal;">Fabricant et numero du lot</span></div>
        <div class="date-label-mobile debug-line">Date<br><span style="font-style:italic; font-weight:normal;">Date</span></div>
        <div class="valid-label-mobile debug-line">Valid Until<br><span style="font-style:italic; font-weight:normal;">Valable hingga</span></div>
        <div class="admin-label-mobile debug-line">Administering Location & Clinician<br><span style="font-style:italic; font-weight:normal;">Lieu d\'admin et Clinicien</span></div>

        <div class="table-wrap debug-line">
            <table class="m-table">
                <tr>
                    <td width="23%" class="debug-line"><strong>' . $row['vaksin_1_nama'] . '</strong></td>
                    <td width="25%" class="debug-line">' . $row['vaksin_1_batch'] . '</td>
                    <td width="14%" class="debug-line">' . date('d/m/y', strtotime($row['vaksin_1_tgl_admin'])) . '</td>
                    <td width="14%" class="debug-line">' . date('d/m/y', strtotime($row['vaksin_1_valid_sampai'])) . '</td>
                    <td width="24%" class="debug-line">' . $row['vaksin_1_faskes'] . '</td>
                </tr>
                ' . (!empty($row['vaksin_2_nama']) ? '
                <tr>
                    <td class="debug-line"><strong>' . $row['vaksin_2_nama'] . '</strong></td>
                    <td class="debug-line">' . $row['vaksin_2_batch'] . '</td>
                    <td class="debug-line">' . date('d/m/y', strtotime($row['vaksin_2_tgl_admin'])) . '</td>
                    <td class="debug-line">' . date('d/m/y', strtotime($row['vaksin_2_valid_sampai'])) . '</td>
                    <td class="debug-line">' . $row['vaksin_2_faskes'] . '</td>
                </tr>' : '') . '
            </table>
        </div>

        <div class="bottom-label-common txt-disease debug-line">Disease targeted:<br><span style="color:#000;">' . $row['penyakit_target'] . '</span></div>
        <div class="bottom-label-common txt-date-bottom debug-line">Date<br><span style="font-style:italic; font-weight:normal;">Date</span></div>
        <div class="bottom-label-common txt-batch-bottom debug-line">Manufacture and Batch No...<br><span style="font-style:italic; font-weight:normal;">Fabricant du vaccin...</span></div>
        <div class="bottom-label-common txt-booster-bottom debug-line">Next Booster<br><span style="font-style:italic; font-weight:normal;">Prochain rappel</span></div>
        <div class="bottom-label-common txt-stamp-bottom debug-line">Official stamp and signature<br><span style="font-style:italic; font-weight:normal;">Cachet officiel et signature</span></div>

        <div class="cert-footer debug-line">
            <div class="footer-disclaimer">
                <strong>Penafisan (Disclaimer):</strong><br>
                Nomor kode ICV elektronik (eICV) berbeda dengan nomor seri ICV fisik<br>
            </div>
            <div class="footer-disclaimer">
                <strong>This certificate was issued by Ministry of Health of Indonesia</strong><br>
                Ce certificat a été délivré par le ministère Indonésien de la Santé
            </div>
         </div>

    </div>
    <div class="text-center mt-3 mb-5">
        <p class="text-muted small"><i class="fa fa-lock"></i> Koneksi Enkripsi Aman - Balai Kekarantinaan Kesehatan</p>
    </div>';

    ob_clean();
    echo json_encode(['result' => 'success', 'html' => $html]);
} else {
    ob_clean();
    echo json_encode(['result' => 'error', 'message' => 'Data tidak ditemukan.']);
}
?>