<?php
declare(strict_types=1);

require __DIR__ . '/lib/Config.php';
require __DIR__ . '/lib/DB.php';
require __DIR__ . '/lib/Response.php';
require __DIR__ . '/lib/Crypto.php';
require __DIR__ . '/lib/Totp.php';
require __DIR__ . '/lib/Auth.php';
require __DIR__ . '/lib/Audit.php';
require __DIR__ . '/lib/Mailer.php';
require __DIR__ . '/lib/Uploads.php';
require __DIR__ . '/lib/Tickets.php';
require __DIR__ . '/lib/Xlsx.php';

Config::load(__DIR__ . '/config/config.php');
date_default_timezone_set((string) Config::get('timezone', 'Asia/Jerusalem'));

header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: same-origin');

// Path after /api, e.g. "auth/login". Works at the domain root and under a
// sub-path such as /cs/api/..., so no change is needed when the folder moves.
$path   = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/';
$path   = preg_replace('#^.*?/api/?#', '', $path, 1);
$path   = trim((string) $path, '/');
$seg    = $path === '' ? [] : explode('/', $path);
$method = $_SERVER['REQUEST_METHOD'];

/** Matches a route pattern like ['tickets', '#'] against the URL segments. */
function route(string $method, array $pattern, callable $handler): void
{
    global $seg;
    if ($_SERVER['REQUEST_METHOD'] !== $method || count($seg) !== count($pattern)) {
        return;
    }
    $args = [];
    foreach ($pattern as $i => $part) {
        if ($part === '#') {
            if (!ctype_digit($seg[$i])) {
                return;
            }
            $args[] = (int) $seg[$i];
        } elseif ($part !== $seg[$i]) {
            return;
        }
    }
    $handler(...$args);
    exit;
}

try {
    Auth::boot();
    Auth::checkCsrf();

    require __DIR__ . '/routes/auth.php';
    require __DIR__ . '/routes/catalogs.php';
    require __DIR__ . '/routes/tickets.php';
    require __DIR__ . '/routes/attachments.php';
    require __DIR__ . '/routes/export.php';
    require __DIR__ . '/routes/documents.php';
    require __DIR__ . '/routes/admin.php';

    Response::error('הנתיב לא נמצא', 404);
} catch (ApiError $e) {
    Response::error($e->getMessage(), $e->getCode() ?: 400);
} catch (PDOException $e) {
    // A unique key or foreign key rejection is a user mistake, not a crash.
    if ($e->getCode() === '23000') {
        error_log('[helpdesk] constraint: ' . $e->getMessage());
        Response::error(str_contains($e->getMessage(), 'Duplicate entry')
            ? 'הערך כבר קיים במערכת'
            : 'הפעולה מפרה קשר בין נתונים קיימים', 409);
    }
    error_log('[helpdesk] ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());
    Response::error('שגיאת שרת. פנו למנהל המערכת.', 500);
} catch (Throwable $e) {
    error_log('[helpdesk] ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());
    Response::error('שגיאת שרת. פנו למנהל המערכת.', 500);
}
