<?php
// login.php
require_once 'includes/auth.php';
require_once 'db.php';

if (current_user()) {
    header('Location: index.php');
    exit;
}

// SECURITY FIX: rate-limiting moved from $_SESSION (trivially bypassed by
// simply discarding cookies between attempts — a new session resets the
// counter to zero) to a persistent DB record keyed by IP + email. This
// survives across sessions, which is what a rate limit actually needs to do.
function loginIdentifier(string $email): string
{
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    return $ip . '|' . strtolower(trim($email));
}

function recentFailedAttempts(PDO $pdo, string $identifier): int
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*) FROM tbl_login_attempts WHERE identifier = ? AND attempted_at > NOW() - INTERVAL 15 MINUTE"
    );
    $stmt->execute([$identifier]);
    return (int) $stmt->fetchColumn();
}

function recordFailedAttempt(PDO $pdo, string $identifier): void
{
    $stmt = $pdo->prepare("INSERT INTO tbl_login_attempts (identifier) VALUES (?)");
    $stmt->execute([$identifier]);
}

$error = '';
$setupSuccess = isset($_GET['setup']) && $_GET['setup'] === 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf(); // SECURITY FIX: closes the Login CSRF gap

    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $identifier = loginIdentifier($email);

    $failedCount = recentFailedAttempts($pdo, $identifier);

    if ($failedCount >= 5) {
        $error = "Too many failed attempts for this account. Try again in 15 minutes.";
    } else {
        $stmt = $pdo->prepare("SELECT * FROM tbl_users WHERE Email = ? AND Deleted_At IS NULL LIMIT 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && (int) $user['Is_Active'] === 1 && password_verify($password, $user['Password_Hash'])) {
            // Session fixation protection: always issue a fresh session ID on login.
            session_regenerate_id(true);

            $_SESSION['user'] = [
                'id'    => (int) $user['UserID'],
                'name'  => $user['Name'],
                'email' => $user['Email'],
                'role'  => $user['Role'],
            ];

            // Coordinator's natural landing page is the expiry dashboard,
            // not the certificate register they can't act on anyway.
            header('Location: ' . ($user['Role'] === 'coordinator' ? 'expiry_dashboard.php' : 'index.php'));
            exit;
        } else {
            recordFailedAttempt($pdo, $identifier);
            $remaining = 5 - ($failedCount + 1);
            $error = $remaining > 0
                ? "Invalid email or password. ({$remaining} attempt(s) remaining before a temporary lock.)"
                : "Invalid email or password. Too many failed attempts — account locked for 15 minutes.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Liftek Iraq — Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container" style="max-width: 400px; margin-top: 100px;">
    <div class="text-center mb-4">
        <h2 class="fw-bold text-primary m-0">Liftek</h2>
        <small class="text-muted">Technical Inspection & NDT Register</small>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-body p-4">
            <?php if ($setupSuccess): ?>
                <div class="alert alert-success py-2">Admin account created. You can log in now.</div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="alert alert-danger py-2"><?= htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <form method="POST">
                <?php csrf_field(); ?>
                <div class="mb-3">
                    <label class="form-label small fw-bold">Email</label>
                    <input type="email" name="email" class="form-control" required autofocus>
                </div>
                <div class="mb-4">
                    <label class="form-label small fw-bold">Password</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary w-100 fw-bold">Log In</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>
