<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['email', 'password']);

$email = strtolower(clean_str($input['email']));
$password = (string) $input['password'];
$ip = get_client_ip();

$pdo = getDbConnection();

// ---- Brute-force protection ----
$stmt = $pdo->prepare(
    'SELECT COUNT(*) FROM admin_login_attempts
     WHERE email = :email AND success = 0 AND attempted_at > (NOW() - INTERVAL :window SECOND)'
);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':window', ADMIN_LOGIN_WINDOW_SECONDS, PDO::PARAM_INT);
$stmt->execute();
if ((int) $stmt->fetchColumn() >= ADMIN_MAX_LOGIN_ATTEMPTS) {
    send_error('Too many failed attempts. Try again in a few minutes.', 429);
}

function record_attempt(PDO $pdo, string $email, string $ip, bool $success): void
{
    $stmt = $pdo->prepare(
        'INSERT INTO admin_login_attempts (email, ip_address, success) VALUES (:email, :ip, :success)'
    );
    $stmt->execute([':email' => $email, ':ip' => $ip, ':success' => $success ? 1 : 0]);
}

$stmt = $pdo->prepare(
    "SELECT id, full_name, email, password_hash, role, is_blocked
     FROM users WHERE email = :email AND role IN ('ADMIN','SUPER_ADMIN') LIMIT 1"
);
$stmt->execute([':email' => $email]);
$admin = $stmt->fetch();

if (!$admin || !password_verify($password, $admin['password_hash'])) {
    record_attempt($pdo, $email, $ip, false);
    send_error('Invalid email or password.', 401);
}

if ((int) $admin['is_blocked'] === 1) {
    record_attempt($pdo, $email, $ip, false);
    send_error('This admin account has been blocked.', 403);
}

record_attempt($pdo, $email, $ip, true);

$token = create_admin_session((int) $admin['id']);

$upd = $pdo->prepare('UPDATE users SET last_login = NOW() WHERE id = :id');
$upd->execute([':id' => $admin['id']]);

log_admin_action($admin['email'], 'ADMIN_LOGIN', $admin['email'], 'Admin logged in from ' . $ip);

send_success([
    'token' => $token,
    'admin' => [
        'id'        => (int) $admin['id'],
        'full_name' => $admin['full_name'],
        'email'     => $admin['email'],
        'role'      => $admin['role'],
    ],
], 'Login successful.');
