<?php
declare(strict_types=1);

require_once __DIR__ . '/../src/Env.php';
Env::load(__DIR__ . '/../.env');
require_once __DIR__ . '/../src/Response.php';
require_once __DIR__ . '/../src/Database.php';
require_once __DIR__ . '/../src/Auth.php';
require_once __DIR__ . '/../src/GameData.php';
require_once __DIR__ . '/../src/Geo.php';
require_once __DIR__ . '/../src/World.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '/';
$path = preg_replace('#^/api#', '', $path);
$method = $_SERVER['REQUEST_METHOD'];
$body = json_decode(file_get_contents('php://input') ?: '{}', true) ?: [];

try {
    if ($method === 'GET' && $path === '/health') Response::json(['ok' => true, 'service' => 'Ritter Realm', 'time' => gmdate('c')]);
    if ($method === 'GET' && $path === '/game/classes') Response::json(GameData::jsonFile('classes'));
    if ($method === 'GET' && $path === '/game/items') Response::json(GameData::jsonFile('items'));
    if ($method === 'GET' && $path === '/game/companions') Response::json(GameData::jsonFile('companions'));
    if ($method === 'GET' && $path === '/game/pois') Response::json(GameData::jsonFile('pois'));
    if ($method === 'POST' && $path === '/auth/guest') Response::json(Auth::createGuest());
    if ($method === 'POST' && $path === '/auth/register') Response::json(Auth::register($body));
    if ($method === 'POST' && $path === '/auth/login') Response::json(Auth::login($body));

    if ($method === 'GET' && $path === '/player/profile') {
        $playerId = Auth::playerIdFromBearer();
        $stmt = Database::pdo()->prepare("SELECT id, username, class_id, level, xp, gold FROM players WHERE id=?");
        $stmt->execute([$playerId]);
        Response::json(['player' => $stmt->fetch(), 'classes' => GameData::jsonFile('classes')]);
    }

    if ($method === 'GET' && $path === '/world/nearby') {
        $playerId = Auth::playerIdFromBearer();
        Response::json(World::nearby((float)($_GET['lat'] ?? 0), (float)($_GET['lon'] ?? 0), $playerId));
    }

    if ($method === 'POST' && $path === '/poi/capture') {
        $playerId = Auth::playerIdFromBearer();
        Response::json(World::capturePoi($playerId, $body));
    }

    if ($method === 'POST' && $path === '/mystic/loot') {
        $playerId = Auth::playerIdFromBearer();
        Response::json(World::lootMystic($playerId, $body));
    }

    Response::json(['error' => 'not_found', 'path' => $path], 404);
} catch (Throwable $e) {
    $debug = Env::get('APP_DEBUG', 'false') === 'true';
    Response::json(['error' => 'server_error', 'message' => $debug ? $e->getMessage() : 'internal error'], 500);
}
