<?php
session_start();
require_once "../config/database.php";

// Check if student is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// 1. Capture the data from the previous selection page (GET)
$session = $_GET['session'] ?? '';
$term = $_GET['term'] ?? '';

// If they somehow got here without selecting session/term, send them back
if (empty($session) || empty($term)) {
    header("Location: results.php");
    exit();
}

$error = "";

// 2. Process the PIN submission (POST)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $pin_input = trim($_POST['pin_code']);
    $session_hidden = $_POST['session_hidden'];
    $term_hidden = $_POST['term_hidden'];

    try {
        // Query the PIN table
        // We check if the PIN exists AND if it has been used less than 3 times
        $stmt = $pdo->prepare("SELECT * FROM pins WHERE pin_code = ?");
        $stmt->execute([$pin_input]);
        $pin_data = $stmt->fetch();

        if ($pin_data) {
            if ($pin_data['times_used'] >= 3) {
                $error = "This PIN has reached its maximum usage limit (3/3).";
            } else {
                // PIN is valid! Update the usage count
                $new_count = $pin_data['times_used'] + 1;
                $update = $pdo->prepare("UPDATE pins SET times_used = ?, status = 'used' WHERE pin_code = ?");
                $update->execute([$new_count, $pin_input]);

                // Redirect to the final report card with the data in the URL
                header("Location: view_final_results.php?session=" . urlencode($session_hidden) . "&term=" . urlencode($term_hidden));
                exit();
            }
        } else {
            $error = "Invalid PIN. Please check the code and try again.";
        }
    } catch (PDOException $e) {
        $error = "System Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify PIN | Student Portal</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f0f2f5; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
        .pin-container { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.1); width: 100%; max-width: 400px; text-align: center; }
        h2 { color: #2c3e50; margin-bottom: 10px; }
        .info-summary { background: #e8f4fd; padding: 10px; border-radius: 8px; color: #2980b9; font-size: 14px; margin-bottom: 25px; }
        .error-box { background: #fee2e2; color: #b91c1c; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; border: 1px solid #fecaca; }
        label { display: block; text-align: left; font-weight: bold; margin-bottom: 8px; color: #4b5563; }
        input[type="text"] { width: 100%; padding: 15px; border: 2px solid #ddd; border-radius: 8px; font-size: 20px; text-align: center; letter-spacing: 4px; box-sizing: border-box; transition: border-color 0.3s; }
        input[type="text"]:focus { border-color: #3498db; outline: none; }
        .btn-verify { width: 100%; padding: 15px; background: #27ae60; color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: bold; cursor: pointer; transition: background 0.3s; margin-top: 10px; }
        .btn-verify:hover { background: #219150; }
        .back-link { display: block; margin-top: 20px; color: #7f8c8d; text-decoration: none; font-size: 14px; }
        .back-link:hover { text-decoration: underline; }
    </style>
</head>
<body>

<div class="pin-container">
    <h2>PIN Verification</h2>
    <div class="info-summary">
        Checking results for:<br>
        <strong><?= htmlspecialchars($session) ?></strong> | <strong><?= htmlspecialchars($term) ?></strong>
    </div>

    <?php if ($error): ?>
        <div class="error-box"><?= $error ?></div>
    <?php endif; ?>

    <form action="verify_pin.php?session=<?= urlencode($session) ?>&term=<?= urlencode($term) ?>" method="POST">
        <input type="hidden" name="session_hidden" value="<?= htmlspecialchars($session) ?>">
        <input type="hidden" name="term_hidden" value="<?= htmlspecialchars($term) ?>">

        <label for="pin_code">Enter 10-Digit PIN</label>
        <input type="text" name="pin_code" id="pin_code" placeholder="XXXXXXXXXX" required maxlength="10" autocomplete="off">
        
        <button type="submit" class="btn-verify">Verify & Unlock Result</button>
    </form>

    <a href="results.php" class="back-link">← Change Session/Term</a>
</div>

</body>
</html>