<?php
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 = ?");
    $stmt->bind_param("s", $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'])) {
            if ($staff['status'] === 'Active') {
                // ✅ Unset student session if it exists
                unset($_SESSION['student']);
                unset($_SESSION['role']);

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

            // Handle suspended or leave statuses
            $_SESSION['login_msg'] = match ($staff['status']) {
                'Suspend' => "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 = ?");
    $stmt->bind_param("s", $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') {
            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'])) {
            unset($_SESSION['staff']);
            unset($_SESSION['role']);
    
            $_SESSION['student'] = $student['id'];
            $_SESSION['role'] = $student['role'];
    
            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();

    }
?>

