<?php
require_once('source/dbconfig.php');
require_once('source/function.php');
session_start();
date_default_timezone_set('Africa/Lagos');

if (isset($_SESSION['student'])) {
    header("Location: welcome.php");
    exit();
}

// School information
$schoolName = "Henzy Royal International School";
$schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
$supportPhone = "+234 803 292 9756";
$supportEmail = "support@hris.com.ng";
$schoolMotto = "Excellence, Integrity, Service";

// Assessment types
$assessmentTypes = ['CA1', 'CA2', 'CA3', 'Term Exam', 'Mock Exam'];

$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $registration_no = trim($_POST['registration_no']);
    $class = trim($_POST['class']);
    $term = trim($_POST['term']);
    $session_input = trim($_POST['session']);
    $assessment_type = trim($_POST['assessment_type']);
    $pin = trim($_POST['pin']);

    try {
        $DBH->beginTransaction();

        // Verify student exists
        $stmt = $DBH->prepare("SELECT * FROM tbl_user WHERE registration_no = ? AND teacher = 'false' AND status = 'Active'");
        $stmt->execute([$registration_no]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$student) throw new Exception("Invalid admission number or inactive account.");

        // Check if there's an exam-subject combination for this class, term, session, and assessment type
        $stmt = $DBH->prepare("
            SELECT es.* 
            FROM tbl_exam_subject es
            JOIN tbl_exam_class ec ON es.exam_id = ec.exam_id
            WHERE ec.class = ? 
            AND ec.term = ? 
            AND ec.session = ?
            AND es.assessment_type = ?
            LIMIT 1
        ");
        $stmt->execute([$class, $term, $session_input, $assessment_type]);
        $examSubject = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$examSubject) {
            throw new Exception("No $assessment_type exam found for $class in $term, $session_input. Please contact your teacher.");
        }

        // Lock and fetch PIN
        $stmt = $DBH->prepare("SELECT * FROM tbl_pin WHERE pin = ? FOR UPDATE");
        $stmt->execute([$pin]);
        $pinRecord = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$pinRecord) throw new Exception("PIN not found.");

        $now = date('Y-m-d H:i:s');

        if (!empty($pinRecord['reg_no'])) {
            // PIN has been used before
            if ($pinRecord['reg_no'] !== $registration_no) {
                throw new Exception("This PIN has already been used by another student.");
            }

            if ($pinRecord['year'] !== $session_input) {
                throw new Exception("This PIN was used in a different session: " . $pinRecord['year']);
            }
            
            // No validation for assessment type - PIN can be used for multiple assessment types
            // Just increment used_count and log
            $DBH->prepare("UPDATE tbl_pin SET used_count = used_count + 1, updated_at = ? WHERE pin = ?")
                ->execute([$now, $pin]);

        } else {
            // First time use — assign with assessment type
            $DBH->prepare("
                UPDATE tbl_pin SET
                    reg_no = ?,
                    class = ?,
                    term = ?,
                    year = ?,
                    date_time = ?,
                    dt_stamp_start = ?,
                    created_date_time = ?,
                    updated_at = ?,
                    used_count = 1
                WHERE pin = ?
            ")->execute([
                $registration_no,
                $class,
                $term,
                $session_input,
                $now,
                $now,
                $now,
                $now,
                $pin
            ]);
        }

        // Log to pin_logins table with assessment type
        $DBH->prepare("
            INSERT INTO pin_logins (pin, reg_no, class, term, year, login_time)
            VALUES (?, ?, ?, ?, ?, ?)
        ")->execute([$pin, $registration_no, $class, $term, $session_input, $now]);

        // Store session with assessment type
        $_SESSION['student'] = $student;
        $_SESSION['exam_info'] = [
            'class' => $class,
            'term' => $term,
            'session' => $session_input,
            'assessment_type' => $assessment_type,
            'pin' => $pin
        ];

        $DBH->commit();
        header("Location: welcome.php");
        exit();

    } catch (Exception $e) {
        $DBH->rollBack();
        $error = $e->getMessage();
    }
}

