<?php
/**
 * Nexora Roulette — authenticated JSON action endpoint.
 * Keeps spin/claim requests outside the full website template render.
 */
define('access', 'api');
header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: private, no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('X-Content-Type-Options: nosniff');

function nexora_roulette_api_output($status, array $payload) {
    if(ob_get_level() > 0 && ob_get_length()) @ob_clean();
    http_response_code((int)$status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

try {
    $webengine = rtrim(str_replace('\\', '/', dirname(__DIR__)), '/') . '/includes/webengine.php';
    if(!@include_once($webengine)) throw new RuntimeException('No se pudo iniciar WebEngine.');

    if(($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        header('Allow: POST');
        nexora_roulette_api_output(405, array('ok'=>false,'message'=>'Método no permitido.'));
    }

    if(!isLoggedIn()) {
        nexora_roulette_api_output(401, array('ok'=>false,'message'=>'Tu sesión expiró. Inicia sesión nuevamente.'));
    }

    if(!class_exists('Plugin\\NexoraRoulette\\NexoraRoulette')) {
        throw new RuntimeException('Ruleta Nexora no está disponible en este momento.');
    }

    $roulette = new \Plugin\NexoraRoulette\NexoraRoulette();
    $action = strtolower(trim((string)($_POST['roulette_action'] ?? '')));

    if($action === 'spin' || isset($_POST['spin_submit'])) {
        $result = $roulette->spin(
            (int)$_SESSION['userid'],
            (string)$_SESSION['username'],
            (string)($_POST['roulette_request_token'] ?? '')
        );
        $postState = $roulette->state((string)$_SESSION['username']);
        $settings = $roulette->settings();
        $rarityLabels = \Plugin\NexoraRoulette\NexoraRoulette::rarityLabels();
        $walletLabel = 'Moneda';
        foreach($roulette->creditConfigs() as $cfg) {
            if((int)$cfg['config_id'] === (int)$settings['credit_config']) {
                $walletLabel = (string)$cfg['config_title'];
                break;
            }
        }

        nexora_roulette_api_output(200, array(
            'ok'=>true,
            'message'=>'Giro procesado correctamente.',
            'next_token'=>\Plugin\NexoraRoulette\NexoraRoulette::issueSpinToken(),
            'spin'=>array(
                'id'=>(int)$result['spin_id'],
                'status'=>(string)$result['status'],
                'pity_triggered'=>!empty($result['pity_triggered']),
                'prize'=>array(
                    'id'=>(int)$result['prize']['id'],
                    'name'=>(string)$result['prize']['name'],
                    'description'=>(string)$result['prize']['description'],
                    'rarity'=>(string)$result['prize']['rarity'],
                    'rarity_label'=>(string)($rarityLabels[$result['prize']['rarity']] ?? $result['prize']['rarity']),
                    'type'=>(string)$result['prize']['prize_type'],
                ),
            ),
            'state'=>array(
                'balance'=>$result['balance'] === null ? null : (int)$result['balance'],
                'free_spins'=>(int)$result['free_spins'],
                'total_spins'=>(int)$postState['total_spins'],
                'pity_streak'=>(int)$postState['pity_streak'],
                'wallet_label'=>$walletLabel,
                'spin_cost'=>(int)$settings['spin_cost'],
            ),
        ));
    }

    if($action === 'claim' || isset($_POST['claim_spin_id'])) {
        $spinId = (int)($_POST['claim_spin_id'] ?? 0);
        $claim = $roulette->claimItem($spinId, (int)$_SESSION['userid'], (string)$_SESSION['username']);
        nexora_roulette_api_output(200, array(
            'ok'=>true,
            'message'=>!empty($claim['already']) ? 'Este premio ya había sido entregado.' : 'Entrega confirmada. El ítem ya está en tu baúl.',
            'next_token'=>\Plugin\NexoraRoulette\NexoraRoulette::issueSpinToken(),
        ));
    }

    nexora_roulette_api_output(400, array('ok'=>false,'message'=>'Acción de ruleta inválida.'));
} catch(InvalidArgumentException $e) {
    nexora_roulette_api_output(400, array(
        'ok'=>false,
        'message'=>$e->getMessage(),
        'next_token'=>class_exists('Plugin\\NexoraRoulette\\NexoraRoulette') ? \Plugin\NexoraRoulette\NexoraRoulette::issueSpinToken() : null,
    ));
} catch(Throwable $e) {
    nexora_roulette_api_output(400, array(
        'ok'=>false,
        'message'=>$e->getMessage(),
        'next_token'=>class_exists('Plugin\\NexoraRoulette\\NexoraRoulette') ? \Plugin\NexoraRoulette\NexoraRoulette::issueSpinToken() : null,
    ));
}
