<?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));
}

// ----------------------
// SESSION-BASED THROTTLE FOR UNKNOWN USERS
// ----------------------
if (!isset($_SESSION['failed_login_attempts'])) {
    $_SESSION['failed_login_attempts'] = 0;
}

$error = '';
if (isset($_GET['locked']) && $_GET['locked'] === '1') {
    $error = 'This account has been locked. Please contact an admin.';
} elseif ($_SESSION['failed_login_attempts'] >= 5) {
    $error = 'Too many login attempts. Please try again later.';
}

// ----------------------
// ADMIN LOCK NOTIFICATION
// ----------------------
function notifyAdminsOfLockedAccount(PDO $pdo, array $lockedUser): void
{
    try {
        // ----------------------
        // FIND SYSTEM SENDER
        // ----------------------
        $systemSenderStmt = $pdo->prepare("
            SELECT id
            FROM admin_users
            WHERE username = 'system'
              AND role = 'System'
            LIMIT 1
        ");
        
        $systemSenderStmt->execute();
        
        $systemSenderId = $systemSenderStmt->fetchColumn();
        
        if (!$systemSenderId) {
            return;
        }

        // ----------------------
        // FIND ADMIN RECIPIENTS
        // ----------------------
        $adminStmt = $pdo->prepare("
            SELECT id
            FROM admin_users
            WHERE role = 'Admin'
        ");

        $adminStmt->execute();

        $adminUsers = $adminStmt->fetchAll(PDO::FETCH_COLUMN);

        if (empty($adminUsers)) {
            return;
        }

        $messageSubject = 'Newsdesk account locked';

        $messageBody = '
            <p>
                The Newsdesk account for
                <strong>'
                . htmlspecialchars($lockedUser['username'], ENT_QUOTES, 'UTF-8')
                . '</strong>
                has been locked after 3 failed login attempts.
            </p>

            <p>
                Please review the account and unlock if appropriate.
            </p>
        ';

        $messageStmt = $pdo->prepare("
            INSERT INTO messages
            (
                sender_id,
                recipient_id,
                subject,
                body,
                parent_message_id,
                sent_at,
                is_read
            )
            VALUES (?, ?, ?, ?, NULL, NOW(), 0)
        ");

        foreach ($adminUsers as $adminUserId) {
            $messageStmt->execute([
                $systemSenderId,
                $adminUserId,
                $messageSubject,
                $messageBody
            ]);
        }

    } catch (Exception $e) {
        // Do not block the lock if message creation fails.
        return;
    }
}

function createRememberMeToken(PDO $pdo, int $userId): void
{
    $selector = bin2hex(random_bytes(12));
    $validator = bin2hex(random_bytes(32));

    $validatorHash = password_hash($validator, PASSWORD_DEFAULT);
    $expiresAt = date('Y-m-d H:i:s', strtotime('+30 days'));

    $stmt = $pdo->prepare("
        INSERT INTO admin_remember_tokens
            (user_id, selector, validator_hash, expires_at)
        VALUES
            (?, ?, ?, ?)
    ");

    $stmt->execute([
        $userId,
        $selector,
        $validatorHash,
        $expiresAt
    ]);

    setcookie('ts_admin_remember', $selector . ':' . $validator, [
        'expires' => time() + (86400 * 30),
        'path' => '/admin',
        'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
}

// ----------------------
// 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,
                    failed_login_attempts,
                    is_locked
                FROM admin_users
                WHERE username = ?
                AND role != 'System'
                LIMIT 1
            ");

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

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

            if (!$user) {

                // Unknown username - keep message generic.
                $_SESSION['failed_login_attempts']++;

                sleep(1);

                $error = 'Invalid username or password.';

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

                // Account is already locked.
                $error = 'This account has been locked. Please contact an admin.';

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

                // Known username, wrong password.
                $newAttempts = ((int)$user['failed_login_attempts']) + 1;

                if ($newAttempts >= 3) {

                    $lockStmt = $pdo->prepare("
                        UPDATE admin_users
                        SET failed_login_attempts = ?,
                            is_locked = 1,
                            locked_at = NOW()
                        WHERE id = ?
                    ");

                    $lockStmt->execute([
                        $newAttempts,
                        $user['id']
                    ]);

                    notifyAdminsOfLockedAccount($pdo, $user);

                    sleep(1);

                    $error = 'This account has been locked. Please contact an admin.';

                } else {

                    $attemptStmt = $pdo->prepare("
                        UPDATE admin_users
                        SET failed_login_attempts = ?
                        WHERE id = ?
                    ");

                    $attemptStmt->execute([
                        $newAttempts,
                        $user['id']
                    ]);

                    sleep(1);

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

            } else {

                // ----------------------
                // 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;

                // RESET ACCOUNT FAILED ATTEMPTS AND UPDATE LAST LOGIN
                $updateStmt = $pdo->prepare("
                    UPDATE admin_users
                    SET failed_login_attempts = 0,
                        locked_at = NULL,
                        last_logged_in = NOW()
                    WHERE id = ?
                ");

                $updateStmt->execute([
                    $user['id']
                ]);
                
                                if (isset($_POST['remember_me']) && $_POST['remember_me'] === '1') {
    createRememberMeToken($pdo, (int)$user['id']);
}

                header('Location: dashboard');

                exit;
            }

        } catch (Exception $e) {

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

$pageTitle = 'Thrillsense Newsdesk';

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

?>

<!-- Bootstrap fallback: remove this if Bootstrap is already included in includes/header.php -->
<link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
    rel="stylesheet"
>

<style>
:root {
    --ts-blue: #262541;
    --ts-blue-dark: #1b1a31;
    --ts-blue-soft: #f1f1f6;
    --ts-red: #dc3545;
}

    body {
        background: var(--ts-blue-soft);
    }

    .login-shell {
        min-height: 100vh;
        min-height: 100dvh;
    }

    .login-panel {
        max-width: 420px;
        width: 100%;
        background: #fff;
        padding: 2.25rem;
        border-radius: 18px;
        border-top: 5px solid var(--ts-blue);
        box-shadow: 0 14px 40px rgba(0, 40, 120, 0.12);
    }

    .login-logo {
        max-width: 130px;
        margin-bottom: 1.5rem;
    }

    .login-title {
        font-weight: 700;
        margin-bottom: 0.35rem;
        color: #111827;
    }

    .login-subtitle {
        color: #6c757d;
        margin-bottom: 1.25rem;
    }

    .newsdesk-status {
        display: inline-flex;
        align-items: center;
        gap: 0.45rem;
        margin-bottom: 1.75rem;
        padding: 0.35rem 0.75rem;
        border-radius: 999px;
        background: var(--ts-blue-soft);
        color: var(--ts-blue-dark);
        font-size: 0.85rem;
        font-weight: 600;
    }

    .pulse-dot {
        width: 9px;
        height: 9px;
        border-radius: 50%;
        background: var(--ts-red);
        box-shadow: 0 0 0 rgba(220, 53, 69, 0.6);
        animation: pulseDot 1.6s infinite;
    }

    @keyframes pulseDot {
        0% {
            box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.6);
        }

        70% {
            box-shadow: 0 0 0 8px rgba(220, 53, 69, 0);
        }

        100% {
            box-shadow: 0 0 0 0 rgba(220, 53, 69, 0);
        }
    }

    .form-label {
        font-weight: 600;
        color: #1f2937;
    }

    .form-control {
        padding: 0.75rem 0.9rem;
        border-radius: 10px;
    }

    .form-control:focus {
        border-color: var(--ts-blue);
        box-shadow: 0 0 0 0.2rem rgba(0, 87, 255, 0.15);
    }

    .btn-login {
        padding: 0.75rem;
        font-weight: 700;
        border-radius: 10px;
        background: var(--ts-blue);
        border-color: var(--ts-blue);
    }

    .btn-login:hover,
    .btn-login:focus {
        background: var(--ts-blue-dark);
        border-color: var(--ts-blue-dark);
    }

    .login-image-side {
        position: relative;
        background:
            linear-gradient(
                rgba(0, 40, 120, 0.45),
                rgba(0, 15, 45, 0.65)
            ),
            url('/img/the-smiler.jpg');
        background-size: cover;
        background-position: center;
        background-color: var(--ts-blue-dark);
    }

    .login-image-side::after {
        content: "Thrillsense Newsdesk";
        position: absolute;
        left: 3rem;
        bottom: 3rem;
        color: #fff;
        font-size: 1.75rem;
        font-weight: 700;
        letter-spacing: -0.03em;
    }

    @media (max-width: 767.98px) {
        .login-panel {
            padding: 1.75rem;
            box-shadow: 0 10px 28px rgba(0, 40, 120, 0.1);
        }

        .login-logo {
            max-width: 115px;
        }
    }
</style>

<div class="container-fluid">

    <div class="row login-shell">

        <!-- LOGIN FORM -->
        <div class="col-12 col-md-6 d-flex justify-content-center align-items-center bg-light px-4 py-5">

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

                <div class="text-center">
                    <img
                        src="/img/thrillsense-blk.png"
                        class="login-logo"
                        alt="Thrillsense"
                    >

                    <h2 class="login-title">
                        Newsdesk Login
                    </h2>

                    <p class="login-subtitle">
                        Sign in to continue to your dashboard
                    </p>

                    <div class="newsdesk-status">
                        <span class="pulse-dot"></span>
                        Live newsroom
                    </div>
                </div>

                <?php if ($error): ?>

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

                <?php endif; ?>

                <!-- CSRF -->
                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= htmlspecialchars($_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>
                
                <div class="form-check mb-4">
    <input
        class="form-check-input"
        type="checkbox"
        name="remember_me"
        id="remember_me"
        value="1"
    >

    <label class="form-check-label" for="remember_me">
        Remember me
    </label>
</div>

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

            </form>

        </div>

        <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'; ?>