<?php
// helpers/auth.php
require_once __DIR__ . '/../config/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Detect API request (so we can return JSON errors instead of HTML)
 */
function is_api_request(): bool
{
    $uri = $_SERVER['REQUEST_URI'] ?? '';
    if (strpos($uri, '/api/') !== false) return true;

    $accept = $_SERVER['HTTP_ACCEPT'] ?? '';
    if (stripos($accept, 'application/json') !== false) return true;

    return false;
}

/**
 * Standardized deny access (JSON for API, plain text for pages)
 */
function deny_access(int $status, string $message): void
{
    http_response_code($status);

    if (is_api_request()) {
        header('Content-Type: application/json');
        echo json_encode(['ok' => false, 'error' => $message]);
        exit;
    }

    // For normal pages:
    die($status . ' ' . $message);
}

/**
 * Check if user is logged in
 */
function is_logged_in(): bool
{
    return isset($_SESSION['user']) && is_array($_SESSION['user']);
}

/**
 * Require login or redirect/deny
 */
function require_login(): void
{
    if (!is_logged_in()) {
        if (is_api_request()) {
            deny_access(401, 'Not logged in');
        } else {
            header('Location: login.php');
            exit;
        }
    }
}

/**
 * Get current logged-in user array
 */
function current_user(): ?array
{
    return is_logged_in() ? $_SESSION['user'] : null;
}

/**
 * Require role by role_name (admin/staff/driver)
 */
function require_role(array $allowed_roles): void
{
    require_login();

    $user = current_user();
    $role = $user['role_name'] ?? '';

    if (!$user || !in_array($role, $allowed_roles, true)) {
        deny_access(403, 'Forbidden: You do not have access to this resource');
    }
}

/**
 * Attempt login by username + password.
 * Returns true on success, false on failure.
 */
function login_attempt(string $username, string $password): bool
{
    $pdo = db();

    $sql = "
        SELECT u.id, u.full_name, u.username, u.email, u.phone,
               u.password_hash, u.is_active,
               r.name AS role_name
        FROM users u
        JOIN roles r ON r.id = u.role_id
        WHERE u.username = :username
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([':username' => $username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) return false;
    if ((int)$user['is_active'] !== 1) return false;
    if (!password_verify($password, $user['password_hash'])) return false;

    // Store only safe fields in session (never store password hash)
    $_SESSION['user'] = [
        'id' => (int)$user['id'],
        'full_name' => $user['full_name'],
        'username' => $user['username'],
        'email' => $user['email'],
        'phone' => $user['phone'],
        'role_name' => $user['role_name'],
    ];

    // Update last_login_at (best effort)
    try {
        $upd = $pdo->prepare("UPDATE users SET last_login_at = NOW() WHERE id = :id");
        $upd->execute([':id' => (int)$user['id']]);
    } catch (Throwable $e) {
        // Ignore logging errors
    }

    return true;
}

/**
 * Logout user
 */
function logout(): void
{
    $_SESSION = [];

    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params["path"],
            $params["domain"],
            $params["secure"],
            $params["httponly"]
        );
    }

    session_destroy();
}
