<?php

require_once __DIR__ . '/../config/auth.php';

header('Content-Type: application/json');

function json_response(array $payload, int $statusCode = 200): void
{
    http_response_code($statusCode);
    echo json_encode($payload);
    exit;
}

function api_require_login(): void
{
    if (!is_logged_in()) {
        json_response(['success' => false, 'message' => 'Login required.'], 401);
    }
}

function api_require_admin(): void
{
    api_require_login();

    if ((current_user()['role'] ?? '') !== 'Admin') {
        json_response(['success' => false, 'message' => 'Access denied.'], 403);
    }
}

function clean_text(mixed $value): string
{
    return trim((string) $value);
}

function title_case_text(mixed $value): string
{
    $text = preg_replace('/\s+/', ' ', clean_text($value));
    return ucwords(strtolower($text));
}
