<?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 = 'ThrillSense Newsdesk Login';
$extraCss = '/admin/assets/css/login.css';

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

?>

<div class="login-page">

    <!-- LOGIN SIDE -->
    <div class="login-panel">

        <div class="login-content">

            <img
                src="https://thrillsense.com/admin/img/thrillsense-sm.png"
                alt="ThrillSense"
                class="login-logo"
            >

            <div class="login-heading">

                <span class="login-kicker">
                    Newsdesk
                </span>

                <h1>
                    CMS Login
                </h1>

                <p>
                    Sign in to manage ThrillSense articles, guides and editorial updates.
                </p>

            </div>

            <?php if ($error): ?>

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

            <?php endif; ?>

            <form method="post" class="login-form">

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

                <!-- USERNAME -->
                <div class="field-group">

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

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

                </div>

                <!-- PASSWORD -->
                <div class="field-group">

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

                    <input
                        id="password"
                        name="password"
                        type="password"
                        class="field-control"
                        placeholder="Enter password"
                        autocomplete="current-password"
                        required
                    >

                </div>

                <!-- SUBMIT -->
                <button
                    type="submit"
                    class="login-btn"
                >
                    Login
                </button>

            </form>

            <div class="security-note">
                Protected admin environment
            </div>

        </div>

    </div>

    <!-- IMAGE SIDE -->
    <div class="login-image-side"></div>

</div>

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