<?php
require_once '../config/database.php';
require_once '../app/helpers/auth.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/login_throttle.php';
require_once '../app/helpers/audit.php';
require_once '../app/helpers/api_security.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
header('Content-Type: application/json; charset=utf-8');
$action = $_GET['action'] ?? '';

switch ($action) {

case 'login':

    $started = microtime(true);
    $email = trim((string)($_POST['email'] ?? ''));
    $password = (string)($_POST['password'] ?? '');
    $csrf = (string)($_POST['csrf_token'] ?? '');
    $dummyHash = '$2y$10$zWbb1XON3QQqDQjlGcWwXeJfy4pE4KuNygeDFQauWl8KWQ/D/VyvG';

    // Validate CSRF token for AJAX login
    if (empty($csrf) || empty($_SESSION['csrf_token']) || !hash_equals((string)$_SESSION['csrf_token'], $csrf)) {
        usleep(300000);
        echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
        exit;
    }

    $throttle = loginThrottleStatus($pdo, $email);
    if ($throttle['locked']) {
        usleep(300000);
        echo json_encode(['status'=>'error','message'=>'Invalid login']);
        exit;
    }

    // 1. Get user + role name
    $stmt = $pdo->prepare("
        SELECT u.id, u.name, u.email, u.password_hash, u.role_id, r.name AS role_name
        FROM users u
        LEFT JOIN roles r ON r.id = u.role_id
        WHERE u.email=? AND u.is_active=1 AND u.deleted_at IS NULL
    ");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    // 2. Validate user
    $hash = $user['password_hash'] ?? $dummyHash;
    $validPassword = password_verify($password, $hash);
    if (!$user || !$validPassword) {
        recordFailedLogin($pdo, $email);
        $elapsed = microtime(true) - $started;
        if ($elapsed < 0.35) {
            usleep((int)((0.35 - $elapsed) * 1000000));
        }
        echo json_encode(['status'=>'error','message'=>'Invalid login']);
        exit;
    }

    clearFailedLogins($pdo, $email);

    // 3. Load permissions
    $permissions = loadUserPermissions($pdo, (int)$user['role_id']);

    // 4. Start session safely
    session_regenerate_id(true);

    // 5. Store session
    $_SESSION['user_id']   = $user['id'];
    $_SESSION['user_name'] = $user['name'];
    $_SESSION['role_id']   = $user['role_id'];
    $_SESSION['role_name'] = $user['role_name'];
    $_SESSION['permissions'] = $permissions;
    $_SESSION['_last_activity'] = time();

    // 6. Audit login
    audit($pdo, (int)$user['id'], 'login', 'auth', (int)$user['id'], 'User logged in', null, null);

    // 7. Success
    echo json_encode(['status'=>'success']);
    break;

case 'logout':
    enforceCsrfForUnsafeRequest();
    $userId = (int)($_SESSION['user_id'] ?? 0);
    if ($userId > 0) {
        require_once '../app/helpers/audit.php';
        try { audit($pdo, $userId, 'logout', 'auth', $userId, 'User logged out', null, null); } catch (Throwable $e) {}
    }
    logoutUser();
    echo json_encode(['status'=>'success']);
    break;
}
