<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/activity.php';

if (is_admin_logged_in()) {
    redirect(ADMIN_URL . '/dashboard.php');
}

$error = '';



$loginLimiterEnabled = get_setting('login_limiter_enabled', '1') === '1';
$maxLoginAttempts = (int) get_setting('max_login_attempts', '5');
$lockoutMinutes = (int) get_setting('lockout_minutes', '15');

if ($maxLoginAttempts <= 0) {
    $maxLoginAttempts = 5;
}

if ($lockoutMinutes <= 0) {
    $lockoutMinutes = 15;
}

if (!isset($_SESSION['admin_login_attempts'])) {
    $_SESSION['admin_login_attempts'] = 0;
}

if (!isset($_SESSION['admin_login_locked_until'])) {
    $_SESSION['admin_login_locked_until'] = 0;
}

$lockedUntil = (int) $_SESSION['admin_login_locked_until'];
$isLocked = $loginLimiterEnabled && $lockedUntil > time();

if (is_post()) {
    if ($isLocked) {
        $remainingSeconds = $lockedUntil - time();
        $remainingMinutes = max(1, ceil($remainingSeconds / 60));
        $error = 'Too many failed login attempts. Please try again in ' . $remainingMinutes . ' minute(s).';
    } elseif (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $email = strtolower(trim($_POST['email'] ?? ''));
        $password = $_POST['password'] ?? '';

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } elseif ($password === '') {
            $error = 'Please enter your password.';
        } else {
            $stmt = $pdo->prepare("
                SELECT *
                FROM admin_users
                WHERE email = ?
                  AND status = 'active'
                LIMIT 1
            ");
            $stmt->execute([$email]);
            $adminUser = $stmt->fetch();

            if ($adminUser && password_verify($password, $adminUser['password_hash'])) {
                $_SESSION['admin_login_attempts'] = 0;
                $_SESSION['admin_login_locked_until'] = 0;

                login_admin($adminUser);

                $stmt = $pdo->prepare("
                    UPDATE admin_users
                    SET last_login_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$adminUser['id']]);
                log_admin_activity(
    'admin_login',
    'Admin logged in: ' . $adminUser['email']
);

                redirect(ADMIN_URL . '/dashboard.php');
            } else {
                if ($loginLimiterEnabled) {
                    $_SESSION['admin_login_attempts']++;

                    if ($_SESSION['admin_login_attempts'] >= $maxLoginAttempts) {
                        $_SESSION['admin_login_locked_until'] = time() + ($lockoutMinutes * 60);
                        $error = 'Too many failed login attempts. Please try again in ' . $lockoutMinutes . ' minute(s).';
                    } else {
                        $remainingAttempts = $maxLoginAttempts - $_SESSION['admin_login_attempts'];
                        $error = 'Invalid email or password. Attempts remaining: ' . $remainingAttempts . '.';
                    }
                } else {
                    $error = 'Invalid email or password.';
                }
            }
        }
    }
}

if ($isLocked && $error === '') {
    $remainingSeconds = $lockedUntil - time();
    $remainingMinutes = max(1, ceil($remainingSeconds / 60));
    $error = 'Too many failed login attempts. Please try again in ' . $remainingMinutes . ' minute(s).';
}

if (isset($_GET['timeout'])) {
    $error = 'Your admin session expired due to inactivity. Please login again.';
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Login | <?= e(APP_NAME); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            min-height: 100vh;
            display: grid;
            place-items: center;
            background: #f7f4ef;
            color: #1f1f1f;
            font-family: Arial, sans-serif;
        }

        .login-card {
            width: min(440px, calc(100% - 32px));
            background: #ffffff;
            border: 1px solid #eee8df;
            border-radius: 24px;
            padding: 34px;
            box-shadow: 0 18px 50px rgba(0,0,0,0.08);
        }

        .login-card h1 {
            margin: 0 0 8px;
            font-size: 30px;
        }

        .login-card p {
            margin: 0 0 24px;
            color: #666;
            line-height: 1.6;
        }

        .field {
            margin-bottom: 16px;
        }

        .field label {
            display: block;
            margin-bottom: 8px;
            font-weight: 700;
        }

        .field input {
            width: 100%;
            border: 1px solid #dfd4c7;
            border-radius: 14px;
            padding: 13px 14px;
            font-size: 15px;
        }

        .btn {
            width: 100%;
            border: none;
            background: #1d1a17;
            color: #fff;
            padding: 14px 18px;
            border-radius: 999px;
            font-weight: 800;
            cursor: pointer;
            font-size: 15px;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .alert {
            padding: 12px 14px;
            border-radius: 14px;
            margin-bottom: 18px;
            font-weight: 700;
            background: #fff0f0;
            color: #a33131;
            border: 1px solid #ffd0d0;
        }

        .hint {
            margin-top: 18px;
            font-size: 13px;
            color: #777;
            text-align: center;
        }
    </style>
</head>
<body>
    <main class="login-card">
        <h1><?= e(APP_NAME); ?></h1>
        <p>Login to manage products, orders, customers, and website settings.</p>

        <?php if ($error): ?>
            <div class="alert"><?= e($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <?= csrf_field(); ?>

            <div class="field">
                <label>Email</label>
                <input
                    type="email"
                    name="email"
                    value="<?= e($_POST['email'] ?? ''); ?>"
                    required
                    <?= $isLocked ? 'disabled' : ''; ?>
                >
            </div>

            <div class="field">
                <label>Password</label>
                <input
                    type="password"
                    name="password"
                    required
                    <?= $isLocked ? 'disabled' : ''; ?>
                >
            </div>

            <button type="submit" class="btn" <?= $isLocked ? 'disabled' : ''; ?>>
                Login
            </button>
        </form>

        <div class="hint">
            Protected admin access · <?= e(APP_NAME); ?>
        </div>
    </main>
</body>
</html>