<?php
// Login — no CSRF required for first-time login but rate-limited.
rate_limit('login', 20);
$d = input();
$email = strtolower(trim((string)($d['email'] ?? '')));
$pass  = (string)($d['password'] ?? '');
if (!v_email($email) || $pass === '') json_error('Email and password are required', 422);

$stmt = db()->prepare('SELECT * FROM users WHERE email=? AND deleted_at IS NULL LIMIT 1');
$stmt->execute([$email]);
$user = $stmt->fetch();
if (function_exists('hv5_table_exists') && hv5_table_exists('login_attempts')) {
    db()->prepare('INSERT INTO login_attempts (email, ip, success) VALUES (?,?,?)')->execute([$email, $_SERVER['REMOTE_ADDR'] ?? null, 0]);
}
if (!$user) { audit('login.fail', 'user', null, $email); json_error('Invalid credentials', 401); }

if (!empty($user['locked_until']) && strtotime($user['locked_until']) > time()) {
    json_error('Account temporarily locked. Try again later.', 423);
}
if (!password_verify($pass, $user['password'])) {
    $fails = (int)$user['failed_logins'] + 1;
    $lock  = $fails >= ($GLOBALS['CONFIG']['security']['login_max_attempts'] ?? 6)
        ? date('Y-m-d H:i:s', time() + 60 * ($GLOBALS['CONFIG']['security']['login_lock_minutes'] ?? 15))
        : null;
    $up = db()->prepare('UPDATE users SET failed_logins=?, locked_until=? WHERE id=?');
    $up->execute([$fails, $lock, $user['id']]);
    audit('login.fail', 'user', $user['id'], $email);
    json_error('Invalid credentials', 401);
}
if ($user['status'] !== 'active') json_error('Account ' . $user['status'], 403);

// success
session_regenerate_id(true);
$_SESSION['user_id'] = (int)$user['id'];
db()->prepare('UPDATE users SET last_login=NOW(), last_ip=?, failed_logins=0, locked_until=NULL WHERE id=?')
    ->execute([$_SERVER['REMOTE_ADDR'] ?? null, $user['id']]);
audit('login.success', 'user', $user['id']);
if (function_exists('hv5_table_exists') && hv5_table_exists('login_attempts')) {
    db()->prepare('UPDATE login_attempts SET success=1 WHERE email=? ORDER BY id DESC LIMIT 1')->execute([$email]);
}

$fresh = current_user();
json_ok(['user' => expose_user($fresh ?: $user), 'csrf' => csrf_token()], 'Welcome back');
