<?php
declare(strict_types=1);

error_reporting(E_ALL);

spl_autoload_register(function (string $class): void {
    $prefix = 'App\\';
    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;
    }
    $relative = substr($class, strlen($prefix));
    $path = __DIR__ . '/../app/' . str_replace('\\', '/', $relative) . '.php';
    if (file_exists($path)) {
        require $path;
    }
});

$configPath = __DIR__ . '/../config/app.php';
if (!file_exists($configPath)) {
    $configPath = __DIR__ . '/../config/app.example.php';
}
$GLOBALS['config'] = require $configPath;

// Pyrk official system timezone.
// Keep this fixed so every API, admin page, client page and cron job uses Lebanon time,
// even if the hosting account / php.ini / old config/app.php is set to another timezone.
$__pyrkTimezone = 'Asia/Beirut';
$GLOBALS['config']['timezone'] = $__pyrkTimezone;
if (!defined('PYRK_SYSTEM_TIMEZONE')) {
    define('PYRK_SYSTEM_TIMEZONE', $__pyrkTimezone);
}
ini_set('display_errors', !empty($GLOBALS['config']['debug']) ? '1' : '0');
ini_set('date.timezone', $__pyrkTimezone);
date_default_timezone_set($__pyrkTimezone);

use App\Core\Auth;
use App\Core\Security;

Security::enforceHttps();
Security::applyHeaders();
Auth::start();

function request_json(): array
{
    $raw = file_get_contents('php://input');
    if (!$raw) {
        return [];
    }
    $decoded = json_decode($raw, true);
    return is_array($decoded) ? $decoded : [];
}

function request_input(): array
{
    $json = request_json();
    return array_merge($_GET, $_POST, $json);
}

function app_config(?string $key = null, mixed $default = null): mixed
{
    $config = $GLOBALS['config'];
    if (!$key) {
        return $config;
    }
    $parts = explode('.', $key);
    $value = $config;
    foreach ($parts as $part) {
        if (!is_array($value) || !array_key_exists($part, $value)) {
            return $default;
        }
        $value = $value[$part];
    }
    return $value;
}
