<?php

// ----------------------
// PRODUCTION ERROR SETTINGS
// ----------------------
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// ----------------------
// SECURE SESSION SETTINGS
// ----------------------
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Lax');

if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
    ini_set('session.cookie_secure', 1);
}

session_start();

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

// ----------------------
// REDIRECT IF LOGGED IN
// ----------------------
if (
    isset($_SESSION['admin_logged_in']) &&
    $_SESSION['admin_logged_in'] === true
) {
    header('Location: dashboard');
    exit;
}

// ----------------------
// CSRF TOKEN
// ----------------------
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// ----------------------
// FAILED LOGIN ATTEMPTS
// ----------------------
if (!isset($_SESSION['failed_login_attempts'])) {
    $_SESSION['failed_login_attempts'] = 0;
}

$error = '';

if ($_SESSION['failed_login_attempts'] >= 5) {
    $error = 'Too many login attempts. Please try again later.';
}

// ----------------------
// LOGIN ATTEMPT
// ----------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {

    // CSRF CHECK
    if (
        !isset($_POST['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
    ) {
        die('Invalid CSRF token');
    }

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

    if ($username === '' || $password === '') {

        $error = 'Invalid username or password.';

    } else {

        try {

            $stmt = $pdo->prepare("
                SELECT 
                    id,
                    username,
                    password_hash,
                    role
                FROM admin_users
                WHERE username = ?
            ");

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

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

            if (
                $user &&
                password_verify($password, $user['password_hash'])
            ) {

                // ----------------------
                // SECURE LOGIN
                // ----------------------
                session_regenerate_id(true);

                $_SESSION['admin_logged_in'] = true;
                $_SESSION['admin_user_id'] = $user['id'];
                $_SESSION['admin_username'] = $user['username'];
                $_SESSION['admin_role'] = $user['role'];

                // RESET FAILED ATTEMPTS
                $_SESSION['failed_login_attempts'] = 0;

                // UPDATE LAST LOGIN
                $updateStmt = $pdo->prepare("
                    UPDATE admin_users
                    SET last_logged_in = NOW()
                    WHERE id = ?
                ");

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

                header('Location: dashboard');

                exit;

            } else {

                // FAILED LOGIN
                $_SESSION['failed_login_attempts']++;

                // SLOW BRUTE FORCE ATTACKS
                sleep(1);

                $error = 'Invalid username or password.';
            }

        } catch (Exception $e) {

            // GENERIC ERROR
            $error = 'An unexpected error occurred.';
        }
    }
}

$pageTitle = 'Admin Login';

require_once __DIR__ . '/includes/header.php';

?>

<div class="container-fluid">

    <div class="row vh-100">

        <!-- LOGIN FORM -->
        <div class="col-md-6 d-flex flex-column justify-content-center align-items-center bg-light">

            <form method="post" class="w-75">

                <h2 class="mb-4">
                    ThrillSense CMS Login
                </h2>

                <?php if ($error): ?>

                    <div class="alert alert-danger">
                        <?= htmlspecialchars($error) ?>
                    </div>

                <?php endif; ?>

                <!-- CSRF -->
                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= $_SESSION['csrf_token'] ?>"
                >

                <!-- USERNAME -->
                <div class="mb-3">

                    <label for="username" class="form-label">
                        Username
                    </label>

                    <input
                        id="username"
                        name="username"
                        type="text"
                        class="form-control"
                        autocomplete="username"
                        required
                        autofocus
                    >

                </div>

                <!-- PASSWORD -->
                <div class="mb-3">

                    <label for="password" class="form-label">
                        Password
                    </label>

                    <input
                        id="password"
                        name="password"
                        type="password"
                        class="form-control"
                        autocomplete="current-password"
                        required
                    >

                </div>

                <!-- SUBMIT -->
                <button
                    type="submit"
                    class="btn btn-primary w-100"
                >
                    Login
                </button>

            </form>

        </div>

        <!-- IMAGE SIDE -->
        <div class="col-md-6 d-none d-md-block p-0 login-image-side"></div>

    </div>

</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>