<?php
// admin/pins/assign_pin.php
$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

// 1. Security Check
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../../auth/login.php");
    exit();
}

// 2. Handle the assignment logic
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['assign'])) {
    $student_id = $_POST['student_id'];

    // Find the first available unused PIN
    $stmt = $pdo->query("SELECT pin_code FROM pins WHERE status = 'unused' LIMIT 1");
    $pin = $stmt->fetchColumn();

    if ($pin) {
        try {
            $pdo->beginTransaction();

            // Update the Student's record with this PIN
            $updateStudent = $pdo->prepare("UPDATE students SET result_pin = ? WHERE id = ?");
            $updateStudent->execute([$pin, $student_id]);

            // Mark this PIN as 'used' so no one else gets it
            $updatePin = $pdo->prepare("UPDATE pins SET status = 'used' WHERE pin_code = ?");
            $updatePin->execute([$pin]);

            $pdo->commit();
            $success = "Successfully assigned PIN: <strong>$pin</strong> to the student.";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Transaction failed: " . $e->getMessage();
        }
    } else {
        $error = "No unused PINs left! Please generate more PINs first.";
    }
}

// 3. Fetch all students for the dropdown
$students = $pdo->query("SELECT id, fullname, reg_number FROM students ORDER BY fullname ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Assign PIN | <?php echo $school_name; ?></title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 40px; background: #f4f7f6; }
        .card { background: white; padding: 30px; border-radius: 10px; max-width: 500px; margin: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
        h2 { color: #2c3e50; text-align: center; }
        select, button { width: 100%; padding: 12px; margin: 15px 0; border-radius: 6px; border: 1px solid #ddd; font-size: 16px; }
        button { background: #27ae60; color: white; border: none; cursor: pointer; font-weight: bold; transition: 0.3s; }
        button:hover { background: #219150; }
        .msg { padding: 15px; border-radius: 6px; margin-bottom: 20px; text-align: center; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .nav-links { text-align: center; margin-top: 20px; }
        .nav-links a { color: #3498db; text-decoration: none; font-size: 14px; margin: 0 10px; }
    </style>
</head>
<body>

<div class="card">
    <h2>Assign Student PIN</h2>
    
    <?php if(isset($success)) echo "<div class='msg success'>$success</div>"; ?>
    <?php if(isset($error)) echo "<div class='msg error'>$error</div>"; ?>

    <form method="POST">
        <label for="student_id">Select Student to Receive PIN:</label>
        <select name="student_id" id="student_id" required>
            <option value="">-- Choose a Student --</option>
            <?php foreach($students as $s): ?>
                <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['fullname']) ?> (<?= $s['reg_number'] ?>)</option>
            <?php endforeach; ?>
        </select>

        <button type="submit" name="assign">Link Unused PIN to Student</button>
    </form>

    <div class="nav-links">
        <a href="generate.php">Generate New PINs</a> | 
        <a href="../dashboard.php">Admin Dashboard</a>
    </div>
</div>

</body>
</html>