<?php
$roulette=new \Plugin\NexoraRoulette\NexoraRoulette();
$simulation=null;
$simulationCount=10000;
if(isset($_POST['run_simulation'])) {
    try {
        $simulationCount=in_array((int)($_POST['simulation_count']??10000),array(10000,100000),true)?(int)$_POST['simulation_count']:10000;
        $simulation=$roulette->simulateEconomy($simulationCount);
        message('success','Simulación completada. No se modificó ninguna cuenta ni tabla de giros.');
    } catch(Throwable $e) { message('error',$e->getMessage()); }
}
$dash=$roulette->economyDashboard();
$settings=$roulette->settings();
$walletLabel='Moneda principal';
foreach($roulette->creditConfigs() as $c) if((int)$c['config_id']===(int)$settings['credit_config']){$walletLabel=(string)$c['config_title'];break;}
$fmt=function($v){return number_format((int)$v);};
$ratio=$dash['actual']['return_ratio'];
$pressureLabel='Sin datos'; $pressureClass='default';
if($ratio!==null){
    if($ratio<0.55){$pressureLabel='Drenaje fuerte';$pressureClass='info';}
    elseif($ratio<0.85){$pressureLabel='Controlada';$pressureClass='success';}
    elseif($ratio<=1.05){$pressureLabel='Casi neutra';$pressureClass='warning';}
    else{$pressureLabel='Expansiva';$pressureClass='danger';}
}
?>
<style>
.nxr-econ-card{min-height:118px}.nxr-econ-card small{display:block;color:#777;text-transform:uppercase;font-size:10px;letter-spacing:.08em}.nxr-econ-card h3{margin:6px 0 4px}.nxr-econ-metric{font-size:12px;color:#777}.nxr-sim-summary{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;margin-bottom:15px}.nxr-sim-box{border:1px solid #ddd;background:#fafafa;border-radius:6px;padding:10px}.nxr-sim-box small{display:block;color:#777}.nxr-sim-box strong{font-size:18px}.nxr-bar{height:8px;background:#e9edf1;border-radius:99px;overflow:hidden}.nxr-bar i{display:block;height:100%;background:#6b7785}@media(max-width:1100px){.nxr-sim-summary{grid-template-columns:repeat(3,1fr)}}
</style>
<h1 class="page-header">Economía de Ruleta <small><?php echo htmlspecialchars($roulette->getRealmLabel(),ENT_QUOTES,'UTF-8'); ?></small></h1>
<div class="alert alert-info"><strong>Lectura correcta:</strong> los indicadores de retorno comparan únicamente la moneda principal del giro. Ítems de Arsenal, premios manuales y valor subjetivo de progresión se muestran por separado para no mezclar unidades económicas incompatibles.</div>
<div class="row">
<div class="col-sm-3"><div class="panel panel-default nxr-econ-card"><div class="panel-body"><small>Giros históricos</small><h3><?php echo $fmt($dash['all']['spins']??0); ?></h3><div class="nxr-econ-metric"><?php echo $fmt($dash['all']['players']??0); ?> cuentas únicas</div></div></div></div>
<div class="col-sm-3"><div class="panel panel-default nxr-econ-card"><div class="panel-body"><small><?php echo htmlspecialchars($walletLabel,ENT_QUOTES,'UTF-8'); ?> consumido</small><h3><?php echo $fmt($dash['all']['spent']??0); ?></h3><div class="nxr-econ-metric">Hoy: <?php echo $fmt($dash['today']['spent']??0); ?></div></div></div></div>
<div class="col-sm-3"><div class="panel panel-default nxr-econ-card"><div class="panel-body"><small>Retorno directo</small><h3><?php echo $fmt($dash['all']['wallet_return']??0); ?></h3><div class="nxr-econ-metric"><?php echo $ratio!==null?number_format($ratio*100,1).'% del saldo consumido':'Sin muestra'; ?></div></div></div></div>
<div class="col-sm-3"><div class="panel panel-<?php echo $pressureClass; ?> nxr-econ-card"><div class="panel-body"><small>Presión de saldo directo</small><h3><?php echo $pressureLabel; ?></h3><div class="nxr-econ-metric">No incluye valoración de ítems.</div></div></div></div>
</div>
<div class="row">
<div class="col-sm-3"><div class="panel panel-default nxr-econ-card"><div class="panel-body"><small>Fragmentos en circulación</small><h3><?php echo $fmt($dash['fragment_supply']['current_fragments']??0); ?> ◆</h3><div class="nxr-econ-metric"><?php echo $fmt($dash['fragment_supply']['accounts']??0); ?> cuentas con progresión</div></div></div></div>
<div class="col-sm-3"><div class="panel panel-default nxr-econ-card"><div class="panel-body"><small>Fragmentos consumidos</small><h3><?php echo $fmt($dash['exchange']['fragments_spent']??0); ?> ◆</h3><div class="nxr-econ-metric">Hoy: <?php echo $fmt($dash['exchange_today']['fragments_spent']??0); ?></div></div></div></div>
<div class="col-sm-3"><div class="panel panel-default nxr-econ-card"><div class="panel-body"><small>Retorno de moneda por canje</small><h3><?php echo $fmt($dash['exchange']['wallet_return']??0); ?></h3><div class="nxr-econ-metric"><?php echo htmlspecialchars($walletLabel,ENT_QUOTES,'UTF-8'); ?> acreditado mediante Fragmentos</div></div></div></div>
<div class="col-sm-3"><div class="panel panel-default nxr-econ-card"><div class="panel-body"><small>Canjes históricos</small><h3><?php echo $fmt($dash['exchange']['redemptions']??0); ?></h3><div class="nxr-econ-metric"><?php echo $fmt($dash['exchange']['players']??0); ?> cuentas únicas</div></div></div></div>
</div>
<div class="row">
<div class="col-md-7"><div class="panel panel-default"><div class="panel-heading"><strong>Emisión y retorno reales</strong></div><div class="table-responsive"><table class="table table-striped" style="margin:0"><tbody>
<tr><th>Giros gratuitos consumidos</th><td class="text-right"><?php echo $fmt($dash['all']['free_consumed']??0); ?></td><th>Giros gratuitos entregados por premios</th><td class="text-right"><?php echo $fmt($dash['all']['free_spins_awarded']??0); ?></td></tr>
<tr><th>Premios de Arsenal</th><td class="text-right"><?php echo $fmt($dash['all']['item_prizes']??0); ?></td><th>Premios manuales</th><td class="text-right"><?php echo $fmt($dash['all']['manual_prizes']??0); ?></td></tr>
<tr><th>Fragmentos NXR emitidos por giros</th><td class="text-right"><?php echo $fmt($dash['actual']['fragments_total']??0); ?></td><th>Fragmentos emitidos hoy</th><td class="text-right"><?php echo $fmt($dash['actual']['fragments_today']??0); ?></td></tr>
<tr><th>Fragmentos consumidos en canjes</th><td class="text-right"><strong><?php echo $fmt($dash['exchange']['fragments_spent']??0); ?></strong></td><th>Fragmentos consumidos hoy</th><td class="text-right"><strong><?php echo $fmt($dash['exchange_today']['fragments_spent']??0); ?></strong></td></tr>
<tr><th>Retorno de <?php echo htmlspecialchars($walletLabel,ENT_QUOTES,'UTF-8'); ?> vía canje</th><td class="text-right"><?php echo $fmt($dash['exchange']['wallet_return']??0); ?></td><th>Giros entregados vía canje</th><td class="text-right"><?php echo $fmt($dash['exchange']['free_spins_awarded']??0); ?></td></tr>
<tr><th>Fragmentos actualmente en cuentas</th><td class="text-right"><?php echo $fmt($dash['fragment_supply']['current_fragments']??0); ?></td><th>Fragmentos acumulados históricamente</th><td class="text-right"><?php echo $fmt($dash['fragment_supply']['lifetime_fragments']??0); ?></td></tr>
<tr><th>Hitos acreditados</th><td class="text-right"><?php echo $fmt($dash['milestones']['claims']??0); ?></td><th>Canjes realizados</th><td class="text-right"><?php echo $fmt($dash['exchange']['redemptions']??0); ?></td></tr>
<tr><th>Balance directo histórico</th><td class="text-right"><strong><?php echo ($dash['actual']['net_wallet']??0)>=0?'+':''; ?><?php echo $fmt($dash['actual']['net_wallet']??0); ?></strong></td><th>Balance directo de hoy</th><td class="text-right"><strong><?php echo ($dash['actual']['net_wallet_today']??0)>=0?'+':''; ?><?php echo $fmt($dash['actual']['net_wallet_today']??0); ?></strong></td></tr>
</tbody></table></div></div></div>
<div class="col-md-5"><div class="panel panel-primary"><div class="panel-heading"><strong>Valor esperado del pool actual</strong></div><div class="panel-body">
<p><strong><?php echo number_format((float)$dash['expected']['direct_wallet_return_per_spin'],2); ?></strong> <?php echo htmlspecialchars($walletLabel,ENT_QUOTES,'UTF-8'); ?> de retorno directo esperado por giro.</p>
<p><strong><?php echo number_format((float)$dash['expected']['free_spins_per_spin']*100,2); ?></strong> giros gratuitos esperados por cada 100 giros.</p>
<p><strong><?php echo number_format((float)$dash['expected']['fragments_per_spin'],2); ?></strong> Fragmentos NXR esperados por giro antes de hitos.</p>
<?php if($dash['expected']['direct_return_ratio']!==null){ ?><p>Retorno directo teórico: <strong><?php echo number_format((float)$dash['expected']['direct_return_ratio']*100,2); ?>%</strong> del costo.</p><?php } ?>
<?php if($dash['actual']['return_ratio_with_exchange']!==null){ ?><hr><p>Retorno histórico de la moneda principal incluyendo canjes ya realizados: <strong><?php echo number_format((float)$dash['actual']['return_ratio_with_exchange']*100,2); ?>%</strong>.</p><small class="text-muted">Este indicador sólo suma canjes que acreditan la misma moneda configurada como costo del giro.</small><?php } ?>
</div></div></div>
</div>

<div class="panel panel-warning">
<div class="panel-heading"><strong>Simulador económico sin escritura</strong></div>
<div class="panel-body"><p>Ejecuta una secuencia virtual continua para una cuenta con los pesos actuales. Aplica pity, giros gratuitos, Fragmentos y hitos. No descuenta saldo, no genera ítems y no inserta giros.</p><form method="post" class="form-inline"><div class="form-group"><label>Volumen&nbsp;</label><select name="simulation_count" class="form-control"><option value="10000" <?php echo $simulationCount===10000?'selected':''; ?>>10.000 giros</option><option value="100000" <?php echo $simulationCount===100000?'selected':''; ?>>100.000 giros</option></select></div> <button class="btn btn-warning" type="submit" name="run_simulation" value="1"><i class="fa fa-flask"></i> Simular</button></form></div>
</div>
<?php if(is_array($simulation)){ ?>
<div class="panel panel-default"><div class="panel-heading"><strong>Resultado de <?php echo number_format((int)$simulation['spins']); ?> giros virtuales</strong></div><div class="panel-body">
<div class="nxr-sim-summary">
<div class="nxr-sim-box"><small>Pagados</small><strong><?php echo $fmt($simulation['paid_spins']); ?></strong></div>
<div class="nxr-sim-box"><small>Gratis usados</small><strong><?php echo $fmt($simulation['free_spins_consumed']); ?></strong></div>
<div class="nxr-sim-box"><small>Saldo consumido</small><strong><?php echo $fmt($simulation['spent']); ?></strong></div>
<div class="nxr-sim-box"><small>Saldo devuelto</small><strong><?php echo $fmt($simulation['wallet_return']); ?></strong></div>
<div class="nxr-sim-box"><small>Retorno</small><strong><?php echo $simulation['return_ratio']!==null?number_format($simulation['return_ratio']*100,1).'%':'—'; ?></strong></div>
<div class="nxr-sim-box"><small>Fragmentos</small><strong><?php echo $fmt($simulation['fragments']); ?></strong></div>
</div>
<div class="table-responsive"><table class="table table-striped table-hover"><thead><tr><th>Premio</th><th>Tipo</th><th>Rareza</th><th class="text-right">Apariciones</th><th class="text-right">Frecuencia simulada</th></tr></thead><tbody>
<?php foreach($simulation['counts'] as $row){ $pct=((int)$row['count']/max(1,(int)$simulation['spins']))*100; ?><tr><td><strong><?php echo htmlspecialchars($row['name'],ENT_QUOTES,'UTF-8'); ?></strong></td><td><?php echo htmlspecialchars($row['type'],ENT_QUOTES,'UTF-8'); ?></td><td><?php echo htmlspecialchars($row['rarity'],ENT_QUOTES,'UTF-8'); ?></td><td class="text-right"><?php echo $fmt($row['count']); ?></td><td class="text-right"><?php echo number_format($pct,3); ?>%</td></tr><?php } ?>
</tbody></table></div>
<div class="alert alert-warning" style="margin-bottom:0">El simulador representa una cuenta virtual continua y no aplica máximos diarios por premio/cuenta, porque esos límites dependen del número de jugadores y del período real. El canje de Fragmentos tampoco se simula: es una decisión voluntaria del jugador, no un resultado probabilístico. Úsalo para probar la estructura estadística del pool, no como proyección exacta de calendario.</div>
</div></div>
<?php } ?>
