<?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'] . '/assets/db/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();
    
    // FORMAT TANGGAL: jS F Y (Contoh: 24th December 2028)
    $tgl_lahir = ($row['tgl_lahir']) ? date('jS F Y', strtotime($row['tgl_lahir'])) : '-';

    $nama_raw = $row['nama_lengkap'];
    $nama_masking = (strlen($nama_raw) > 3) ? substr($nama_raw, 0, -3) . '***' : $nama_raw;
    $paspor_raw = $row['no_paspor'];
    $paspor_masking = (strlen($paspor_raw) > 3) ? substr($paspor_raw, 0, -3) . '***' : $paspor_raw;

    $urlVerifikasi = "https://sinkarkes.kemmkesgo.id/welcome/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>
        .full-width-container { width: 100%; padding: 0; margin: 0; background: #fff; }

        .digital-certificate {
            position: relative;
            width: 100%;
            margin: 0;
            background-image: url("/assets/templates/template4.png");
            background-size: 100% 100%;
            background-repeat: no-repeat;
            aspect-ratio: 210 / 297; 
            color: #77777f;
            font-family: "Helvetica", Arial, sans-serif;
            overflow: hidden;
            border-radius: 0;
        }

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

        .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; }
        
        .txt-name { position: absolute; top: 31%; left: 5%; width: 55%; font-weight: bold; font-size: 2.1vw; text-transform: uppercase; text-align: left; }
        .txt-passport { position: absolute; top: 34%; left: 5%; width: 40%; font-size: 2.1vw; text-align: left; }
        .txt-dob { position: absolute; top: 37%; left: 5%; width: 40%; font-size: 2.1vw; text-align: left; }
        .txt-ihr { position: absolute; top: 43.5%; left: 5%; width: 80%; font-size: 2.2vw; line-height: 1.2; text-align: left; }

        .qr-wrap { position: absolute; top: 31%; right: 7%; width: 21%; text-align: center; }
        .qr-wrap img { width: 90%; height: auto; }
        .icv-no { font-size: 2vw; font-weight: bold; margin-top: 0.5px; }

        .vaccine-label-mobile { position: absolute; top: 49.3%; left: 5%; width: 20%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: left; }
        .batch-label-mobile { position: absolute; top: 49.3%; left: 26%; width: 20%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: left; }
        .date-label-mobile { position: absolute; top: 49.3%; left: 50%; width: 14%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: left; }
        .valid-label-mobile { position: absolute; top: 49.3%; left: 59%; width: 13%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: left; }
        .admin-label-mobile { position: absolute; top: 49.3%; left: 74%; width: 20%; font-size: 1.9vw; line-height: 1.1; font-weight: bold; text-align: left; }

        .table-wrap { position: absolute; top: 61.5%; left: 5%; width: 90%; }
        /* Font m-table diperkecil sedikit (1.8vw) agar muat format tanggal yang panjang */
        .m-table { width: 100%; border-collapse: collapse; font-size: 1.8vw; color: #77777f; table-layout: fixed; }
        .m-table td { vertical-align: top; padding: 4px 2px; height: 12.5vw; text-align: left; line-height: 1.1; word-wrap: break-word; }

        .bottom-label-common { position: absolute; top: 79.5%; font-size: 1.7vw; font-weight: bold; line-height: 1.2; text-align: left; }
        .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: 8%; }
        .txt-stamp-bottom { left: 75%; width: 22%; }

        .cert-footer { position: absolute; bottom: 5%; left: 0; width: 100%; text-align: center; line-height: 1.3; color: #77777f; }
        .footer-disclaimer { font-size: 2vw; }

        @media (min-width: 600px) {
            .digital-certificate { max-width: 600px; margin: 30px auto; border-radius: 10px; box-shadow: 0 15px 45px rgba(0,0,0,0.2); }
            .title-en { font-size: 22px; }
            .title-fr { font-size: 16px; }
            .txt-name, .txt-passport, .txt-dob { font-size: 14px; }
            .txt-ihr { font-size: 13px; }
            .qr-wrap { width: 120px; }
            .icv-no { font-size: 12px; }
            .m-table { font-size: 11px; }
            .m-table td { height: 75px; }
            .vaccine-label-mobile, .batch-label-mobile, .date-label-mobile, .valid-label-mobile, .admin-label-mobile { font-size: 11px; }
            .bottom-label-common { font-size: 10px; }
            .footer-disclaimer { font-size: 12px; }
        }
    </style>

    <div class="full-width-container">
        <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">' . $nama_masking . '</div>
            <div class="txt-passport debug-line">Passport ' . $paspor_masking . '</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">Vaccine or Prophylaxis</div>
            <div class="batch-label-mobile">Manufacturer and Batch no...</div>
            <div class="date-label-mobile">Date</div>
            <div class="valid-label-mobile">Valid Until</div>
            <div class="admin-label-mobile">Administering Location...</div>

            <div class="table-wrap debug-line">
                <table class="m-table">
                    <tr>
                        <td width="23%"><strong>' . $row['vaksin_1_nama'] . '</strong></td>
                        <td width="25%">' . $row['vaksin_1_batch'] . '</td>
                        <td width="14%">' . date('jS F Y', strtotime($row['vaksin_1_tgl_admin'])) . '</td>
                        <td width="14%">' . date('jS F Y', strtotime($row['vaksin_1_valid_sampai'])) . '</td>
                        <td width="24%">' . $row['vaksin_1_faskes'] . '</td>
                    </tr>
                    ' . (!empty($row['vaksin_2_nama']) ? '
                    <tr>
                        <td><strong>' . $row['vaksin_2_nama'] . '</strong></td>
                        <td>' . $row['vaksin_2_batch'] . '</td>
                        <td>' . date('jS F Y', strtotime($row['vaksin_2_tgl_admin'])) . '</td>
                        <td>' . date('jS F Y', strtotime($row['vaksin_2_valid_sampai'])) . '</td>
                        <td>' . $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</div>
            <div class="bottom-label-common txt-batch-bottom debug-line">Manufacture and Batch No...</div>
            <div class="bottom-label-common txt-booster-bottom debug-line">Next Booster</div>
            <div class="bottom-label-common txt-stamp-bottom debug-line">Official stamp and signature</div>

            <div class="cert-footer debug-line">
                <div class="footer-disclaimer">
                    <strong>Nomor kode ICV elektronik (eICV) berbeda dengan nomor seri ICV fisik</strong><br>
                    This certificate was issued by Ministry of Health of Indonesia
                </div>
            </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.']);
}