<?php
session_start();

// ✅ Database connection
$con = mysqli_connect('localhost', 'hmrsaasc_cert765', 'hmrsaasc_cert765', 'hmrsaasc_cert765');
if (!$con) {
    die("Database Connection Failed: " . mysqli_connect_error());
}

// ✅ Collect input from form
$name   = trim($_POST['name']);
$email  = trim($_POST['email']);
$post   = trim($_POST['post']);
$token  = trim($_POST['token']); // <-- new field for token/PIN

if (empty($name) || empty($email) || empty($post) || empty($token)) {
    echo "<script>
        alert('Please enter your full name, email, post/training, and token.');
        window.location.href='index.html';
    </script>";
    exit();
}

// ✅ Validate Token
$tq = "SELECT * FROM tokens WHERE token_code='$token' AND status='unused'";
$tres = mysqli_query($con, $tq);

if (!$tres || mysqli_num_rows($tres) < 1) {
    echo "<script>
        alert('Invalid or already used token. Please buy a valid token for ₦2000 (Two Thousand Naira) only. Contact 08023296883 or 08030404960 or any of those numbers via whatsapp');
        window.location.href='index.html';
    </script>";
    exit();
}

// ✅ Fetch intern record
$q = "SELECT * FROM intern WHERE NAME='$name' AND EMAIL='$email' AND POST='$post'";
$result = mysqli_query($con, $q);

if (!$result || mysqli_num_rows($result) < 1) {
    echo "<script>
        alert('No matching record found! Check your details or complete registration.');
        window.location.href='index.html';
    </script>";
    exit();
}

$row = mysqli_fetch_assoc($result);
$start     = $row['START_DATE'];
$end       = $row['END_DATE'];
$passport  = $row['PASSPORT']; // e.g., "uploads/xxx.jpg"

// ✅ Build correct passport path (handle both possible upload folders)
$passport_path = __DIR__ . '/' . $passport;
if (!file_exists($passport_path)) {
    $passport_path = __DIR__ . '/Register/' . $passport;
}

// ✅ Generate certificate PDF
require("fpdf/fpdf.php");
include("phpqrcode/qrlib.php");

$pdf = new FPDF('L');
$pdf->AddPage();
$pdf->SetTitle("Certificate", false);

// ✅ Add background certificate template
$pdf->Image('Certificate.jpg', 3, 3, 291, 203);

// ✅ Add recipient name (auto-centered)
$pdf->SetFont("Courier", "B", 42);
$pdf->SetTextColor(10, 43, 73);

$nameWidth = $pdf->GetStringWidth($name);  // measure width of name text
$pageWidth = $pdf->GetPageWidth();         // full page width in mm

// Calculate X to center the name horizontally
$x = ($pageWidth - $nameWidth) / 2;

// Set Y position (106) and X dynamically
$pdf->SetXY($x, 106);

// Draw the name
$pdf->Cell($nameWidth, 10, $name, 0, 1, "L");

// ✅ Add start and end dates
$pdf->SetXY(67, 124);
$pdf->SetFont("Courier", "B", 12);
$pdf->SetTextColor(10, 43, 73);
$pdf->Cell(0, 10, $start, 0, 1, "L");

$pdf->SetXY(220, 124);
$pdf->Cell(0, 10, $end, 0, 1, "L");

// ✅ Add QR code with verification URL
$verifyURL = "https://hmrsaas.com.ng/cert/verify.php?token=" . urlencode($token);  
// If still on localhost, use:  "http://localhost/cert/verify.php?token=" . $token;

$qrcode_path = __DIR__ . "/Verify.png";
QRcode::png($verifyURL, $qrcode_path, QR_ECLEVEL_L, 4);

$pdf->Image($qrcode_path, 138.5, 158, 20, 20);

// ✅ Add passport photo (absolute placement fix)
if (file_exists($passport_path)) {
    $pdf->SetXY(0, 0);
    $pdf->Image($passport_path, 135, 85, 20, 20, '', '', '', false, 300, '', false, false, 0);
} else {
    error_log("Passport file not found at: " . $passport_path);
}

// ✅ Mark token as used after successful generation
$update = "UPDATE tokens 
           SET status='used', used_by='$email', used_on=NOW() 
           WHERE token_code='$token'";
mysqli_query($con, $update);

// ✅ Output PDF
$pdf->Output();
?>
