<?php
/**
 * IBVTE Student Login Page
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Check database connection before proceeding
if (!checkDBConnection()) {
    exit;
}

require_once __DIR__ . '/../middleware.php';

// Redirect if already logged in as student
if (Auth()->isLoggedIn() && Auth()->hasRole('student')) {
    header('Location: dashboard.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rollNumber = preg_replace('/[^0-9]/', '', $_POST['roll_number'] ?? '');
    $rollNumber = str_pad($rollNumber, 10, '0', STR_PAD_LEFT); // Ensure 10-digit
    $dobRaw = trim($_POST['dob'] ?? '');
    $dob = parseDOB($dobRaw); // Convert DD/MM/YYYY → YYYY-MM-DD for DB
    $captcha = $_POST['captcha'] ?? '';
    
    // Verify math captcha
    $captchaVerify = Middleware()->verifyCaptcha($captcha, 'math');
    if (!$captchaVerify['success']) {
        $error = $captchaVerify['message'];
    } else {
        // Verify student credentials
        $db = DB();
        $student = $db->fetchOne(
            "SELECT s.*, u.id as user_id, u.is_active 
             FROM students s 
             LEFT JOIN users u ON s.user_id = u.id
             WHERE s.roll_number = ? AND s.date_of_birth = ? AND s.is_active = 1",
            [$rollNumber, $dob]
        );
        
        if ($student) {
            // Create student session
            $_SESSION['user_id'] = $student['user_id'] ?? 'student_' . $student['id'];
            $_SESSION['student_id'] = $student['id'];
            $_SESSION['student_name'] = $student['full_name'];
            $_SESSION['roll_number'] = $student['roll_number'];
            $_SESSION['role_slug'] = 'student';
            $_SESSION['last_activity'] = time();
            
            header('Location: dashboard.php');
            exit;
        } else {
            $error = 'Invalid Roll Number or Date of Birth';
            Middleware()->recordFailedAttempt('student_login');
        }
    }
}

// Generate math captcha for NEXT attempt
$mathCaptcha = Middleware()->generateMathCaptcha();
$flash = getFlashMessage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Login - <?= APP_SHORT_NAME ?></title>
    <meta name="description" content="Official student portal login page for the Indian Board of Vocational and Technical Education (IBVTE). Enter your roll number and date of birth to access your dashboard.">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #3b0b7c;
            --secondary-color: #6c4ab6;
        }
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', sans-serif;
        }
        .login-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.1);
            overflow: hidden;
            max-width: 500px;
            width: 100%;
            margin: 20px;
        }
        .login-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }
        .login-header img {
            max-width: 80px;
            margin-bottom: 15px;
            border-radius: 50%;
            border: 4px solid rgba(255,255,255,0.3);
        }
        .login-body {
            padding: 40px;
        }
        .form-floating {
            margin-bottom: 20px;
        }
        .form-floating input {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            height: 55px;
        }
        .form-floating input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(59,11,124,0.1);
        }
        .btn-login {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            border: none;
            border-radius: 10px;
            padding: 15px;
            font-weight: 600;
            width: 100%;
            color: white;
            transition: all 0.3s;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(59,11,124,0.3);
            color: white;
        }
        .captcha-box {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 12px;
            border-radius: 10px;
            text-align: center;
            font-family: 'Courier New', monospace;
            font-size: 1.5rem;
            letter-spacing: 8px;
            font-weight: bold;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
        }
        .links-section {
            text-align: center;
            margin-top: 20px;
        }
        .links-section a {
            color: var(--primary-color);
            text-decoration: none;
        }
        .links-section a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="login-header">
            <img src="../assets/images/logo.jpeg" alt="IBVTE Logo">
            <h4 class="mb-1">Student Portal</h4>
            <p class="mb-0 opacity-75 small">Indian Board of Vocational & Technical Education</p>
        </div>
        
        <div class="login-body">
            <?php if ($flash): ?>
                <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show">
                    <?= $flash['message'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle me-2"></i><?= $error ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="" id="loginForm">
                <div class="form-floating">
                    <input type="text" class="form-control" id="roll_number" name="roll_number" 
                           placeholder="Roll Number (10 digits)" required maxlength="10"
                           pattern="[0-9]{10}" inputmode="numeric"
                           title="10-digit numeric roll number">
                    <label for="roll_number"><i class="fas fa-id-card me-2"></i>Roll Number (10 Digits)</label>
                </div>
                
                <div class="mb-3">
                    <label class="small fw-bold text-muted mb-1 d-block">Date of Birth (DD/MM/YYYY)</label>
                    <input type="text" class="form-control" id="dob" name="dob" 
                           placeholder="DD/MM/YYYY" required maxlength="10"
                           pattern="[0-9]{2}/[0-9]{2}/[0-9]{4}"
                           title="Enter date in DD/MM/YYYY format"
                           style="height:55px;border:2px solid #e0e0e0;border-radius:10px;font-size:1rem;">
                </div>
                
                <div class="mb-3">
                    <label class="small fw-bold text-muted mb-2">Security Verification</label>
                    <div class="input-group">
                        <span class="input-group-text bg-primary text-white fw-bold" style="border-radius: 10px 0 0 10px; border: none; font-size: 1.2rem;">
                            <?= $mathCaptcha['question'] ?>
                        </span>
                        <input type="number" class="form-control" id="captcha" name="captcha" 
                               placeholder="Answer" required maxlength="5"
                               style="height: 55px; border: 2px solid #e0e0e0; border-radius: 0 10px 10px 0;">
                    </div>
                </div>
                
                <button type="submit" class="btn btn-login" id="submitBtn">
                    <i class="fas fa-sign-in-alt me-2"></i>Login
                </button>
            </form>

        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('loginForm').addEventListener('submit', function() {
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerHTML = 
                '<i class="fas fa-spinner fa-spin me-2"></i>Verifying...';
        });
    </script>
</body>
</html>
