<?php

declare(strict_types=1);

/**
 * Front controller + router. All requests hit public/index.php.
 *
 * Auth (AuthController):
 *   GET  /login, POST /login
 *   GET  /login/mfa, POST /login/mfa, POST /login/mfa/resend
 *   GET  /login/mfa/options, POST /login/mfa/passkey
 *   GET  /login/passkey/options, POST /login/passkey
 *   GET  /mfa/wizard, POST /mfa/wizard/totp, POST /mfa/wizard/skip
 *   GET  /mfa/wizard/passkey/options, POST /mfa/wizard/passkey/register
 *   GET  /mfa/wizard/qr
 *   POST /logout
 *   GET  /password/forgot, POST /password/forgot
 *   GET  /password/reset, POST /password/reset
 *   GET  /invite/accept, POST /invite/accept
 *
 * Profile (ProfileController):
 *   GET  /profile
 *   GET  /profile/totp/setup, POST /profile/totp/confirm, POST /profile/totp/disable
 *   GET  /profile/passkeys/options, POST /profile/passkeys/register, POST /profile/passkeys/delete
 *
 * Tickets (TicketController):
 *   GET  /, GET /tickets, GET /tickets/archive, GET /tickets/new
 *   POST /tickets, POST /tickets/ai-check, POST /tickets/priority-check
 *   POST /tickets/{id}/reply, POST /tickets/{id}/ai-rewrite
 *   GET  /tickets/{id}, GET /tickets/{id}/state
 *   POST /tickets/{id}/escalate, POST /tickets/{id}/status
 *   POST /tickets/{id}/assign
 *   POST /tickets/{id}/links, POST /tickets/{id}/links/{linkedId}/remove
 *
 * Triage (TriageController):
 *   GET  /triage, POST /triage/act
 *
 * Admin (AdminController + CompanyAdminController):
 *   GET  /admin/users, POST /admin/invite, POST /admin/users/toggle
 *   POST /admin/users/capabilities, POST /admin/users/triage-access
 *   GET  /admin/users/{id}/ticket, POST /admin/users/{id}/ticket
 *   GET  /admin/departments, POST /admin/departments
 *   GET  /admin/companies, POST /admin/companies
 *   GET  /admin/slas, POST /admin/slas
 *   GET  /admin/directory, POST /admin/directory, POST /admin/directory/sync
 *   GET  /admin/mailboxes, POST /admin/mailboxes, POST /admin/mailboxes/poll
 *   GET  /admin/api-keys, POST /admin/api-keys, POST /admin/api-keys/toggle
 *   GET  /admin/settings, POST /admin/settings
 *   POST /admin/settings/smtp, POST /admin/settings/smtp-test, POST /admin/settings/theme, POST /admin/settings/ai-agent
 *   GET  /admin/stats, GET /admin/audit
 *   GET  /branding/{file}
 *
 * API (ApiController, Bearer key):
 *   POST /api/v1/tickets, POST /api/v1/classify
 */

declare(strict_types=1);

require_once dirname(__DIR__) . '/src/bootstrap.php';

use App\Controllers\AdminController;
use App\Controllers\ApiController;
use App\Controllers\AuthController;
use App\Controllers\ProfileController;
use App\Controllers\TicketController;
use App\Controllers\TriageController;
use App\Services\AuthService;

header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; script-src 'self'");

AuthService::startSecureSession();

$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

$auth = new AuthController();
$tickets = new TicketController();
$triage = new TriageController();
$admin = new AdminController();
$api = new ApiController();
$profile = new ProfileController();
$co = new \App\Controllers\CompanyAdminController();
$canned = new \App\Controllers\CannedReplyAdminController();

// Strip base path if deployed under a subdirectory (APP_URL path part).
$basePath = parse_url(imms_base_url(), PHP_URL_PATH) ?? '';
if ($basePath !== '' && str_starts_with($path, $basePath)) {
    $path = substr($path, strlen($basePath)) ?: '/';
}

