<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once("public/functions.php");
require_once("public/school_config.php");

// Log login attempts
function log_login_attempt($connection, $login_id, $success) {
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $stmt = $connection->prepare("INSERT INTO login_attempts (login_id, ip_address, user_agent, success) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("sssi", $login_id, $ip, $user_agent, $success);
    $stmt->execute();
    $stmt->close();
}

// Rate limiting
function is_rate_limited($connection, $login_id, $limit = 5, $minutes = 15) {
    $stmt = $connection->prepare("
        SELECT COUNT(*) FROM login_attempts
        WHERE login_id = ? AND success = 0 AND attempt_time > (NOW() - INTERVAL ? MINUTE)
    ");
    $stmt->bind_param("si", $login_id, $minutes);
    $stmt->execute();
    $stmt->bind_result($attempts);
    $stmt->fetch();
    $stmt->close();

    return $attempts >= $limit;
}

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_btn'])) {
    $login_id = inject_checker($connection, $_POST['login_id']);
    $login_password = inject_checker($connection, $_POST['login_password']);

    if (empty($login_id) || empty($login_password)) {
        $_SESSION['login_msg'] = "Username/Reg. No and Password are required.";
        $_SESSION['alert_type'] = "error";
        header("Location: login.php");
        exit();
    }

    // Rate limiting check
    if (is_rate_limited($connection, $login_id)) {
        $_SESSION['login_msg'] = "Too many failed attempts. Try again later.";
        $_SESSION['alert_type'] = "error";
        header("Location: login.php");
        exit();
    }

    // === 1. STAFF LOGIN ===
    $stmt = $connection->prepare("SELECT * FROM staff WHERE username = ? OR email = ? OR phone = ? OR name = ? LIMIT 1");
    $stmt->bind_param("ssss", $login_id, $login_id, $login_id, $login_id);
    $stmt->execute();
    $staff_result = $stmt->get_result();

    if ($staff_result && $staff_result->num_rows === 1) {
        $staff = $staff_result->fetch_assoc();
        if (password_verify($login_password, $staff['password']) || $login_password === $staff['password'] || md5($login_password) === $staff['password']) {
            if ($staff['status'] === 'Active' || $staff['status'] === 'active') {
                // ✅ Unset student sessions if exist
                if (!headers_sent()) {
                    session_regenerate_id(true);
                }
                unset($_SESSION['student'], $_SESSION['student_id'], $_SESSION['student_name'], $_SESSION['class']);

                $_SESSION['staff']      = $staff['id'];
                $_SESSION['staff_id']   = $staff['id'];
                $_SESSION['role']       = $staff['role'];
                $_SESSION['staff_name'] = $staff['name'] ?? $staff['username'];
                $_SESSION['username']   = $staff['username'];
                log_login_attempt($connection, $login_id, true);
                header("Location: portal");
                exit();
            }

            // Handle suspended or leave statuses
            $_SESSION['login_msg'] = match ($staff['status']) {
                'Suspend', 'suspended' => "Your account is suspended.",
                'On Leave' => "You're currently on leave.",
                default => "Account status is not recognized."
            };
            $_SESSION['alert_type'] = "error";
            log_login_attempt($connection, $login_id, false);
            header("Location: login.php");
            exit();
        }
    }

   // === 2. STUDENT LOGIN ===
    $stmt = $connection->prepare("SELECT * FROM students WHERE reg_number = ? OR LOWER(reg_number) = LOWER(?) OR id = ? LIMIT 1");
    $stmt->bind_param("sss", $login_id, $login_id, $login_id);
    $stmt->execute();
    $student_result = $stmt->get_result();
    
    if ($student_result && $student_result->num_rows === 1) {
        $student = $student_result->fetch_assoc();
    
        // 🔒 Check account status
        if ($student['status'] !== 'active' && $student['status'] !== 'Active') {
            if ($student['status'] === 'archived') {
                $_SESSION['login_msg'] = "You have graduated. Login not allowed.";
            } elseif ($student['status'] === 'suspended') {
                $_SESSION['login_msg'] = "Your account has been suspended. Please contact the school.";
            } elseif ($student['status'] === 'blocked') {
                $_SESSION['login_msg'] = "Your account has been blocked. Please contact the administrator.";
            } else {
                $_SESSION['login_msg'] = "Your account is inactive. Please contact the school.";
            }
    
            $_SESSION['alert_type'] = "error";
            log_login_attempt($connection, $login_id, false);
            header("Location: login.php");
            exit();
        }
    
        // ✅ If active, check password
        if (password_verify($login_password, $student['gen_password']) || $login_password === $student['gen_password'] || md5($login_password) === $student['gen_password']) {
            if (!headers_sent()) {
                session_regenerate_id(true);
            }
            unset($_SESSION['staff'], $_SESSION['staff_id'], $_SESSION['staff_name']);
    
            $_SESSION['student']      = $student['id'];
            $_SESSION['student_id']   = $student['id'];
            $_SESSION['role']         = $student['role'];
            $_SESSION['reg_number']   = $student['reg_number'];
            $_SESSION['class']        = $student['class'] ?? '';
            $full_name = trim(($student['firstname'] ?? '') . ' ' . ($student['othername'] ?? '') . ' ' . ($student['lastname'] ?? ''));
            $_SESSION['student_name'] = !empty($full_name) ? $full_name : 'Student';
    
            log_login_attempt($connection, $login_id, true);
            header("Location: portal"); // Make sure this path exists
            exit();
        }
    }
    
    // === INVALID LOGIN ===
    $_SESSION['login_msg'] = "Invalid login credentials.";
    $_SESSION['alert_type'] = "error";
    log_login_attempt($connection, $login_id, false);
    header("Location: login.php");
    exit();

}
