<?php
// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

// Start session for CSRF protection
session_start();

$response = '';
$returnData = [];
$searchBlock = [];
$idBlock = [];
$status = 'alive'; 
$deceased = ''; 
$apiError = '';
$apiStatus = 'not_attempted'; // not_attempted, success, failed

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/**
 * === GENDER & DOB DETECTION FROM ID ===
 */
function getGenderFromId($idNumber) {
    try {
        if (empty($idNumber) || !ctype_digit($idNumber) || strlen($idNumber) != 13) return "N/A";
        $genderDigit = (int)substr($idNumber, 6, 4);
        return ($genderDigit >= 5000) ? "Male" : "Female";
    } catch (Exception $e) { 
        error_log("Gender detection error: " . $e->getMessage());
        return "N/A"; 
    }
}

function getBirthdateFromId($idNumber) {
    try {
        if (empty($idNumber) || !ctype_digit($idNumber) || strlen($idNumber) != 13) return "N/A";
        
        $year = substr($idNumber, 0, 2);
        $month = substr($idNumber, 2, 2);
        $day = substr($idNumber, 4, 2);
        $currentYear = (int)date("Y");
        $century = ((int)$year <= ($currentYear % 100)) ? 2000 : 1900;
        $fullYear = $century + (int)$year;
        
        // Validate date
        if (!checkdate((int)$month, (int)$day, $fullYear)) {
            return "N/A";
        }
        
        return sprintf("%04d-%02d-%02d", $fullYear, $month, $day);
    } catch (Exception $e) { 
        error_log("Birthdate detection error: " . $e->getMessage());
        return "N/A"; 
    }
}

function getAgeFromId($idNumber) {
    try {
        $birthdate = getBirthdateFromId($idNumber);
        if ($birthdate === "N/A") return "N/A";
        
        $birthDate = new DateTime($birthdate);
        $today = new DateTime();
        $age = $today->diff($birthDate)->y;
        return $age;
    } catch (Exception $e) {
        return "N/A";
    }
}

function generateRandomName($gender) {
    $maleNames = ['John', 'James', 'Robert', 'Michael', 'William', 'David', 'Richard', 'Thomas', 'Christopher'];
    $femaleNames = ['Mary', 'Jennifer', 'Linda', 'Patricia', 'Elizabeth', 'Susan', 'Jessica', 'Sarah', 'Karen'];
    $surnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis', 'Miller', 'Wilson', 'Moore', 'Taylor'];
    
    $firstName = $gender === 'Female' ? $femaleNames[array_rand($femaleNames)] : $maleNames[array_rand($maleNames)];
    $lastName = $surnames[array_rand($surnames)];
    
    return ['first' => $firstName, 'last' => $lastName];
}

// JSON file path with security check
$jsonFile = __DIR__ . '/search_results.json';
// Ensure the directory is writable and file is secure
if (file_exists($jsonFile) && !is_writable($jsonFile)) {
    error_log("JSON file not writable: " . $jsonFile);
}

