<?php
/**
 * MU Nexora — public read-only equipped-items endpoint.
 */
define('access', 'api');
header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: private, no-store, max-age=0');
header('Pragma: no-cache');

try {
    $webengine = rtrim(str_replace('\\', '/', dirname(__DIR__)), '/') . '/includes/webengine.php';
    if(!@include_once($webengine)) throw new RuntimeException('Service unavailable.');

    if(($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
        http_response_code(405);
        header('Allow: GET');
        throw new RuntimeException('Método no permitido.');
    }

    $realm = class_exists('NexoraRealm')
        ? NexoraRealm::validate(isset($_GET['realm']) ? $_GET['realm'] : NexoraRealm::active())
        : null;
    if(class_exists('NexoraRealm')) NexoraRealm::selectPublic($realm, false);

    if(!isset($_GET['req']) || !is_string($_GET['req']) || $_GET['req'] === '') {
        http_response_code(400);
        throw new InvalidArgumentException('Personaje no especificado.');
    }

    $encoded = trim($_GET['req']);
    if(!Validator::Chars($encoded, array('a-z', 'A-Z', '0-9', '_', '-'))) {
        http_response_code(400);
        throw new InvalidArgumentException('Solicitud inválida.');
    }

    $character = base64url_decode($encoded);
    if($character === false || !is_string($character) || $character === '') {
        http_response_code(400);
        throw new InvalidArgumentException('Solicitud inválida.');
    }

    $equipment = new ProfileEquipment($character, $realm);
    $result = $equipment->getPublicEquipment();
    http_response_code(200);
    echo json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch(InvalidArgumentException $ex) {
    if(http_response_code() < 400) http_response_code(400);
    echo json_encode(array('ok' => false, 'error' => $ex->getMessage()), JSON_UNESCAPED_UNICODE);
} catch(Exception $ex) {
    if(http_response_code() < 400) http_response_code(500);
    echo json_encode(array(
        'ok' => false,
        'error' => 'No se pudo actualizar el equipamiento en este momento.'
    ), JSON_UNESCAPED_UNICODE);
}