$routes = [
    'GET /login' => fn() => $auth->showLogin(),
    'POST /login' => fn() => $auth->login(),
    'GET /login/mfa' => fn() => $auth->showMfa(),
    'POST /login/mfa' => fn() => $auth->verifyMfa(),
    'POST /login/mfa/resend' => fn() => $auth->resendMfa(),
    'GET /mfa/wizard' => fn() => $auth->showWizard(),
    'POST /mfa/wizard/totp' => fn() => $auth->wizardTotp(),
    'POST /mfa/wizard/skip' => fn() => $auth->wizardSkip(),
    'GET /mfa/wizard/passkey/options' => fn() => $auth->wizardPasskeyOptions(),
    'POST /mfa/wizard/passkey/register' => fn() => $auth->wizardPasskeyRegister(),
    'GET /mfa/wizard/qr' => fn() => $auth->wizardQr(),
    'GET /login/mfa/options' => fn() => $auth->passkeyOptions(),
    'POST /login/mfa/passkey' => fn() => $auth->passkeyVerify(),
    'GET /login/passkey/options' => fn() => $auth->passkeyLoginOptions(),
    'POST /login/passkey' => fn() => $auth->passkeyLogin(),
    'POST /logout' => fn() => $auth->logout(),
    'GET /profile' => fn() => $profile->show(),
    'POST /profile/start-page' => fn() => $profile->saveStartPage(),
    'GET /profile/sidebar-prefs' => fn() => $profile->sidebarPrefs(),
    'POST /profile/sidebar-prefs' => fn() => $profile->saveSidebarPrefs(),
    'GET /profile/totp/setup' => fn() => $profile->totpSetup(),
    'POST /profile/totp/confirm' => fn() => $profile->totpConfirm(),
    'POST /profile/totp/disable' => fn() => $profile->totpDisable(),
    'GET /profile/passkeys/options' => fn() => $profile->passkeyOptions(),
    'POST /profile/passkeys/register' => fn() => $profile->passkeyRegister(),
    'POST /profile/passkeys/delete' => fn() => $profile->passkeyDelete(),
    'GET /password/forgot' => fn() => $auth->showForgot(),
    'POST /password/forgot' => fn() => $auth->forgot(),
    'GET /password/reset' => fn() => $auth->showReset(),
    'POST /password/reset' => fn() => $auth->reset(),
    'GET /invite/accept' => fn() => $auth->showInviteAccept(),
    'POST /invite/accept' => fn() => $auth->acceptInvite(),

    'GET /' => fn() => header('Location: ' . (AuthService::user() ? AuthService::homeDestination(AuthService::user()) : '/login')),
    'GET /tickets' => fn() => $tickets->index(),
    'GET /tickets/archive' => fn() => $tickets->archive(),
    'GET /tickets/new' => fn() => $tickets->createForm(),
    'POST /tickets' => fn() => $tickets->create(),
    'POST /tickets/ai-check' => fn() => $tickets->aiCheck(),
    'POST /tickets/priority-check' => fn() => $tickets->priorityCheck(),
    'POST /tickets/{id}/reply' => fn(int $id) => $tickets->reply($id),
    'POST /tickets/{id}/agent-draft/{msgId}/send' => fn(int $id, int $msgId) => $tickets->agentDraftSend($id, $msgId),
    'POST /tickets/{id}/agent-draft/{msgId}/discard' => fn(int $id, int $msgId) => $tickets->agentDraftDiscard($id, $msgId),
    'POST /tickets/{id}/ai-rewrite' => fn(int $id) => $tickets->aiRewriteReply($id),
    'GET /tickets/{id}' => fn(int $id) => $tickets->show($id),
    'GET /tickets/{id}/state' => fn(int $id) => $tickets->state($id),
    'GET /tickets/{id}/updates' => fn(int $id) => $tickets->updates($id),
    'GET /tickets/live-count' => fn() => $tickets->liveCount(),
    'POST /tickets/{id}/escalate' => fn(int $id) => $tickets->escalate($id),
    'POST /tickets/{id}/status' => fn(int $id) => $tickets->status($id),
    'POST /tickets/{id}/undo-close' => fn(int $id) => $tickets->undoClose($id),
    'POST /tickets/{id}/links' => fn(int $id) => $tickets->addLink($id),
    'POST /tickets/{id}/links/{linkedId}/remove' => fn(int $id, int $linkedId) => $tickets->removeLink($id, $linkedId),
    'POST /tickets/views/save' => fn() => $tickets->saveView(),
    'POST /tickets/views/{id}/delete' => fn(int $id) => $tickets->deleteView($id),
    'POST /tickets/bulk' => fn() => $tickets->bulkAction(),
    'GET /attachments/{id}/download' => fn(int $id) => $tickets->download($id),

    'GET /triage' => fn() => $triage->index(),
    'POST /triage/act' => fn() => $triage->act(),

    'GET /admin/users' => fn() => $admin->users(),
    'GET /admin/users/{id}/ticket' => fn(int $id) => $admin->ticketForUserForm($id),
    'POST /admin/users/{id}/ticket' => fn(int $id) => $admin->ticketForUser($id),
    'POST /admin/invite' => fn() => $admin->invite(),
    'POST /admin/invite/revoke' => fn() => $admin->revokeInvite(),
    'POST /admin/users/capabilities' => fn() => $admin->saveCapabilities(),
    'POST /admin/users/triage-access' => fn() => $admin->setTriageAccess(),
    'GET /admin/departments' => fn() => $admin->departments(),
    'POST /admin/departments' => fn() => $admin->saveDepartment(),
    'GET /admin/api-keys' => fn() => $admin->apiKeys(),
    'POST /admin/api-keys' => fn() => $admin->createApiKey(),
    'POST /admin/api-keys/toggle' => fn() => $admin->toggleApiKey(),
    'GET /admin/agent-triggers' => fn() => $admin->agentTriggers(),
    'POST /admin/agent-triggers' => fn() => $admin->saveAgentTrigger(),
    'POST /admin/agent-triggers/delete' => fn() => $admin->deleteAgentTrigger(),
    'POST /admin/agent-triggers/generate' => fn() => $admin->generateAgentTrigger(),
    'POST /admin/agent-triggers/toggle' => fn() => $admin->toggleAgent(),
    'POST /admin/agent-triggers/test' => fn() => $admin->agentTriggerTest(),
    'GET /admin/settings' => fn() => $admin->settings(),
    'GET /admin/stats' => fn() => $admin->stats(),
    'POST /admin/settings' => fn() => $admin->saveSettings(),
    'GET /admin/audit' => fn() => $admin->audit(),
    'GET /admin/companies' => fn() => $co->companies(),
    'POST /admin/companies' => fn() => $co->saveCompany(),
    'GET /admin/slas' => fn() => $co->slas(),
    'POST /admin/slas' => fn() => $co->saveSla(),
    'GET /admin/directory' => fn() => $co->directory(),
    'POST /admin/directory' => fn() => $co->saveDirectory(),
    'POST /admin/directory/sync' => fn() => $co->syncDirectory(),
    'GET /admin/mailboxes' => fn() => $co->mailboxes(),
    'POST /admin/mailboxes' => fn() => $co->saveMailbox(),
    'POST /admin/mailboxes/poll' => fn() => $co->pollMailbox(),
    'POST /admin/settings/smtp' => fn() => $admin->saveSmtp(),
    'POST /admin/settings/smtp-test' => fn() => $admin->testMail(),
    'POST /admin/settings/theme' => fn() => $admin->saveTheme(),
    'GET /branding/{file}' => fn(string $file) => $admin->branding($file),
    'POST /admin/settings/ai-agent' => fn() => $admin->saveAiAgent(),

    'POST /api/v1/tickets' => fn() => $api->createTicket(),
    'POST /api/v1/classify' => fn() => $api->classify(),
    'GET /admin/canned' => fn() => $canned->index(),
    'POST /admin/canned' => fn() => $canned->save(),
    'POST /admin/canned/{id}/update' => fn(int $id) => $canned->save(),
    'POST /admin/canned/{id}/delete' => fn(int $id) => $canned->delete($id),
];
foreach ($routes as $route => $handler) {
    [$routeMethod, $routePath] = explode(' ', $route, 2);
    if ($routeMethod !== $method) {
        continue;
    }
    if ($routePath === $path) {
        $handler();
        exit;
    }
    // {param} segments (numeric)
    $pattern = '#^' . preg_replace('/\\\\\\{[a-zA-Z]+\\\\\\}/', '(\\d+)', preg_quote($routePath, '#')) . '$#';
    if (preg_match($pattern, $path, $m)) {
        $args = array_map('intval', array_slice($m, 1));
        $handler(...$args);
        exit;
    }
}

http_response_code(404);
final class NotFoundController extends \App\Controllers\Controller {
    public function render(): void {
        $this->view('errors/404', [], 'layout');
    }
}
(new NotFoundController())->render();
