<?php
require_once('source/dbconfig.php');
require_once('source/function.php');

session_start();

// Redirect if already logged in
if (isset($_SESSION['student'])) {
    header("Location: welcome.php");
    exit();
}

$error = null;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $registration_no = $_POST['registration_no'];
    $class = $_POST['class'];
    $term = $_POST['term'];
    $session = $_POST['session'];
    $pin = $_POST['pin'];

    try {
        $DBH->beginTransaction();

        // 1. Verify Admission Number Exists and is active
        $stmt = $DBH->prepare("
            SELECT * FROM tbl_user 
            WHERE registration_no = :reg_no
            AND teacher = 'false'
            AND status = 'Active'
        ");
        $stmt->execute(['reg_no' => $registration_no]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$student) {
            throw new Exception("Invalid admission number or account not active");
        }

        // 2. Verify PIN exists and is either unassigned or assigned to this registration number 
        $stmt = $DBH->prepare("
            SELECT * FROM tbl_pin 
            WHERE pin = :pin
            AND term = :term
            AND year = :session
            AND (reg_no IS NULL OR reg_no = '' OR reg_no = :reg_no)
        ");
        $stmt->execute([
            'pin' => $pin,
            'term' => $term,
            'session' => $session,
            'reg_no' => $registration_no
        ]);
        $pinRecord = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$pinRecord) {
            throw new Exception("PIN not found, already assigned to another student, or wrong Academic Session selected. Please purchase a new PIN from the school or verify the selected session.");
        }

        // 3. Update PIN record with student details
        $stmt = $DBH->prepare("
            UPDATE tbl_pin 
            SET reg_no = :reg_no,
                class = :class,
                date_time = NOW(),
                dt_stamp_start = NOW(),
                dt_stamp_end = DATE_ADD(NOW(), INTERVAL 3 MONTH)
            WHERE pin = :pin
            AND term = :term
            AND year = :year
            AND (reg_no IS NULL OR reg_no = '' OR reg_no = :reg_no)
        ");
        $stmt->execute([
            'reg_no' => $registration_no,
            'class' => $class,
            'pin' => $pin,
            'term' => $term,
            'year' => $session
        ]);
        
        // Check if any rows were affected
        if ($stmt->rowCount() === 0) {
            throw new Exception("Failed to update PIN record. It may already be assigned to another student.");
        }
        
        // 4. Update Session
        $_SESSION['student'] = $student;
        $_SESSION['exam_info'] = [
            'class' => $class,
            'term' => $term,
            'session' => $session,
            'pin' => $pin
        ];
        
        $DBH->commit();
        header("Location: welcome.php");
        exit();
        
    } catch (Exception $e) {
        $DBH->rollBack();
        $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>BKMS-BLC CBT Portal - Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #e8f5e9;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .login-container {
            max-width: 600px;
            margin: 5% auto;
            padding: 30px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .school-logo {
            max-width: 150px;
            display: block;
            margin: 0 auto 20px;
        }
        .school-header {
            color: #2e7d32;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-label {
            font-weight: 600;
            color: #2e7d32;
        }
        .btn-login {
            background-color: #2e7d32;
            border: none;
            padding: 10px 0;
            font-weight: 600;
        }
        .form-control, .form-select {
            border: 1px solid #2e7d32;
        }
        .form-control:focus, .form-select:focus {
            border-color: #2e7d32;
            box-shadow: 0 0 0 0.25rem rgba(46, 125, 50, 0.25);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="login-container">
            <img src="assets/images/bkms.png" alt="BKMS Logo" class="school-logo">
            <h2 class="school-header">BKMS-BLC CBT Portal</h2>
            
            <?php if (isset($error)): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <form method="POST">
                <div class="row g-3">
                    <div class="col-md-12">
                        <label for="registration_no" class="form-label">ADMISSION NUMBER</label>
                        <input type="text" class="form-control" id="registration_no" name="registration_no" required>
                    </div>
                    
                    <div class="col-md-12">
                        <label for="class" class="form-label">CLASS</label>
                        <select class="form-select" id="class" name="class" required>
                            <option value="">Select Class</option>
                            <?php
                            $classes = $DBH->query("SELECT DISTINCT class FROM tbl_class ORDER BY class");
                            while ($class = $classes->fetch(PDO::FETCH_ASSOC)): ?>
                                <option value="<?php echo htmlspecialchars($class['class']); ?>">
                                    <?php echo htmlspecialchars($class['class']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-12">
                        <label for="term" class="form-label">TERM</label>
                        <select class="form-select" id="term" name="term" required>
                            <option value="">Select Term</option>
                            <option value="1st Term">1st Term</option>
                            <option value="2nd Term">2nd Term</option>
                            <option value="3rd Term">3rd Term</option>
                        </select>
                    </div>
                    
                    <div class="col-md-12">
                        <label for="session" class="form-label">SESSION</label>
                        <select class="form-select" id="session" name="session" required>
                            <option value="">Select Session</option>
                            <?php
                            $sessions = $DBH->query("SELECT DISTINCT session FROM tbl_session ORDER BY session DESC");
                            while ($session = $sessions->fetch(PDO::FETCH_ASSOC)): ?>
                                <option value="<?php echo htmlspecialchars($session['session']); ?>">
                                    <?php echo htmlspecialchars($session['session']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-12">
                        <label for="pin" class="form-label">PIN</label>
                        <input type="password" class="form-control" id="pin" name="pin" placeholder="Enter your PIN" required>
                    </div>
                     
                    <div class="col-md-12 mt-4">
                        <button type="submit" class="btn btn-login btn-success w-100">
                            LOGIN
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>