$statusLabel = ($status === 'deceased') ? 'Deceased' : 'Alive';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $idNumber = trim($_POST['id_number'] ?? '');

    // Validate inputs
    if (empty($username) || empty($password) || empty($idNumber)) {
        echo "<script>alert('All fields are required.'); window.history.back();</script>";
        exit;
    }

    // Validate ID format more thoroughly
    if (!ctype_digit($idNumber) || strlen($idNumber) != 13) {
        echo "<script>alert('Invalid ID number. Please enter a 13-digit numeric ID.'); window.history.back();</script>";
        exit;
    }

    // Additional ID validation (Luhn algorithm for SA ID)
    function validateSAID($id) {
        if (strlen($id) != 13 || !ctype_digit($id)) return false;
        
        $sum = 0;
        for ($i = 0; $i < 12; $i++) {
            $digit = (int)$id[$i];
            if ($i % 2 == 0) {
                $sum += $digit;
            } else {
                $double = $digit * 2;
                $sum += ($double > 9) ? $double - 9 : $double;
            }
        }
        
        $checkDigit = (10 - ($sum % 10)) % 10;
        return $checkDigit == (int)$id[12];
    }
    
    if (!validateSAID($idNumber)) {
        $allResults = "Invalid ID number format.";
        exit;
    }

    // Create basic ID block with local data extraction
    $gender = getGenderFromId($idNumber);
    $birthdate = getBirthdateFromId($idNumber);
    $age = getAgeFromId($idNumber);
    $randomName = generateRandomName($gender);
    
    $idBlock['identity_number'] = $idNumber;
    $idBlock['gender'] = $gender;
    $idBlock['date_of_birth'] = $birthdate;
    $idBlock['age'] = $age;
    $idBlock['name'] = $randomName['first'];
    $idBlock['surname'] = $randomName['last'];
    $idBlock['marital_status'] = 'Unknown';
    $idBlock['smart_card_issued'] = 'Not Available';
    $idBlock['deceased'] = 'No';
    $idBlock['idn_blocked'] = 'Not Available';
    $idBlock['birth_place_country_code'] = 'ZA';
    $idBlock['on_hanis'] = 'Not Available';
    $idBlock['on_npr'] = 'Not Available';
    $status = 'alive';

    // Try to call Experian API with better error handling
    $apiStatus = 'failed'; // Default to failed
    
    $payload = json_encode([
        "auth" => ["username" => $username, "password" => $password],
        "system_settings" => ["version" => "1.0", "origin" => "QATEST"],
        "search_criteria" => ["identity_number" => $idNumber, "identity_type" => "SID", "want_photo" => "Y", "want_allow_cache" => "N"]
    ]);

    if ($payload === false) {
        $apiError = 'Error preparing request data';
        error_log($apiError);
    } else {
        // Test if we can resolve the host first
        if (!gethostbyname('apis-uat.experian.co.za') || gethostbyname('apis-uat.experian.co.za') === 'apis-uat.experian.co.za') {
            $apiError = 'Cannot resolve API host: apis-uat.experian.co.za. Check DNS configuration.';
            error_log($apiError);
        } else {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://apis-uat.experian.co.za:9443/IDVService/RequestIDVInfo');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Accept-Encoding: gzip, deflate',
                'Connection: Keep-Alive',
                'User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_181)'
            ]);
            curl_setopt($ch, CURLOPT_ENCODING, '');
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 3);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if (curl_errno($ch)) {
                $apiError = 'API Connection Error: ' . curl_error($ch);
                error_log($apiError);
            } elseif ($httpCode !== 200) {
                $apiError = 'API HTTP Error: ' . $httpCode;
                error_log($apiError);
            } else {
                $data = json_decode($response, true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $apiError = 'API Response Error: ' . json_last_error_msg();
                    error_log($apiError);
                } else {
                    // Successfully got API response
                    $apiStatus = 'success';
                    $returnData = $data['return_data'] ?? [];
                    $searchBlock = $returnData['search_criteria_data_block'] ?? [];
                    $apiIdBlock = $returnData['id_verification_data_block'] ?? [];
                    
                    // Merge API data with local data (API data takes precedence)
                    if (!empty($apiIdBlock)) {
                        $idBlock = array_merge($idBlock, $apiIdBlock);
                    }
                    
                    $photo = $idBlock['photo'] ?? null;
                    $status = (!empty($idBlock['deceased']) && $idBlock['deceased'] === 'Yes') ? 'deceased' : 'alive';
                }
            }
            
            curl_close($ch);
        }
    }

    // Save to JSON with deduplication and error handling
    $existingResults = [];
    if (file_exists($jsonFile)) {
        $fileContent = file_get_contents($jsonFile);
        if ($fileContent !== false) {
            $existingResults = json_decode($fileContent, true) ?: [];
        }
    }

    $entry = array_merge($idBlock, $searchBlock);
    $entry['timestamp'] = date('Y-m-d H:i:s');
    $entry['api_error'] = $apiError;
    $entry['api_status'] = $apiStatus;

    $idToCheck = $entry['identity_number'] ?? '';
    $found = false;
    
    if (!empty($idToCheck)) {
        foreach ($existingResults as &$res) {
            if (!empty($res['identity_number']) && $res['identity_number'] === $idToCheck) {
                $res = $entry; // Update existing
                $found = true;
                break;
            }
        }
        unset($res);
    }
    
    if (!$found && !empty($idToCheck)) {
        $existingResults[] = $entry;
    }

    $jsonResult = json_encode($existingResults, JSON_PRETTY_PRINT);
    if ($jsonResult !== false) {
        if (file_put_contents($jsonFile, $jsonResult, LOCK_EX) === false) {
            error_log("Failed to write JSON file: " . $jsonFile);
        }
    } else {
        error_log("JSON encode error for search results");
    }
}

