<?php
require_once __DIR__ . '/../app/includes/auth.php';
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; script-src 'self' https://cdn.jsdelivr.net; font-src 'self' data: https://cdn.jsdelivr.net;");
if (current_user()) {
    redirect('/dashboard.php');
}

function login_blocked(string $email, string $ip): bool
{
    $cutoff = date('Y-m-d H:i:s', time() - 900);
    $stmt = db()->prepare("SELECT COUNT(*) FROM login_attempts WHERE success = 0 AND attempted_at >= ? AND (email = ? OR ip_address = ?)");
    $stmt->execute([$cutoff, $email, $ip]);
    return (int)$stmt->fetchColumn() >= 5;
}

function record_login_attempt(string $email, string $ip, bool $success): void
{
    $stmt = db()->prepare('INSERT INTO login_attempts (email, ip_address, success, attempted_at) VALUES (?, ?, ?, ?)');
    $stmt->execute([$email, $ip, $success ? 1 : 0, now()]);
    if ($success) {
        db()->prepare('DELETE FROM login_attempts WHERE success = 0 AND (email = ? OR ip_address = ?)')->execute([$email, $ip]);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $email = trim((string)post('email'));
    $password = (string)post('password');
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';

    if (login_blocked($email, $ip)) {
        flash('error', 'Too many failed login attempts. Please try again later.');
        log_activity('login.blocked', 'Blocked login attempt for ' . $email);
        redirect('/login.php');
    }

    $stmt = db()->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        if ($user['status'] !== 'active') {
            record_login_attempt($email, $ip, false);
            log_activity('login.failed', 'Failed login for deactivated account ' . $email);
            flash('error', 'Your account has been deactivated. Please contact the administrator.');
            redirect('/login.php');
        }
        record_login_attempt($email, $ip, true);
        login_user($user);
        log_activity('login.success', 'Successful login for ' . $email);
        redirect('/dashboard.php');
    }
    record_login_attempt($email, $ip, false);
    log_activity('login.failed', 'Failed login for ' . $email);
    flash('error', 'Invalid email or password.');
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="<?= APP_BASE ?>/assets/css/app.css?v=<?= time() ?>" rel="stylesheet">
</head>
<body class="login-page">
    <div class="login-card">
        <div class="login-logo">F</div>
        <h1><?= APP_NAME ?></h1>
        <p>Sign in to create and manage solar quotations.</p>
        <?php if ($msg = flash('error')): ?><div class="alert alert-danger"><?= e($msg) ?></div><?php endif; ?>
        <form method="post" novalidate>
            <?= csrf_field() ?>
            <label class="form-label">Email</label>
            <input class="form-control mb-3" type="email" name="email" autocomplete="username" required>
            <label class="form-label">Password</label>
            <input class="form-control mb-4" type="password" name="password" autocomplete="current-password" required>
            <button class="btn btn-primary w-100 mb-3" type="submit"><i class="bi bi-box-arrow-in-right me-1"></i>Login</button>
            <div class="d-flex justify-content-between text-muted" style="font-size:0.9rem;">
                <a href="<?= APP_BASE ?>/forgot_password.php" class="text-decoration-none">Forgot Password?</a>
                <a href="<?= APP_BASE ?>/register.php" class="text-decoration-none fw-bold">Create Account</a>
            </div>
        </form>
    </div>
</body>
</html>
