<?php
// verify.php — Public certificate verification page (no login required by
// design). Anyone who scans a certificate's QR code lands here.
//
// SECURITY (2026-08-31): This page intentionally shows a SUMMARY-ONLY
// verification card and must NEVER link to, embed, or expose the full
// printable/downloadable certificate (generate_certificate.php). Doing so
// previously let anyone with a scanned/guessed QR link view, print, and
// save the full certificate with no login at all -- the exact abuse this
// page exists to prevent. Every field shown below already appears on the
// physical/digital certificate itself, so this card leaks nothing beyond
// what a legitimate certificate holder already has in hand.
//
// Accepts EITHER:
//   ?token=<64-char CertToken>   (preferred — what new QR codes generate)
//   ?job=<Job_No>                (legacy fallback, kept for old certificates)

require_once 'db.php';

$token = $_GET['token'] ?? null;
$jobNo = $_GET['job'] ?? null;

$job = null;

if ($token) {
    $stmt = $pdo->prepare("SELECT * FROM tbl_jobs WHERE CertToken = ?");
    $stmt->execute([$token]);
    $job = $stmt->fetch(PDO::FETCH_ASSOC);
} elseif ($jobNo) {
    $stmt = $pdo->prepare("SELECT * FROM tbl_jobs WHERE Job_No = ?");
    $stmt->execute([$jobNo]);
    $job = $stmt->fetch(PDO::FETCH_ASSOC);

    // Self-heal: if this legacy job has no CertToken yet, generate one now
    // so future scans of a re-printed certificate use the secure token link.
    if ($job && empty($job['CertToken'])) {
        // Same 128-bit / 32-char token length as generate_certificate.php.
        $newToken = bin2hex(random_bytes(16));
        $upd = $pdo->prepare("UPDATE tbl_jobs SET CertToken = ? WHERE ID = ?");
        $upd->execute([$newToken, $job['ID']]);
        $job['CertToken'] = $newToken;
    }
} else {
    die("Invalid certificate link.");
}

$clientName = $job['Client_Name'] ?? 'N/A';
$category   = $job['Category'] ?? 'N/A';
$inspector  = $job['Engineer'] ?? 'N/A';
$approval   = strtoupper($job['Approval'] ?? 'PASS');

// Same category detection generate_certificate.php uses, so this card
// branches the same way the real certificate template does.
$isTraining = $job ? (strcasecmp($category, 'Training') === 0) : false;

$itemName = $job['Item_Name'] ?? 'N/A';
$serialNo = $job['Serial_No'] ?? 'N/A';

// Site Name is stored as a foreign key (Site_ID); resolve it the same way
// generate_certificate.php does.
$siteName = 'N/A';
if (!empty($job['Site_ID'])) {
    try {
        $stmtSite = $pdo->prepare('SELECT Site_Name FROM tbl_client_sites WHERE SiteID = ? AND Deleted_At IS NULL LIMIT 1');
        $stmtSite->execute([$job['Site_ID']]);
        $siteVal = $stmtSite->fetchColumn();
        if ($siteVal !== false && trim((string) $siteVal) !== '') {
            $siteName = trim($siteVal);
        }
    } catch (\Throwable $e) {
        // keep default 'N/A'
    }
}

$subLocation    = trim($job['Sub_Location'] ?? '') ?: 'N/A';
$inspectionType = trim($job['Inspection_Type'] ?? '') ?: 'In-Service Thorough Examination';

$issueDateRaw  = $job['Issue_Date'] ?? null;
$expiryDateRaw = $job['Expiry_Date'] ?? null;
$issueDate  = !empty($issueDateRaw)  ? date('d M Y', strtotime($issueDateRaw))  : 'N/A';
$expiryDate = !empty($expiryDateRaw) ? date('d M Y', strtotime($expiryDateRaw)) : 'N/A';
$isExpired  = !empty($expiryDateRaw) && (strtotime($expiryDateRaw) < strtotime('today'));

