<?php
session_start();

// Redirect if already logged in
if (isset($_SESSION['student_id']) && $_SESSION['role'] === 'admin') {
    header("Location: admin_page.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 (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = filter_input(INPUT_POST, 'student_id', FILTER_SANITIZE_STRING);
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

    if (empty($student_id) || empty($password)) {
        $error = "Admin ID and password are required.";
    } else {
        try {
            $stmt = $conn->prepare("SELECT student_id, password FROM users WHERE student_id = :student_id AND role = 'admin'");
            $stmt->execute([':student_id' => $student_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && $user['password'] === $password) {
                $_SESSION['student_id'] = $user['student_id'];
                $_SESSION['role'] = 'admin';
                header("Location: admin_page.php");
                exit();
            } else {
                $error = "Invalid admin ID 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="Admin login for Gakero E.L.C.K High School dashboard.">
    <meta name="keywords" content="Gakero E.L.C.K High School, admin login, dashboard">
    <meta name="author" content="Gakero E.L.C.K High School">
    <title>Admin Login - Gakero E.L.C.K High School</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>

    <!-- Login Section -->
    <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">Admin 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="student_id" class="form-label">Admin ID</label>
                                <input type="text" id="student_id" name="student_id" class="form-control" required aria-describedby="adminIdError">
                                <div id="adminIdError" class="invalid-feedback">Please enter your admin ID.</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>