<?php
$roulette=new \Plugin\NexoraRoulette\NexoraRoulette();
if(isset($_POST['save_prize'])) {
    try { $id=$roulette->savePrize($_POST); message('success','Premio #'.$id.' guardado para '.$roulette->getRealmLabel().'.'); }
    catch(Throwable $e){ message('error',$e->getMessage()); }
}
if(isset($_POST['retire_id'])) {
    try { $roulette->retirePrize((int)$_POST['retire_id']); message('success','Premio retirado del pool. El historial anterior se conserva.'); }
    catch(Throwable $e){ message('error',$e->getMessage()); }
}
$edit=null;
if(isset($_GET['edit'])) $edit=$roulette->getPrize((int)$_GET['edit']);
$types=\Plugin\NexoraRoulette\NexoraRoulette::prizeTypeLabels();
$rarities=\Plugin\NexoraRoulette\NexoraRoulette::rarityLabels();
$credits=$roulette->creditConfigs();
$items=$roulette->itemshopItems();
$prizes=$roulette->getPrizes(false);
$odds=$roulette->odds(true); $probById=array(); foreach($odds['prizes'] as $p) $probById[(int)$p['id']]=(float)$p['probability'];
$defaults=array('id'=>0,'name'=>'','description'=>'','prize_type'=>'credits','rarity'=>'common','weight'=>100,'amount'=>0,'credit_config_id'=>0,'item_id'=>0,'daily_global_limit'=>0,'daily_account_limit'=>0,'active'=>1,'sort_order'=>100);
$f=is_array($edit)?array_merge($defaults,$edit):$defaults;
?>
<h1 class="page-header">Premios de Ruleta <small><?php echo htmlspecialchars($roulette->getRealmLabel(),ENT_QUOTES,'UTF-8'); ?></small></h1>
<div class="alert alert-info"><strong>Economía y geometría están separadas:</strong> el <strong>Peso</strong> controla la probabilidad real del servidor. El <strong>Orden visual</strong> controla la posición alrededor de la rueda. Desde V1.2.0 todos los segmentos visibles son simétricos e idénticos en tamaño, aunque sus probabilidades sean diferentes.</div>
<div class="row">
<div class="col-lg-5">
<div class="panel panel-primary"><div class="panel-heading"><?php echo (int)$f['id']>0?'Editar premio #'.(int)$f['id']:'Nuevo premio'; ?></div><div class="panel-body">
<form method="post" id="roulettePrizeForm">
<input type="hidden" name="id" value="<?php echo (int)$f['id']; ?>">
<div class="form-group"><label>Nombre</label><input class="form-control" name="name" maxlength="120" required value="<?php echo htmlspecialchars($f['name'],ENT_QUOTES,'UTF-8'); ?>"></div>
<div class="form-group"><label>Descripción para el jugador</label><textarea class="form-control" name="description" maxlength="400" rows="2"><?php echo htmlspecialchars($f['description'],ENT_QUOTES,'UTF-8'); ?></textarea></div>
<div class="row"><div class="col-sm-6"><div class="form-group"><label>Tipo</label><select class="form-control" name="prize_type" id="roulettePrizeType"><?php foreach($types as $key=>$label){ ?><option value="<?php echo $key; ?>" <?php echo $f['prize_type']===$key?'selected':''; ?>><?php echo htmlspecialchars($label,ENT_QUOTES,'UTF-8'); ?></option><?php } ?></select></div></div><div class="col-sm-6"><div class="form-group"><label>Rareza</label><select class="form-control" name="rarity"><?php foreach($rarities as $key=>$label){ ?><option value="<?php echo $key; ?>" <?php echo $f['rarity']===$key?'selected':''; ?>><?php echo htmlspecialchars($label,ENT_QUOTES,'UTF-8'); ?></option><?php } ?></select></div></div></div>
<div class="row"><div class="col-sm-6"><div class="form-group"><label>Peso</label><input type="number" min="0" max="100000000" class="form-control" name="weight" value="<?php echo (int)$f['weight']; ?>"></div></div><div class="col-sm-6"><div class="form-group"><label>Orden visual</label><input type="number" class="form-control" name="sort_order" value="<?php echo (int)$f['sort_order']; ?>"></div></div></div>
<div id="rouletteCreditsFields">
<div class="form-group"><label>Moneda que recibe</label><select class="form-control" name="credit_config_id"><option value="0">— Seleccionar —</option><?php foreach($credits as $cfg){ ?><option value="<?php echo (int)$cfg['config_id']; ?>" <?php echo (int)$f['credit_config_id']===(int)$cfg['config_id']?'selected':''; ?>>#<?php echo (int)$cfg['config_id']; ?> · <?php echo htmlspecialchars($cfg['config_title'],ENT_QUOTES,'UTF-8'); ?></option><?php } ?></select></div>
</div>
<div id="rouletteAmountFields"><div class="form-group"><label>Cantidad</label><input type="number" min="0" class="form-control" name="amount" value="<?php echo (int)$f['amount']; ?>"><span class="help-block">Para saldo: créditos entregados. Para giros: cantidad adicional. Para Fragmentos NXR: cantidad acumulada.</span></div></div>
<div id="rouletteItemFields">
<div class="form-group"><label>Buscar en Arsenal</label><input type="text" class="form-control" id="rouletteItemFilter" placeholder="Escribe nombre, sección o ID"></div>
<div class="form-group"><label>Ítem</label><select class="form-control" size="7" name="item_id" id="rouletteItemSelect"><option value="0">— Seleccionar —</option><?php foreach($items as $item){ $label='#'.(int)$item['id'].' · '.(string)$item['name'].' · '.$item['item_section'].':'.$item['item_index']; ?><option value="<?php echo (int)$item['id']; ?>" data-search="<?php echo htmlspecialchars(mb_strtolower($label),ENT_QUOTES,'UTF-8'); ?>" <?php echo (int)$f['item_id']===(int)$item['id']?'selected':''; ?>><?php echo htmlspecialchars($label,ENT_QUOTES,'UTF-8'); ?></option><?php } ?></select><span class="help-block">La ruleta referencia el producto de Arsenal; al reclamar se genera un ítem real con serial nuevo.</span></div>
</div>
<hr><div class="row"><div class="col-sm-6"><div class="form-group"><label>Máximo global / día</label><input type="number" min="0" class="form-control" name="daily_global_limit" value="<?php echo (int)$f['daily_global_limit']; ?>"><span class="help-block">0 = ilimitado.</span></div></div><div class="col-sm-6"><div class="form-group"><label>Máximo por cuenta / día</label><input type="number" min="0" class="form-control" name="daily_account_limit" value="<?php echo (int)$f['daily_account_limit']; ?>"><span class="help-block">0 = ilimitado.</span></div></div></div>
<div class="checkbox"><label><input type="checkbox" name="active" value="1" <?php echo !empty($f['active'])?'checked':''; ?>> Premio activo</label></div>
<button class="btn btn-success" type="submit" name="save_prize" value="1"><i class="fa fa-save"></i> Guardar premio</button>
<?php if((int)$f['id']>0){ ?><a class="btn btn-default" href="<?php echo admincp_base('nexoraroulette&page=prizes'); ?>">Cancelar edición</a><?php } ?>
</form>
</div></div></div>
<div class="col-lg-7">
<div class="panel panel-default"><div class="panel-heading"><strong>Pool configurado</strong></div><div class="table-responsive"><table class="table table-striped table-hover" style="margin:0"><thead><tr><th>Premio</th><th>Tipo</th><th>Rareza</th><th>Peso</th><th>Prob. base</th><th>Límites</th><th>Estado</th><th></th></tr></thead><tbody>
<?php if(!$prizes){ ?><tr><td colspan="8" class="text-muted">Aún no hay premios configurados.</td></tr><?php } ?>
<?php foreach($prizes as $p){ ?><tr><td><strong><?php echo htmlspecialchars($p['name'],ENT_QUOTES,'UTF-8'); ?></strong><br><small>#<?php echo (int)$p['id']; ?></small></td><td><?php echo htmlspecialchars($types[$p['prize_type']]??$p['prize_type'],ENT_QUOTES,'UTF-8'); ?></td><td><?php echo htmlspecialchars($rarities[$p['rarity']]??$p['rarity'],ENT_QUOTES,'UTF-8'); ?></td><td><?php echo number_format((int)$p['weight']); ?></td><td><?php echo isset($probById[(int)$p['id']])?number_format($probById[(int)$p['id']],2).'%':'—'; ?></td><td><small>Global: <?php echo (int)$p['daily_global_limit']?:'∞'; ?><br>Cuenta: <?php echo (int)$p['daily_account_limit']?:'∞'; ?></small></td><td><?php echo (int)$p['active']===1?'<span class="label label-success">Activo</span>':'<span class="label label-default">Retirado</span>'; ?></td><td style="white-space:nowrap"><a class="btn btn-xs btn-primary" href="<?php echo admincp_base('nexoraroulette&page=prizes&edit='.(int)$p['id']); ?>">Editar</a> <?php if((int)$p['active']===1){ ?><form method="post" style="display:inline"><button class="btn btn-xs btn-danger" name="retire_id" value="<?php echo (int)$p['id']; ?>" onclick="return confirm('¿Retirar este premio del pool? El historial se conserva.');">Retirar</button></form><?php } ?></td></tr><?php } ?>
</tbody></table></div></div></div>
</div>
<script>
(function(){
var type=document.getElementById('roulettePrizeType'),credits=document.getElementById('rouletteCreditsFields'),amount=document.getElementById('rouletteAmountFields'),items=document.getElementById('rouletteItemFields');
function sync(){var v=type.value;credits.style.display=v==='credits'?'block':'none';amount.style.display=(v==='credits'||v==='free_spins'||v==='fragments')?'block':'none';items.style.display=v==='itemshop'?'block':'none';} type.addEventListener('change',sync);sync();
var filter=document.getElementById('rouletteItemFilter'),select=document.getElementById('rouletteItemSelect');if(filter&&select)filter.addEventListener('input',function(){var q=this.value.toLowerCase().trim();Array.prototype.forEach.call(select.options,function(o,i){if(i===0)return;o.hidden=q!=='' && (o.getAttribute('data-search')||'').indexOf(q)===-1;});});
})();
</script>
