<?php

session_start();

require_once __DIR__ . '/library/config.php';
require_once __DIR__ . '/library/audit_log.php';

/*
|--------------------------------------------------------------------------
| ALREADY LOGGED IN
|--------------------------------------------------------------------------
*/

if (isset($_SESSION['user_id'])) {

    header("Location: dashboard.php");
    exit;
}

$error = '';
$school_id = null;

/*
|--------------------------------------------------------------------------
| LOGIN SUBMIT
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /*
    |--------------------------------------------------------------------------
    | GET FORM DATA
    |--------------------------------------------------------------------------
    */

    $username = trim($_POST['username'] ?? '');

    $password = $_POST['password'] ?? '';

    /*
    |--------------------------------------------------------------------------
    | VALIDATION
    |--------------------------------------------------------------------------
    */

    if (empty($username) || empty($password)) {

        $error = "Username and password required.";

    } else {

        /*
        |--------------------------------------------------------------------------
        | FETCH USER + SCHOOL
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare("
            SELECT
                u.*,
                s.id AS school_id,
                s.status AS school_status,
                s.subscription_end,
                s.subscription_status
            FROM users u
            INNER JOIN schools s
                ON s.id = u.school_id
            WHERE u.username = ?
            AND u.status = 'active'
            LIMIT 1
        ");

        $stmt->execute([$username]);

        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        /*
        |--------------------------------------------------------------------------
        | USER CHECK
        |--------------------------------------------------------------------------
        */

        if (!$user) {

            $error = "Invalid username or password.";

            // Audit Log - Failed Login
            logActivity($pdo, [
                'school_id' => null,
                'user_id'   => null,
                'module'    => 'Authentication',
                'action'    => 'LOGIN_FAILED',
                'record_id' => null,
                'message'   => "Failed login attempt for username: {$username}",
                'old_data'  => null,
                'new_data'  => [
                    'username'     => $username,
                    'reason'       => 'Invalid credentials',
                    'ip_address'   => $_SERVER['REMOTE_ADDR'] ?? null,
                    'user_agent'   => $_SERVER['HTTP_USER_AGENT'] ?? null
                ]
            ]);

        } else {

            $school_id = $user['school_id'];

            /*
            |--------------------------------------------------------------------------
            | SUBSCRIPTION EXPIRY CHECK
            |--------------------------------------------------------------------------
            */

            if (
                !empty($user['subscription_end']) &&
                strtotime($user['subscription_end']) < strtotime(date('Y-m-d'))
            ) {

                /*
                |--------------------------------------------------------------------------
                | AUTO EXPIRE SCHOOL
                |--------------------------------------------------------------------------
                */

                $expireStmt = $pdo->prepare("
                    UPDATE schools
                    SET
                        status = 'inactive',
                        subscription_status = 'Expired'
                    WHERE id = ?
                    LIMIT 1
                ");

                $expireStmt->execute([
                    $user['school_id']
                ]);

                $error = "School subscription expired.";

                // Audit Log - Subscription Expired
                logActivity($pdo, [
                    'school_id' => $school_id,
                    'user_id'   => null,
                    'module'    => 'Authentication',
                    'action'    => 'LOGIN_FAILED',
                    'record_id' => $user['id'],
                    'message'   => "Login failed - Subscription expired for user: {$username}",
                    'old_data'  => null,
                    'new_data'  => [
                        'username'       => $username,
                        'reason'         => 'Subscription expired',
                        'subscription_end' => $user['subscription_end'],
                        'ip_address'     => $_SERVER['REMOTE_ADDR'] ?? null
                    ]
                ]);

            }

            /*
            |--------------------------------------------------------------------------
            | SCHOOL STATUS CHECK
            |--------------------------------------------------------------------------
            */

            elseif ($user['school_status'] !== 'active') {

                $error = "School account inactive.";

                // Audit Log - School Inactive
                logActivity($pdo, [
                    'school_id' => $school_id,
                    'user_id'   => null,
                    'module'    => 'Authentication',
                    'action'    => 'LOGIN_FAILED',
                    'record_id' => $user['id'],
                    'message'   => "Login failed - School inactive for user: {$username}",
                    'old_data'  => null,
                    'new_data'  => [
                        'username'     => $username,
                        'reason'       => 'School inactive',
                        'ip_address'   => $_SERVER['REMOTE_ADDR'] ?? null
                    ]
                ]);

            }

            /*
            |--------------------------------------------------------------------------
            | ACCOUNT LOCK CHECK
            |--------------------------------------------------------------------------
            */

            elseif ((int)$user['account_locked'] === 1) {

                $error = "Account temporarily locked.";

                // Audit Log - Account Locked
                logActivity($pdo, [
                    'school_id' => $school_id,
                    'user_id'   => null,
                    'module'    => 'Authentication',
                    'action'    => 'LOGIN_FAILED',
                    'record_id' => $user['id'],
                    'message'   => "Login failed - Account locked for user: {$username}",
                    'old_data'  => null,
                    'new_data'  => [
                        'username'     => $username,
                        'reason'       => 'Account locked',
                        'ip_address'   => $_SERVER['REMOTE_ADDR'] ?? null
                    ]
                ]);

            }

            /*
            |--------------------------------------------------------------------------
            | PASSWORD VERIFY
            |--------------------------------------------------------------------------
            */

            elseif (!password_verify($password, $user['password'])) {

                $failed = $user['failed_attempts'] + 1;

                $lock = ($failed >= 5) ? 1 : 0;

                $updateStmt = $pdo->prepare("
                    UPDATE users
                    SET
                        failed_attempts = ?,
                        account_locked = ?
                    WHERE id = ?
                    LIMIT 1
                ");

                $updateStmt->execute([
                    $failed,
                    $lock,
                    $user['id']
                ]);

                $error = "Invalid username or password.";

                // Audit Log - Wrong Password
                logActivity($pdo, [
                    'school_id' => $school_id,
                    'user_id'   => null,
                    'module'    => 'Authentication',
                    'action'    => 'LOGIN_FAILED',
                    'record_id' => $user['id'],
                    'message'   => "Wrong password for user: {$username} (Attempt {$failed}/5)",
                    'old_data'  => null,
                    'new_data'  => [
                        'username'       => $username,
                        'reason'         => 'Invalid password',
                        'attempts'       => $failed,
                        'account_locked' => $lock,
                        'ip_address'     => $_SERVER['REMOTE_ADDR'] ?? null
                    ]
                ]);

            } else {

                /*
                |--------------------------------------------------------------------------
                | RESET FAILED ATTEMPTS
                |--------------------------------------------------------------------------
                */

                $resetStmt = $pdo->prepare("
                    UPDATE users
                    SET
                        failed_attempts = 0,
                        account_locked = 0,
                        last_login = NOW(),
                        last_login_ip = ?
                    WHERE id = ?
                    LIMIT 1
                ");

                $resetStmt->execute([
                    $_SERVER['REMOTE_ADDR'],
                    $user['id']
                ]);

                /*
                |--------------------------------------------------------------------------
                | SECURE SESSION
                |--------------------------------------------------------------------------
                */

                session_regenerate_id(true);
				/*
					|-------------------------------------------------------------------------- 
					| 🔥 NEW: SESSION TIMEOUT START 
					|-------------------------------------------------------------------------- 
					*/
					$_SESSION['last_activity'] = time(); // Timeout counter start

                /*
                |--------------------------------------------------------------------------
                | SESSION VARIABLES
                |--------------------------------------------------------------------------
                */

                $_SESSION['user_id'] = $user['id'];

                $_SESSION['school_id'] = $user['school_id'];

                $_SESSION['username'] = $user['username'];

                $_SESSION['name'] = $user['name'];

                $_SESSION['role'] = $user['role'];

                /*
                |--------------------------------------------------------------------------
                | AUDIT LOG - SUCCESSFUL LOGIN
                |--------------------------------------------------------------------------
                */

                logActivity($pdo, [
                    'school_id' => $school_id,
                    'user_id'   => $user['id'],
                    'module'    => 'Authentication',
                    'action'    => 'LOGIN',
                    'record_id' => $user['id'],
                    'message'   => "User logged in: {$username} ({$user['role']})",
                    'old_data'  => null,
                    'new_data'  => [
                        'username'     => $username,
                        'role'         => $user['role'],
                        'name'         => $user['name'],
                        'ip_address'   => $_SERVER['REMOTE_ADDR'] ?? null,
                        'user_agent'   => $_SERVER['HTTP_USER_AGENT'] ?? null,
                        'login_time'   => date('Y-m-d H:i:s')
                    ]
                ]);

                /*
                |--------------------------------------------------------------------------
                | REDIRECT
                |--------------------------------------------------------------------------
                */

                header("Location: dashboard.php");

                exit;
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>

        Login | School ERP

    </title>

    <!-- AdminLTE -->

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/admin-lte/3.2.0/css/adminlte.min.css"
    >

    <!-- Font Awesome -->

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"
    >

</head>

<body class="hold-transition login-page">

<div class="login-box">

    <div class="login-logo">

        <a href="#">

            <b>School</b> ERP

        </a>

    </div>

    <div class="card">

        <div class="card-body login-card-body">

            <p class="login-box-msg">

                Sign in to continue

            </p>

            <?php if ($error): ?>

                <div class="alert alert-danger">

                    <?= htmlspecialchars($error); ?>

                </div>

            <?php endif; ?>

            <form method="POST">

                <div class="input-group mb-3">

                    <input
                        type="text"
                        name="username"
                        class="form-control"
                        placeholder="Username"
                        required
                        autocomplete="off"
                        value="<?= htmlspecialchars($_POST['username'] ?? ''); ?>"
                    >

                    <div class="input-group-append">

                        <div class="input-group-text">

                            <span class="fas fa-user"></span>

                        </div>

                    </div>

                </div>

                <div class="input-group mb-3">

                    <input
                        type="password"
                        name="password"
                        class="form-control"
                        placeholder="Password"
                        required
                    >

                    <div class="input-group-append">

                        <div class="input-group-text">

                            <span class="fas fa-lock"></span>

                        </div>

                    </div>

                </div>

                <button
                    type="submit"
                    class="btn btn-primary btn-block"
                >

                    Login

                </button>

            </form>

        </div>

    </div>

</div>

<!-- Scripts -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.2/js/bootstrap.bundle.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/admin-lte/3.2.0/js/adminlte.min.js"></script>

</body>

</html>