<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use VoxEarth\Config;
use VoxEarth\Router;
use VoxEarth\Enum\RouteType;
use VoxEarth\Service\SupabaseClient;
use VoxEarth\Service\PollService;
use VoxEarth\Service\TranslationService;
use VoxEarth\Handler\HomeHandler;
use VoxEarth\Handler\PollHandler;
use VoxEarth\Handler\ApiHandler;

// Bootstrap
$config = new Config();
$supabase = new SupabaseClient($config);
$pollService = new PollService($supabase);
$translationService = new TranslationService($supabase);

// CORS preflight for API routes (native app shells call from
// https://localhost / capacitor://localhost origins)
$reqPath = trim((string) parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH), '/');
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS' && str_starts_with($reqPath, 'api/')) {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Access-Control-Max-Age: 86400');
    http_response_code(204);
    exit;
}

// Route
$router = new Router();
$route = $router->resolve($_SERVER['REQUEST_URI'] ?? '/');

// Dispatch
match ($route['type']) {
    RouteType::Home => (new HomeHandler($config))->handle(),

    RouteType::Poll => (new PollHandler($config, $pollService))
        ->handle($route['params']['pollId']),

    RouteType::Create => require __DIR__ . '/create.html',

    RouteType::Ranking => require __DIR__ . '/ranking.html',

    RouteType::Developers => require __DIR__ . '/developers.html',

    RouteType::Privacy => require __DIR__ . '/privacy.html',

    RouteType::Sitemap => (new VoxEarth\Handler\SitemapHandler($config, $supabase))->handle(),

    RouteType::Embed => (function() use ($route) {
        $pollId = htmlspecialchars($route['params']['pollId'], ENT_QUOTES, 'UTF-8');
        header('X-Frame-Options: ALLOWALL');
        header('Content-Security-Policy: frame-ancestors *');
        $html = file_get_contents(__DIR__ . '/embed.html');
        echo str_replace('</head>', "<script>window.EMBED_POLL_ID='{$pollId}';</script>\n</head>", $html);
    })(),

    RouteType::ApiPollCreate => (new ApiHandler($pollService, $translationService, $supabase))
        ->createPoll(),

    RouteType::ApiPollGet => (new ApiHandler($pollService, $translationService, $supabase))
        ->getPoll($route['params']['pollId']),

    RouteType::ApiPollVerifyPassword => (new ApiHandler($pollService, $translationService, $supabase))
        ->verifyPollPassword($route['params']['pollId']),

    RouteType::ApiPollReport => (new ApiHandler($pollService, $translationService, $supabase))
        ->reportPoll($route['params']['pollId']),

    RouteType::ApiTranslation => (new ApiHandler($pollService, $translationService, $supabase))
        ->getTranslation($route['params']['pollId'], $route['params']['langCode']),

    RouteType::ApiPollStats => (new ApiHandler($pollService, $translationService, $supabase))
        ->getPollStats($route['params']['pollId']),

    RouteType::ApiSeriesTrend => (new ApiHandler($pollService, $translationService, $supabase))
        ->getSeriesTrend($route['params']['seriesId']),

    RouteType::ApiOembed => (new ApiHandler($pollService, $translationService, $supabase))
        ->oembed(),

    RouteType::Static => false, // Let web server handle static files

    RouteType::NotFound => (function () {
        http_response_code(404);
        echo 'Not Found';
    })(),
};