// Function to get badge class for assessment type
function getAssessmentBadgeClass($type) {
    switch($type) {
        case 'CA1': return 'badge-ca1';
        case 'CA2': return 'badge-ca2';
        case 'CA3': return 'badge-ca3';
        case 'Term Exam': return 'badge-term';
        case 'Mock Exam': return 'badge-mock';
        default: return 'badge-secondary';
    }
}
?>

<!-- HTML Section -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= $schoolName ?> - CBT Portal Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="../coll_logo.png">
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-blue: #1a4b8c;
            --secondary-gold: #FFD700;
            --dark-blue: #0f2b4f;
            --light-blue: #4a7db5;
            --light-gold: #FFF1B8;
            --bg-light: #f5f9ff;
            --success-green: #28a745;
            --danger-red: #dc3545;
        }
        
        body {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            font-family: 'Poppins', sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            padding: 20px;
            position: relative;
            overflow-x: hidden;
        }
        
        /* Animated background */
        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="%23FFD700" fill-opacity="0.05" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,122.7C672,117,768,139,864,154.7C960,171,1056,181,1152,170.7C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>') no-repeat bottom;
            background-size: cover;
            opacity: 0.3;
            pointer-events: none;
        }
        
        .login-container {
            max-width: 650px;
            width: 100%;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            position: relative;
            z-index: 1;
            border: 1px solid rgba(255, 215, 0, 0.3);
        }
        
        .login-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            padding: 40px 30px 30px;
            text-align: center;
            position: relative;
            border-bottom: 3px solid var(--secondary-gold);
        }
        
        .login-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, var(--secondary-gold), var(--primary-blue));
        }
        
        .logo-container {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
        }
        
        .school-logo {
            width: 80px;
            height: 80px;
            object-fit: contain;
            background: white;
            padding: 10px;
            border-radius: 50%;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            border: 3px solid var(--secondary-gold);
            margin-right: 15px;
            transition: all 0.3s ease;
        }
        
        .school-logo:hover {
            transform: rotate(360deg) scale(1.1);
            box-shadow: 0 8px 25px rgba(255, 215, 0, 0.4);
        }
        
        .school-title {
            text-align: left;
        }
        
        .school-name {
            font-family: 'Playfair Display', serif;
            font-weight: 700;
            font-size: 1.5rem;
            margin-bottom: 5px;
            line-height: 1.2;
        }
        
        .school-motto {
            font-size: 0.9rem;
            color: var(--secondary-gold);
            font-style: italic;
            margin-bottom: 0;
        }
        
        .login-title {
            font-size: 1.8rem;
            font-weight: 600;
            margin-top: 10px;
            margin-bottom: 5px;
        }
        
        .login-subtitle {
            font-size: 0.95rem;
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .login-body {
            padding: 40px 30px;
        }
        
        .form-label {
            font-weight: 600;
            color: var(--dark-blue);
            margin-bottom: 0.5rem;
        }
        
        .form-label i {
            color: var(--secondary-gold);
            margin-right: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
            outline: none;
        }
        
        /* Assessment Type Badge Styles */
        .assessment-badge {
            display: inline-block;
            padding: 0.3rem 0.8rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-left: 0.5rem;
        }
        
        .badge-ca1 { background: linear-gradient(135deg, #17a2b8, #138496); color: white; }
        .badge-ca2 { background: linear-gradient(135deg, #28a745, #218838); color: white; }
        .badge-ca3 { background: linear-gradient(135deg, #ffc107, #e0a800); color: var(--dark-blue); }
        .badge-term { background: linear-gradient(135deg, #6610f2, #520dc2); color: white; }
        .badge-mock { background: linear-gradient(135deg, #fd7e14, #e56b08); color: white; }
        .badge-secondary { background: linear-gradient(135deg, #6c757d, #545b62); color: white; }
        
        .btn-login {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            border: none;
            color: white;
            font-weight: 600;
            padding: 1rem;
            font-size: 1.1rem;
            border-radius: 50px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            border: 1px solid var(--secondary-gold);
            width: 100%;
            margin-top: 1rem;
        }
        
        .btn-login::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            transform: translate(-50%, -50%);
            transition: width 0.5s, height 0.5s;
        }
        
        .btn-login:hover::before {
            width: 300px;
            height: 300px;
        }
        
        .btn-login:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(26, 75, 140, 0.4);
        }
        
        .btn-login i {
            margin-right: 0.5rem;
            color: var(--secondary-gold);
        }
        
        .alert {
            border-radius: 10px;
            border: none;
            padding: 1rem 1.5rem;
            margin: 20px 30px 0;
            border-left: 4px solid transparent;
            animation: slideIn 0.5s ease;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            color: #721c24;
            border-left-color: #dc3545;
        }
        
        .alert i {
            margin-right: 0.5rem;
        }
        
        .support-info {
            text-align: center;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 2px dashed rgba(255, 215, 0, 0.3);
        }
        
        .support-link {
            color: var(--primary-blue);
            text-decoration: none;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin: 0 10px;
        }
        
        .support-link:hover {
            color: var(--secondary-gold);
            transform: translateY(-2px);
        }
        
        .support-link i {
            color: var(--secondary-gold);
        }
        
        .copyright {
            text-align: center;
            margin-top: 20px;
            font-size: 0.8rem;
            color: #666;
        }
        
        .copyright a {
            color: var(--primary-blue);
            text-decoration: none;
        }
        
        .copyright a:hover {
            color: var(--secondary-gold);
        }
        
        .info-note {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-radius: 10px;
            padding: 10px 15px;
            margin-top: 20px;
            font-size: 0.85rem;
            color: var(--dark-blue);
            border-left: 3px solid var(--secondary-gold);
        }
        
        .info-note i {
            color: var(--secondary-gold);
            margin-right: 8px;
        }
        
        .floating-shape {
            position: absolute;
            background: rgba(255, 215, 0, 0.1);
            border-radius: 50%;
            z-index: 0;
        }
        
        .shape1 {
            width: 200px;
            height: 200px;
            top: -50px;
            right: -50px;
        }
        
        .shape2 {
            width: 150px;
            height: 150px;
            bottom: -30px;
            left: -30px;
        }
        
        .assessment-help {
            font-size: 0.8rem;
            margin-top: 0.25rem;
            color: #666;
        }
        
        @media (max-width: 576px) {
            .logo-container {
                flex-direction: column;
                text-align: center;
            }
            
            .school-logo {
                margin-right: 0;
                margin-bottom: 15px;
            }
            
            .school-title {
                text-align: center;
            }
            
            .school-name {
                font-size: 1.2rem;
            }
            
            .login-title {
                font-size: 1.5rem;
            }
            
            .login-body {
                padding: 30px 20px;
            }
            
            .support-link {
                display: block;
                margin: 10px 0;
            }
        }
    </style>
</head>
<body>
    <!-- Decorative shapes -->
    <div class="floating-shape shape1"></div>
    <div class="floating-shape shape2"></div>

    <div class="login-container">
        <div class="login-header">
            <div class="logo-container">
                <img src="../coll_logo.png" alt="<?= $schoolName ?>" class="school-logo">
                <div class="school-title">
                    <h1 class="school-name"><?= $schoolName ?></h1>
                    <p class="school-motto">"<?= $schoolMotto ?>"</p>
                </div>
            </div>
            <h2 class="login-title">CBT Portal</h2>
            <p class="login-subtitle">Computer Based Test Login</p>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <div class="login-body">
            <form method="POST">
                <div class="mb-3">
                    <label for="registration_no" class="form-label">
                        <i class="fas fa-id-card"></i> Admission Number
                    </label>
                    <input type="text" name="registration_no" id="registration_no" class="form-control" 
                           placeholder="Enter your admission number" value="<?= isset($_POST['registration_no']) ? htmlspecialchars($_POST['registration_no']) : '' ?>" required>
                </div>

                <div class="mb-3">
                    <label for="class" class="form-label">
                        <i class="fas fa-users"></i> Class
                    </label>
                    <select name="class" id="class" class="form-select" 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)) {
                            $selected = (isset($_POST['class']) && $_POST['class'] == $class['class']) ? 'selected' : '';
                            echo "<option value='" . htmlspecialchars($class['class']) . "' $selected>" . htmlspecialchars($class['class']) . "</option>";
                        }
                        ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label for="term" class="form-label">
                        <i class="fas fa-calendar-alt"></i> Term
                    </label>
                    <select name="term" id="term" class="form-select" required>
                        <option value="">Select Term</option>
                        <option value="1st Term" <?= (isset($_POST['term']) && $_POST['term'] == '1st Term') ? 'selected' : '' ?>>1st Term</option>
                        <option value="2nd Term" <?= (isset($_POST['term']) && $_POST['term'] == '2nd Term') ? 'selected' : '' ?>>2nd Term</option>
                        <option value="3rd Term" <?= (isset($_POST['term']) && $_POST['term'] == '3rd Term') ? 'selected' : '' ?>>3rd Term</option>
                    </select>
                </div>

                <div class="mb-3">
                    <label for="session" class="form-label">
                        <i class="fas fa-calendar"></i> Academic Session
                    </label>
                    <select name="session" id="session" class="form-select" 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)) {
                            $selected = (isset($_POST['session']) && $_POST['session'] == $session['session']) ? 'selected' : '';
                            echo "<option value='" . htmlspecialchars($session['session']) . "' $selected>" . htmlspecialchars($session['session']) . "</option>";
                        }
                        ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label for="assessment_type" class="form-label">
                        <i class="fas fa-clipboard-list"></i> Assessment Type
                    </label>
                    <select name="assessment_type" id="assessment_type" class="form-select" required>
                        <option value="">Select Assessment Type</option>
                        <?php foreach ($assessmentTypes as $type): 
                            $selected = (isset($_POST['assessment_type']) && $_POST['assessment_type'] == $type) ? 'selected' : '';
                        ?>
                            <option value="<?= $type ?>" <?= $selected ?>>
                                <?= $type ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="assessment-help">
                        <i class="fas fa-info-circle" style="color: var(--secondary-gold);"></i>
                        Select the type of assessment you're taking (e.g., CA1, CA2, Term Exam)
                    </div>
                </div>

                <div class="mb-3">
                    <label for="pin" class="form-label">
                        <i class="fas fa-lock"></i> Examination PIN
                    </label>
                    <input type="password" name="pin" id="pin" class="form-control" 
                           placeholder="Enter your examination PIN" required>
                </div>

                <button type="submit" class="btn-login">
                    <i class="fas fa-sign-in-alt"></i> LOGIN TO CBT
                </button>
            </form>

            <!-- Assessment Type Info -->
            <div class="row mt-3 g-2">
                <div class="col-6 col-md-4">
                    <span class="badge-ca1 assessment-badge">CA1</span>
                </div>
                <div class="col-6 col-md-4">
                    <span class="badge-ca2 assessment-badge">CA2</span>
                </div>
                <div class="col-6 col-md-4">
                    <span class="badge-ca3 assessment-badge">CA3</span>
                </div>
                <div class="col-6 col-md-4">
                    <span class="badge-term assessment-badge">Term Exam</span>
                </div>
                <div class="col-6 col-md-4">
                    <span class="badge-mock assessment-badge">Mock Exam</span>
                </div>
            </div>

            <!-- Quick info note -->
            <div class="info-note">
                <i class="fas fa-info-circle"></i>
                Enter your admission number, select the assessment type (CA1, CA2, etc.), and enter your PIN to access your examination. A single PIN can be used for multiple assessment types within the same session.
            </div>

            <div class="support-info">
                <a href="tel:<?= $supportPhone ?>" class="support-link">
                    <i class="fas fa-phone-alt"></i> Call Support
                </a>
                <a href="mailto:<?= $supportEmail ?>" class="support-link">
                    <i class="fas fa-envelope"></i> Email Support
                </a>
            </div>

            <div class="copyright">
                © <?= date('Y'); ?> <a href="#"><?= $schoolName ?></a>. All rights reserved.<br>
                <small>Powered by <a href="https://dataswift.com.ng" target="_blank">DataSwift Coders</a></small>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Form validation
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('form').addEventListener('submit', function(e) {
                const registration = document.getElementById('registration_no').value;
                const className = document.getElementById('class').value;
                const term = document.getElementById('term').value;
                const session = document.getElementById('session').value;
                const assessmentType = document.getElementById('assessment_type').value;
                const pin = document.getElementById('pin').value;
                
                if (!registration || !className || !term || !session || !assessmentType || !pin) {
                    e.preventDefault();
                    alert('Please fill in all fields');
                }
            });
        });
    </script>
</body>
</html>