<?php
// 1. Aktifkan laporan error untuk debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 2. Sertakan koneksi database
include $_SERVER['DOCUMENT_ROOT'] . '/assets/db/db.php';

// 3. Pastikan data dikirim melalui POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Ambil data identitas dari form
    $no_icv    = mysqli_real_escape_string($conn, $_POST['no_icv']);
    $nama      = mysqli_real_escape_string($conn, $_POST['nama_lengkap']);
    $paspor    = mysqli_real_escape_string($conn, $_POST['no_paspor']);
    $tgl_lahir = $_POST['tgl_lahir'];
    
    // Ambil data Vaksin 1
    $v1_nama    = mysqli_real_escape_string($conn, $_POST['vaksin_1_nama']);
    $v1_batch   = mysqli_real_escape_string($conn, $_POST['vaksin_1_batch']);
    $v1_tgl     = !empty($_POST['vaksin_1_tgl_admin']) ? $_POST['vaksin_1_tgl_admin'] : NULL;
    $v1_valid   = !empty($_POST['vaksin_1_valid_sampai']) ? $_POST['vaksin_1_valid_sampai'] : NULL;
    $v1_faskes  = mysqli_real_escape_string($conn, $_POST['vaksin_1_faskes']);

    // Ambil data Vaksin 2
    $v2_nama    = mysqli_real_escape_string($conn, $_POST['vaksin_2_nama']);
    $v2_batch   = mysqli_real_escape_string($conn, $_POST['vaksin_2_batch']);
    $v2_tgl     = !empty($_POST['vaksin_2_tgl_admin']) ? $_POST['vaksin_2_tgl_admin'] : NULL;
    $v2_valid   = !empty($_POST['vaksin_2_valid_sampai']) ? $_POST['vaksin_2_valid_sampai'] : NULL;
    $v2_faskes  = mysqli_real_escape_string($conn, $_POST['vaksin_2_faskes']);

    // 4. Query Insert sesuai struktur gambar database Anda
    // Nama kolom disesuaikan: no_icv, nama_lengkap, no_paspor, tgl_lahir, vaksin_1_nama, vaksin_2_nama, dsb.
    
    $query = "INSERT INTO sertifikat_vaksin 
              (no_icv, nama_lengkap, no_paspor, tgl_lahir, 
               vaksin_1_nama, vaksin_2_nama, vaksin_1_batch, vaksin_2_batch, 
               vaksin_1_tgl_admin, vaksin_2_tgl_admin, vaksin_1_valid_sampai, 
               vaksin_2_valid_sampai, vaksin_1_faskes, vaksin_2_faskes) 
              VALUES 
              ('$no_icv', '$nama', '$paspor', '$tgl_lahir', 
               '$v1_nama', '$v2_nama', '$v1_batch', '$v2_batch', 
               " . ($v1_tgl ? "'$v1_tgl'" : "NULL") . ", 
               " . ($v2_tgl ? "'$v2_tgl'" : "NULL") . ", 
               " . ($v1_valid ? "'$v1_valid'" : "NULL") . ", 
               " . ($v2_valid ? "'$v2_valid'" : "NULL") . ", 
               '$v1_faskes', '$v2_faskes')";

    if ($conn->query($query) === TRUE) {
        echo "<script>
                alert('Data Berhasil Disimpan!');
                window.location.href='list_sertifikat.php';
              </script>";
    } else {
        echo "<h4>Gagal Menyimpan Data</h4>";
        echo "Error: " . $conn->error;
        echo "<br><br><a href='admin.php'>Kembali ke Form</a>";
    }
} else {
    echo "Akses langsung tidak diizinkan.";
}
?>