// Training-specific fields (only fetched for Training-category jobs).
$traineeName        = 'N/A';
$courseContent      = '';
$trainingParameters = '';
if ($job && $isTraining) {
    try {
        $stmtTraining = $pdo->prepare('SELECT Trainee_Name, Course_Content, Training_Parameters FROM tbl_training_records WHERE JobID = ? LIMIT 1');
        $stmtTraining->execute([$job['ID']]);
        $trainingRow = $stmtTraining->fetch(PDO::FETCH_ASSOC);
        if ($trainingRow) {
            $traineeName        = trim((string) ($trainingRow['Trainee_Name'] ?? '')) ?: 'N/A';
            $courseContent      = trim((string) ($trainingRow['Course_Content'] ?? ''));
            $trainingParameters = trim((string) ($trainingRow['Training_Parameters'] ?? ''));
        }
    } catch (\PDOException $e) {
        // keep defaults
    }
}

$verifiedAt = date('Y-m-d H:i:s');
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Liftek Certificate Verification</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container my-5" style="max-width: 600px;">
    <div class="card shadow border-0 text-center p-4">
        <?php if ($job): ?>
            <div class="text-success mb-3">
                <i class="fa-solid fa-circle-check fa-4x"></i>
            </div>
            <h4 class="fw-bold">AUTHENTIC LIFTEK CERTIFICATE</h4>
            <p class="text-muted small">This inspection record is officially verified on the Liftek Iraq database.</p>

            <hr>

            <table class="table table-sm text-start my-3">
                <tr><th>Job No:</th><td><strong class="text-primary"><?= htmlspecialchars($job['Job_No']); ?></strong></td></tr>
                <tr><th>Client Name:</th><td><?= htmlspecialchars($clientName); ?></td></tr>
                <tr><th>Category:</th><td><?= htmlspecialchars($category); ?></td></tr>
                <tr><th>Site Name:</th><td><?= htmlspecialchars($siteName); ?></td></tr>
                <tr><th>Sub Location:</th><td><?= htmlspecialchars($subLocation); ?></td></tr>
                <tr><th>Type of Inspection:</th><td><?= htmlspecialchars($inspectionType); ?></td></tr>

                <?php if ($isTraining): ?>
                    <tr><th>Trainee Name:</th><td><?= htmlspecialchars($traineeName); ?></td></tr>
                    <?php if ($courseContent !== ''): ?>
                        <tr><th>Training Course:</th><td><?= nl2br(htmlspecialchars($courseContent)); ?></td></tr>
                    <?php endif; ?>
                    <?php if ($trainingParameters !== ''): ?>
                        <tr><th>Training Parameters:</th><td><?= nl2br(htmlspecialchars($trainingParameters)); ?></td></tr>
                    <?php endif; ?>
                <?php else: ?>
                    <tr><th>Item Name:</th><td><?= htmlspecialchars($itemName); ?></td></tr>
                    <tr><th>Serial No:</th><td><code><?= htmlspecialchars($serialNo); ?></code></td></tr>
                <?php endif; ?>

                <tr><th>Issue Date:</th><td><?= htmlspecialchars($issueDate); ?></td></tr>
                <tr><th>Expiry Date:</th><td><?= htmlspecialchars($expiryDate); ?></td></tr>
                <tr><th>Validity:</th><td>
                    <?php if ($expiryDate === 'N/A'): ?>
                        <span class="badge bg-secondary">N/A</span>
                    <?php elseif ($isExpired): ?>
                        <span class="badge bg-danger">EXPIRED</span>
                    <?php else: ?>
                        <span class="badge bg-success">VALID</span>
                    <?php endif; ?>
                </td></tr>
                <tr><th>Inspector:</th><td><?= htmlspecialchars($inspector); ?></td></tr>
                <tr><th>Status:</th><td><span class="badge <?= $approval === 'PASS' ? 'bg-success' : 'bg-danger'; ?>"><?= htmlspecialchars($approval); ?></span></td></tr>
            </table>

            <p class="text-muted" style="font-size: 11px;">
                Verified live on <?= htmlspecialchars($verifiedAt); ?>.<br>
                This page shows a verification summary only. For an official printed/digital
                copy of this certificate, please contact Liftek Iraq directly.
            </p>
        <?php else: ?>
            <div class="text-danger mb-3">
                <i class="fa-solid fa-triangle-exclamation fa-4x"></i>
            </div>
            <h4 class="fw-bold text-danger">CERTIFICATE NOT FOUND</h4>
            <p class="text-muted">The certificate scanned does not exist in the official register. Please check with Liftek technical support.</p>
        <?php endif; ?>
    </div>
</div>

</body>
</html>