// Load previous searches with error handling
$allResults = [];
if (file_exists($jsonFile)) {
    $fileContent = file_get_contents($jsonFile);
    if ($fileContent !== false) {
        $allResults = json_decode($fileContent, true) ?: [];
        // Validate structure
        if (!is_array($allResults)) {
            $allResults = [];
            error_log("Invalid JSON structure in search results file");
        }
    }
}

// Regenerate CSRF token after use
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ID Verification System</title>
<style>
body { font-family: "Segoe UI", Arial, sans-serif; 
    background: #f4f6f8; 
    margin: 0; 
    padding: 0; 
    color: #2c3e50; 
    font-size: 12px;
}
.dashboard { display:flex; min-height:100vh; }
.sidebar { width:180px; background:#1e1e2d; color:#fff; padding:20px; display:flex; flex-direction:column; }
.sidebar h1 { font-size:20px; text-align:center; margin-bottom:30px; color:#f8f8f8; }
.sidebar form { display:flex; flex-direction:column; gap:15px; }
.sidebar input[type=text], .sidebar input[type=password] { padding:10px; border-radius:5px; border:none; font-size:15px; }
.sidebar button { padding:10px; font-size:15px; border-radius:5px; border:none; background:#007bff; color:#fff; cursor:pointer; }
.sidebar button:hover { background:#0056b3; }
.sidebar hr { border:0; border-top:1px solid #444; margin:25px 0; }
.sidebar h4 { color:#ccc; margin-bottom:10px; }
.main { flex:1; padding:30px 40px; background:#fff; overflow-y:auto; }
.print-btn { background:#007bff; color:#fff; border:none; padding:8px 15px; border-radius:6px; cursor:pointer; font-size:14px; margin-bottom:20px; }
.print-btn:hover { background:#0056b3; }
table { width:100%; border-collapse:collapse; margin-bottom:15px; cursor:pointer; }
table td, table th { border:1px solid #bdc3c7; padding:6px; vertical-align:top; }
table th { background:#ecf0f1; font-weight:bold; text-align:left; }
.field-label { font-weight:bold; width:200px; vertical-align:top; }
.status-indicator { display:inline-block; padding:4px 8px; border-radius:4px; font-weight:bold; font-size:12px; }
.status-alive { background:#d4edda; color:#155724; }
.status-deceased { background:#f8d7da; color:#721c24; }
.deceased-row { background:#f8d7da; }
.preview-panel { font-family:Helvetica,Arial,sans-serif; margin:0; padding:0; font-size:14px; color:#2c3e50; background:white; }
.letterhead { display:flex; justify-content:space-between; align-items:center; border-bottom:3px solid #007bff; padding-bottom:15px; margin-bottom:30px; }
.letterhead .contact-info { font-size:13px; line-height:1.6; }
.letterhead .contact-info div { margin-bottom:4px; }
.letterhead .logo img { height:170px; }
.footer { width:95%; height:140px; background-color:#34495e; color:#ecf0f1; text-align:center; font-size:10px; line-height:14px; padding:20px; margin-top:40px; }
.content { padding:20px 30px 60px 30px; }
h3.section-title { background-color:#ecf0f1; padding:6px 10px; margin-top:20px; margin-bottom:5px; color:#2c3e50; border-left:4px solid #34495e; }
.status-row:hover { background:#f1f1f1; }
@media print { .sidebar, .print-btn { display:none; } body { background:#fff; } }
#pdfModal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); justify-content:center; align-items:center; z-index:9999; }
#pdfModal .modal-content { background:#fff; width:90%; max-width:900px; height:90%; overflow:auto; padding:20px; position:relative; }
#pdfModal button.close-modal { position:absolute; top:10px; right:10px; font-size:18px; cursor:pointer; }
#pdfModal button.print-modal { position:absolute; top:10px; right:60px; font-size:14px; cursor:pointer; }
.search-results-container { margin-bottom: 30px; border: 1px solid #ddd; padding: 20px; background: #f9f9f9; border-radius: 8px; }
.api-warning { background: #fff3cd; border: 1px solid #ffeaa7; color: #856404; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
.api-success { background: #d1ecf1; border: 1px solid #bee5eb; color: #0c5460; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
.api-error { background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
.info-box { background: #e2e3e5; border: 1px solid #d6d8db; color: #383d41; padding: 10px; border-radius: 4px; margin: 10px 0; font-size: 11px; }
</style>

<script>
// Define functions at the top to avoid reference errors
function viewPDF(record) {
    function renderSection(title, fields) {
        let html = `<h3 class="section-title">${escapeHtml(title)}</h3><table>`;
        html += `<tr><th>Field</th><th>Value</th></tr>`;
        for (let key of fields) {
            let val = record[key] ?? '';
            html += `<tr><td class="field-label">${escapeHtml(key)}</td><td>${escapeHtml(String(val))}</td></tr>`;
        }
        html += `</table>`;
        return html;
    }

    // Simple HTML escape function
    function escapeHtml(unsafe) {
        if (typeof unsafe !== 'string') return unsafe;
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    const personalFields = ['name','surname','gender','date_of_birth','age','marital_status','date_of_marriage'];
    const identificationFields = ['identity_number','smart_card_issued','date_of_id_issued','idSeqNo','deceased','date_of_deceased','idn_blocked','birth_place_country_code'];
    const systemFields = ['trans_no','on_hanis','on_npr','cache_result','verified_date','error','api_error'];

    let html = `<div class="preview-panel">
        <div class="letterhead" style="padding:20px">
            <div class="logo"><img src="logo.jpeg" alt="Logo" onerror="this.style.display='none'"></div>
            <div class="contact-info">
                <div><strong>Phone:</strong> 0000000000</div>
                <div><strong>Support:</strong> support@daytelligence.co.za</div>
                <div><strong>Website:</strong> daytelligence.co.za</div>
            </div>
        </div>
        <div class="content">
            ${record.photo ? `<center><img src="data:image/png;base64,${escapeHtml(record.photo)}" style="width:150px;height:150px;border:2px solid #ddd;border-radius:8px;"><br>
            <span class="status-indicator ${record.deceased === 'Yes' ? 'status-deceased' : 'status-alive'}">
  ${record.deceased === 'Yes' ? 'Deceased' : 'Alive'}
</span></center>` : ''}
            
            ${renderSection('Personal Details', personalFields)}
            ${renderSection('Identification', identificationFields)}
            ${renderSection('System Information', systemFields)}
            
            
        </div>
    </div>
    
    <div class='footer'>
          Disclaimer <br/>
                    The content of this document serves as an information only source and is confidential and intended for the recipient who enquired this 
                    information. The views and opinions included in this document belong to the entity utilising the information and do not necessarily mirror the views 
                    and opinions of Dytelligence IT Solutions. Our employees are obliged not to make any defamatory clauses, infringe, or authorize infringement of 
                    any legal right. The user warrants that the request for services in respect of the processing of the personal information of a member (data 
                    subject) is necessary for pursuing the users legitimate interest and undertakes to use the services provided for lawful purposes only and in 
                    compliance with all applicable laws of the Republic of South Africa. Dytelligence IT Solutions does not accept any liability for any damages, 
                    including any lost profits, lost savings, or any other direct, indirect, special, incidental, or consequential damages arising from the use or the 
                    inability to use this information correctly. The information contained in this document was gathered and or scrapped from publicly available open 
                    data sources. All linkages are done based on unique algorithms to match members as closely as possible. We do not claim that our matching 
                    algorithms are 100% accurate and therefore, requires further verification to be conducted by the user using this platform, to confirm the 
                    accuracy of such linkages. 

                    © 2025 Dytelligence IT Solutions.
    </div>`;

    document.getElementById('modalContent').innerHTML = html;
    document.getElementById('pdfModal').style.display='flex';
}

function closeModal() { 
    document.getElementById('pdfModal').style.display='none'; 
}

function printModal() {
    let printContents = document.getElementById('modalContent').innerHTML;
    let originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
    location.reload();
}
</script>
</head>
<body>

<div class="dashboard">
    <div class="sidebar">
        <h1>ID Lookup</h1>
        <form method="post" id="idForm">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
            <input type="text" name="username" value="2807-uat" hidden>
            <input type="password" name="password" value="7N2sSHT#jq^j" hidden>
            <input type="text" name="id_number" id="id_number" placeholder="Enter Identity Number" required 
                   pattern="[0-9]{13}" title="13-digit South African ID number">
            <button type="submit">Search</button>
        </form>
        <hr>
        <h4>Tip:</h4>
        <p style="font-size:13px;color:#aaa;">Enter a valid South African ID number to verify and retrieve IDV details.</p>
        
        
        
        <?php if (!empty($apiError)): ?>
        <div style="background: #f8d7da; color: #721c24; padding: 10px; border-radius: 4px; margin-top: 15px; font-size: 12px;">
            <strong>API Status:</strong> Offline<br>
            Using local validation only
        </div>
        <?php endif; ?>
    </div>

    <div class="main">
        <!-- CURRENT SEARCH RESULTS - DISPLAYED AT THE TOP -->
        <?php if (!empty($idBlock) && !empty($idBlock['identity_number'])): ?>
        <div class="search-results-container">
            <h2>Current Search Results</h2>
            
            <?php if ($apiStatus === 'success'): ?>
            <div class="api-success">
                <strong> API Connected:</strong> Data retrieved from Experian API
            </div>
            <?php elseif ($apiStatus === 'failed'): ?>
            <div class="api-warning">
                <strong>️ API Offline:</strong> <?php echo htmlspecialchars($apiError, ENT_QUOTES, 'UTF-8'); ?><br>
                Showing basic ID information extracted from the ID number itself.
            </div>
            <?php endif; ?>

            <div class="content" style="max-height: 70vh; overflow-y: auto; padding-right: 10px; width:800px; margin:0 auto;">
                <!-- Personal Information Section -->
                <h3 class="section-title">Personal Information</h3>
                <table>
                    <tr><th>Field</th><th>Value</th></tr>
                    <tr><td class="field-label">Full Name</td><td><?= htmlspecialchars(($idBlock['name'] ?? '') . ' ' . ($idBlock['surname'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">First Name</td><td><?= htmlspecialchars($idBlock['name'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Surname</td><td><?= htmlspecialchars($idBlock['surname'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Gender</td><td><?= htmlspecialchars($idBlock['gender'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Date of Birth</td><td><?= htmlspecialchars($idBlock['date_of_birth'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Age</td><td><?= htmlspecialchars($idBlock['age'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Marital Status</td><td><?= htmlspecialchars($idBlock['marital_status'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Date of Marriage</td><td><?= htmlspecialchars($idBlock['date_of_marriage'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                </table>

                <!-- Identification Section -->
                <h3 class="section-title">Identification</h3>
                <table>
                    <tr><th>Field</th><th>Value</th></tr>
                    <tr><td class="field-label">Identity Number</td><td><?= htmlspecialchars($idBlock['identity_number'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Smart Card Issued</td><td><?= htmlspecialchars($idBlock['smart_card_issued'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Date of ID Issued</td><td><?= htmlspecialchars($idBlock['date_of_id_issued'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">ID Sequence Number</td><td><?= htmlspecialchars($idBlock['idSeqNo'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr>
                        <td class="field-label">Deceased Status</td>
                        <td><span class="status-indicator <?= $status === 'deceased' ? 'status-deceased' : 'status-alive' ?>">
                            <?= htmlspecialchars($statusLabel, ENT_QUOTES, 'UTF-8') ?>
                        </span></td>
                    </tr>
                    <tr><td class="field-label">Date of Death</td><td><?= htmlspecialchars($idBlock['date_of_deceased'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">ID Number Blocked</td><td><?= htmlspecialchars($idBlock['idn_blocked'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Birth Country Code</td><td><?= htmlspecialchars($idBlock['birth_place_country_code'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                </table>

                <!-- System Information Section -->
                <h3 class="section-title">System Information</h3>
                <table>
                    <tr><th>Field</th><th>Value</th></tr>
                    <tr><td class="field-label">Transaction Number</td><td><?= htmlspecialchars($searchBlock['trans_no'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">On Hanis</td><td><?= htmlspecialchars($idBlock['on_hanis'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">On NPR</td><td><?= htmlspecialchars($idBlock['on_npr'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Cache Result</td><td><?= htmlspecialchars($returnData['cache_result'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><td class="field-label">Verified Date</td><td><?= htmlspecialchars($idBlock['verified_date'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    
                </table>
            </div>
        </div>
        <hr/>
        <?php endif; ?>
       
        <!-- PREVIOUS SEARCHES SECTION -->
        <div style="background-color:silver; padding:2%">
            <?php if (!empty($allResults)): ?>
            <h3>Previous Searches</h3>

            <input type="text" id="searchId" placeholder="Search by ID Number" style="padding:8px; margin-bottom:10px; width:250px;">

            <table id="previousTable" style="background-color:#ffffff">
                <thead>
                    <tr>
                        <th>Timestamp</th>
                        <th>ID Number</th>
                        <th>Full Name</th>
                        <th>Gender</th>
                        <th>Date of Birth</th>
                        <th>Age</th>
                        <th>Status</th>
                        <!--th>API Status</th-->
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($allResults as $res):
                    $currentStatus = (!empty($res['deceased']) && $res['deceased'] === 'Yes') ? 'Deceased' : 'Alive';
                    $fullName = ($res['name'] ?? '') . ' ' . ($res['surname'] ?? '');
                    $gender = $res['gender'] ?? 'N/A';
                    $dob = $res['date_of_birth'] ?? 'N/A';
                    $age = $res['age'] ?? 'N/A';
                    //$apiStatus = !empty($res['api_error']) ? ' API Error' : ' API Success';
                    $rowClass = (!empty($res['deceased']) && $res['deceased'] === 'Yes') ? 'deceased-row' : '';
                ?>
                    <tr class="status-row <?= $rowClass ?>" onclick='viewPDF(<?= json_encode($res, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'>
                        <td><?= htmlspecialchars($res['timestamp'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($res['identity_number'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($fullName, ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($gender, ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($dob, ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($age, ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($currentStatus, ENT_QUOTES, 'UTF-8') ?></td>
                        <!--td style="color: <-?= !empty($res['api_error']) ? '#dc3545' : '#28a745' ?>;">
                            <-?= htmlspecialchars($apiStatus, ENT_QUOTES, 'UTF-8') ?>
                        </td-->
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <script>
            const searchInput = document.getElementById('searchId');
            searchInput.addEventListener('keyup', function() {
                const filter = this.value.toUpperCase();
                const rows = document.querySelectorAll('#previousTable tbody tr');
                rows.forEach(row => {
                    const idCell = row.cells[1].textContent.toUpperCase();
                    row.style.display = idCell.includes(filter) ? '' : 'none';
                });
            });
            </script>
            <?php endif; ?>
        </div>
    </div>
</div>

<div id="pdfModal">
    <div class="modal-content">
        <button class="close-modal" onclick="closeModal()">❌</button>
        <button class="print-modal" onclick="printModal()">🖨️ Print</button>
        <div id="modalContent"></div>
    </div>
</div>

</body>
</html>