<?php
session_start();

// Redirect if already logged in
if (isset($_SESSION['student_id']) && in_array($_SESSION['role'], ['student', 'admin'])) {
    header("Location: financials.php");
    exit();
}

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_db";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    $error = "Connection failed. Please try again later.";
}

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $admission_no = filter_input(INPUT_POST, 'admission_no', FILTER_SANITIZE_STRING);
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

    if (empty($admission_no) || empty($password)) {
        $error = "Admission Number and password are required.";
    } else {
        try {
            $stmt = $conn->prepare("SELECT id, admission_no, password, role FROM students WHERE admission_no = :admission_no");
            $stmt->execute([':admission_no' => $admission_no]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && $password === $user['password']) {
                $_SESSION['student_id'] = $user['id'];
                $_SESSION['role'] = $user['role'];
                header("Location: " . ($user['role'] === 'admin' ? 'admin_page.php' : 'financials.php'));
                exit();
            } else {
                $error = "Invalid Admission Number or password.";
            }
        } catch(PDOException $e) {
            error_log("Login error: " . $e->getMessage());
            $error = "An error occurred. Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Student login for Cypher University portal.">
    <meta name="keywords" content="Cypher University, student login, portal">
    <meta name="author" content="Cypher University">
    <title>Student Login - Cypher University</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    <div class="container my-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h2 class="section-title text-center">Student Login</h2>
                        <?php if (isset($error)): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <?php echo htmlspecialchars($error); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        <?php endif; ?>
                        <form method="POST" class="contact-form" id="login-form">
                            <div class="mb-3">
                                <label for="admission_no" class="form-label">Admission Number</label>
                                <input type="text" id="admission_no" name="admission_no" class="form-control" required aria-describedby="admissionNoError">
                                <div id="admissionNoError" class="invalid-feedback">Please enter your admission number.</div>
                            </div>
                            <div class="mb-3">
                                <label for="password" class="form-label">Password</label>
                                <input type="password" id="password" name="password" class="form-control" required aria-describedby="passwordError">
                                <div id="passwordError" class="invalid-feedback">Please enter your password.</div>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">Login</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('login-form').addEventListener('submit', function(event) {
            let isValid = true;
            const inputs = this.querySelectorAll('input[required]');
            inputs.forEach(input => {
                if (!input.value.trim()) {
                    input.classList.add('is-invalid');
                    isValid = false;
                } else {
                    input.classList.remove('is-invalid');
                }
            });
            if (!isValid) {
                event.preventDefault();
            }
        });
    </script>
</body>
</html>