<?php
require_once 'includes/db_connect.php';

// Enable error logging
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'logs/php_errors.log');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $password = $_POST['password']; // Password is not sanitized to preserve integrity
    $role = filter_input(INPUT_POST, 'role', FILTER_SANITIZE_STRING);

    if (empty($username) || empty($password) || empty($role)) {
        $error = "All fields are required.";
        error_log("Login attempt failed: Empty fields detected.");
    } else {
        try {
            if ($role == 'admin') {
                $stmt = $pdo->prepare("SELECT * FROM admins WHERE username = ?");
                $stmt->execute([$username]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($user) {
                    if (password_verify($password, $user['password'])) {
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['role'] = 'admin';
                        header("Location: admin/admin_dashboard.php");
                        exit;
                    } else {
                        $error = "Incorrect password for admin.";
                        error_log("Login failed: Incorrect password for admin username '$username'.");
                    }
                } else {
                    $error = "Admin username not found.";
                    error_log("Login failed: Admin username '$username' not found.");
                }
            } else {
                $stmt = $pdo->prepare("SELECT * FROM applicants WHERE email = ? OR applicant_id = ?");
                $stmt->execute([$username, $username]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($user) {
                    if (password_verify($password, $user['password'])) {
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['role'] = 'student';
                        header("Location: student/student_dashboard.php");
                        exit;
                    } else {
                        $error = "Incorrect password for student.";
                        error_log("Login failed: Incorrect password for student username/email '$username'.");
                    }
                } else {
                    $error = "Student username/email not found.";
                    error_log("Login failed: Student username/email '$username' not found.");
                }
            }
        } catch (PDOException $e) {
            $error = "Database error. Please try again.";
            error_log("Login failed: PDOException - " . $e->getMessage());
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - British Entrance Academy</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="bg-light">
    <div class="container">
        <div class="row justify-content-center mt-5">
            <div class="col-md-4">
                <div class="card shadow">
                    <div class="card-body">
                        <h3 class="card-title text-center mb-4">Login</h3>
                        <?php if (isset($error)): ?>
                            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                        <?php endif; ?>
                        <form method="POST"> 
                            <div class="mb-3">
                                <label for="username" class="form-label">Username/Email</label>
                                <input type="text" class="form-control" id="username" name="username" required>
                            </div>
                            <div class="mb-3">
                                <label for="password" class="form-label">Password</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            <div class="mb-3">
                                <label for="role" class="form-label">Role</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="student">Student</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary w-100" style="background-color: #66CDAA;">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>
</body>
</html>