<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/SimpleCaptcha.php';

if (isUserLoggedIn()) {
    redirect('');
}

$pdo = getPDO();
$errorMsg = null;
$formEmail = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
    $formEmail = trim($_POST['email'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $captchaInput = $_POST['captcha'] ?? '';

    if (!SimpleCaptcha::verify($captchaInput)) {
        $errorMsg = __('err_captcha');
    } elseif (empty($email) || empty($password)) {
        $errorMsg = __('err_login');
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND role IN ('client','announcer') LIMIT 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($password, $user['password_hash'])) {
            $errorMsg = __('err_login');
        } elseif (!$user['email_verified']) {
            $errorMsg = __('err_account_not_verified');
        } elseif ($user['status'] !== 'active') {
            $errorMsg = __('err_account_suspended');
        } else {
            // post_verify_redirect n'est utilisé que par le flux inscription->activation
            // (voir verify-account.php) ; une connexion normale ne doit jamais en hériter.
            unset($_SESSION['post_verify_redirect']);
            loginUserSession($user);
            redirect('');
        }
    }
}

$pageTitle = __('login_title');
require_once ROOT_PATH . '/templates/partials/header.php';
?>

<div class="max-w-md mx-auto px-4 py-16">
    <div class="bg-luxury-card border border-luxury-rose/10 rounded-2xl p-8 border-rose-glow space-y-6">

        <div class="text-center">
            <h1 class="font-playfair text-2xl font-bold text-luxury-rose"><?= __('login_title') ?></h1>
        </div>

        <?php if ($errorMsg): ?>
            <div class="p-3 bg-red-950/30 border border-red-500/20 text-red-400 text-sm font-light rounded-lg">
                ⚠️ <?= e($errorMsg) ?>
            </div>
        <?php endif; ?>

        <form action="" method="POST" class="space-y-5">
            <div>
                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_account_email') ?> *</label>
                <input type="email" name="email" required value="<?= e($formEmail) ?>"
                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
            </div>

            <div>
                <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_password') ?> *</label>
                <input type="password" name="password" required
                       class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                <p class="text-right mt-1.5">
                    <a href="<?= BASE_URL ?>/forgot-password.php" class="text-[11px] text-luxury-rose hover:text-luxury-rosehover underline"><?= __('forgot_password_link') ?></a>
                </p>
            </div>

            <!-- Captcha -->
            <div class="bg-luxury-darker/60 rounded-xl p-4 border border-luxury-rose/5 space-y-3">
                <div class="flex items-center justify-between">
                    <span class="text-xs font-semibold uppercase tracking-wider text-luxury-muted"><?= __('admin_captcha') ?></span>
                    <div class="flex items-center gap-2">
                        <img id="captcha-img" src="<?= BASE_URL ?>/captcha-image.php" alt="captcha" class="rounded border border-luxury-rose/15">
                        <button type="button" onclick="reloadCaptcha()" class="text-luxury-rose hover:text-luxury-rosehover text-xs" title="<?= __('captcha_reload') ?>">↻</button>
                    </div>
                </div>
                <input type="text" name="captcha" required autocomplete="off" placeholder="<?= __('captcha_placeholder') ?>"
                       class="bg-luxury-card text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
            </div>

            <button type="submit" class="w-full py-3 bg-gradient-to-r from-luxury-rose to-luxury-rosehover hover:from-luxury-rosehover hover:to-luxury-rose text-luxury-dark text-xs font-bold uppercase tracking-widest rounded-lg shadow-md transition duration-300">
                <?= __('btn_login') ?>
            </button>
        </form>

        <p class="text-center text-xs text-luxury-muted">
            <?= __('no_account_yet') ?> <a href="<?= BASE_URL ?>/register.php" class="text-luxury-rose hover:text-luxury-rosehover underline"><?= __('register_link') ?></a>
        </p>
    </div>
</div>

<script>
    function reloadCaptcha() {
        document.getElementById('captcha-img').src = '<?= BASE_URL ?>/captcha-image.php?t=' + Date.now();
    }
</script>

<?php
require_once ROOT_PATH . '/templates/partials/footer.php';
?>
