<?php
require_once 'config/db.php';
// Do not require login here. Public access needed for QR scan.

if (!isset($_GET['token'])) {
    die("Invalid verification link.");
}

$token = $_GET['token'];

// Fetch certificate
$stmt = $pdo->prepare("SELECT * FROM certificates WHERE token = ? AND status = 'active'");
$stmt->execute([$token]);
$cert = $stmt->fetch();

if (!$cert) {
    die("Certificate not found or invalid.");
}

// Redirect directly to PDF as requested
header("Location: generate_pdf.php?token=" . urlencode($token));
exit();

// Fetch settings for template
$settings_stmt = $pdo->query("SELECT template_path, website_name FROM settings WHERE id = 1");
$settings = $settings_stmt->fetch();

// Load coordinates
$coords = include 'config/coordinates.php';

// Conversions for 300 DPI
function mmToPx($mm) { return $mm * 11.81; }
function ptToPx($pt) { return $pt * 4.16; }

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Certificate - <?php echo htmlspecialchars($settings['website_name']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { 
            background: #e9ecef; 
            user-select: none; 
            -webkit-user-select: none; 
            margin: 0; 
            padding: 20px;
            display: flex;
            justify-content: center;
        }
        
        .verify-banner {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #28a745;
            color: white;
            text-align: center;
            padding: 10px;
            z-index: 1000;
            font-weight: bold;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        .cert-container {
            width: 2480px;
            height: 3508px;
            background-image: url('<?php echo $settings['template_path']; ?>');
            background-size: cover;
            position: relative;
            box-shadow: 0 0 20px rgba(0,0,0,0.2);
            background-color: white;
            /* Start with transform origin top-left to avoid weird shifts */
            transform-origin: top left;
             margin: 60px auto; /* Center horizontally with margin for banner */
        }
        
        .cert-field {
            position: absolute;
            font-family: 'Times New Roman', serif; /* Approximate match */
            line-height: 1.2;
            white-space: pre-wrap;
            color: #000;
            font-weight: bold; /* Make text bolder to be visible */
        }

        /* Anti-theft protections */
        @media print {
            body { display: none !important; }
        }
        
        /* Loading overlay */
        #loading { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 2rem; display: none; }
    </style>
    <script>
        // Disable Right Click
        document.addEventListener('contextmenu', event => event.preventDefault());
        // Disable Key Combos (Ctrl+P, Ctrl+S, Ctrl+U)
        document.onkeydown = function(e) {
            if (e.ctrlKey && (e.key === 'p' || e.key === 's' || e.key === 'u')) {
                alert('Action disabled for security.');
                return false;
            }
        };

        // Dynamic Resize Function
        function resizeCert() {
            const container = document.getElementById('certContainer');
            const wrapper = document.getElementById('wrapper'); // We need a wrapper to scroll if needed, or just center
            
            // Calculate scale based on window width
            // We want some padding (e.g. 20px on each side)
            const availableWidth = window.innerWidth - 40;
            const originalWidth = 2480;
            
            let scale = availableWidth / originalWidth;
            
            // Limit max scale to 1 (don't zoom in pixelated) unless on huge screen
            if (scale > 1) scale = 1;
            
            // Apply scale
            container.style.transform = `scale(${scale})`;
            
            // Adjust container height so it doesn't take 3508px scrolling area
            // We need to set the wrapper height or margin-bottom to account for the scaled height
            const scaledHeight = 3508 * scale;
            container.style.marginBottom = `-${3508 - scaledHeight}px`; // Pull up footer space
            
            // Center horizontally manually if needed, but margin: auto handles it if width is set?
            // With transform scale on top-left, we need to center the container itself?
            // Better approach:
            // container.style.left = `${(window.innerWidth - (2480 * scale)) / 2}px`;
        }
        
        window.addEventListener('resize', resizeCert);
        window.addEventListener('load', resizeCert);
    </script>
</head>
<body>

<div class="verify-banner">
    <i class="fa fa-check-circle"></i> Certificate Verified Successfully. This is a system generated preview.
</div>

<div id="wrapper" style="width: 100%; overflow-x: hidden; display: flex; justify-content: center;">
    <div class="cert-container" id="certContainer">
    <?php
    foreach ($coords as $key => $pos) {
        if ($key === 'qr') continue; 

        $value = '';
        switch ($key) {
            case 'reg_no': $value = $cert['registration_no']; break;
            case 'date_reg': $value = date('d-m-Y', strtotime($cert['date_of_registration'])); break;
            case 'name': $value = $cert['name']; break;
            case 'gender': $value = $cert['gender']; break;
            case 'dob': $value = date('d-m-Y', strtotime($cert['dob'])); break;
            case 'place': $value = $cert['place_of_birth']; break;
            case 'mother': $value = $cert['mother_name']; break;
            case 'father': $value = $cert['father_name']; break;
            case 'present_addr': $value = $cert['present_address']; break;
            case 'perm_addr': $value = $cert['permanent_address']; break;
            case 'issue_date': $value = date('d-m-Y H:i:s', strtotime($cert['date_of_issue'])); break;
        }

        $left = mmToPx($pos['x']);
        $top = mmToPx($pos['y']);
        $width = mmToPx($pos['w']);
        $fontSize = ptToPx($pos['size']);
        $align = ($pos['align'] === 'C') ? 'center' : (($pos['align'] === 'R') ? 'right' : 'left');

        echo "<div class='cert-field' style='left: {$left}px; top: {$top}px; width: {$width}px; font-size: {$fontSize}px; text-align: {$align};'>";
        echo htmlspecialchars($value);
        echo "</div>";
    }
    
    // Render QR Code (optional in preview?)
    if (isset($coords['qr'])) {
       $q = $coords['qr'];
       $qrUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . "/verify.php?token=" . $cert['token'];
       // For preview, we can generate it on the fly or just show a placeholder?
       // We can use an API for QR or text
       // Let's invoke a simple QR generator via PHP if needed, but for now skip or use a placeholder div
       // Or generate it? The previous code didn't render it in HTML.
       // Let's render it if needed.
       $left = mmToPx($q['x']);
       $top = mmToPx($q['y']);
       $w = mmToPx($q['w']);
       echo "<div style='position:absolute; left:{$left}px; top:{$top}px; width:{$w}px; height:{$w}px; background:white;'>";
       echo "<img src='https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode($qrUrl) . "' style='width:100%; height:100%;'>";
       echo "</div>";
    }
    ?>
    </div>
</div>

</body>
</html>
