<?php
use Plugin\ItemShop\ItemShop;

function itemshopSupportEsc($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function itemshopSupportCurrency($value) {
    $map=array('WCOINC'=>'WCoinC','WCOINP'=>'WCoinP','GOBLINPOINT'=>'Goblin Points');
    $key=strtoupper(trim((string)$value));
    return $map[$key] ?? $key;
}
function itemshopSupportStatus($value) {
    $value=(string)$value;
    if($value==='delivered') return array('success','Entregado','Compra real');
    if($value==='delivered_test') return array('warning','Prueba','Datos de prueba');
    return array('default',$value,$value);
}
function itemshopSupportDate($value) {
    if(empty($value)) return '—';
    try {
        $date=new DateTimeImmutable((string)$value,new DateTimeZone('UTC'));
        return $date->setTimezone(new DateTimeZone(date_default_timezone_get()))->format('Y-m-d H:i:s T');
    } catch(Throwable $e) { return (string)$value; }
}
function itemshopSupportTraits($snapshot) {
    if(!is_array($snapshot)) return array();
    $traits=array();
    $level=(int)($snapshot['item_level'] ?? 0);
    $traits[]='Nivel +'.$level;
    if(!empty($snapshot['has_skill'])) $traits[]='Skill';
    if(!empty($snapshot['has_luck'])) $traits[]='Luck';
    $option=(int)($snapshot['option_level'] ?? 0);
    if($option>0) $traits[]='Adicional +'.($option*4);
    $excellent=(int)($snapshot['excellent_mask'] ?? 0) & 0x3F;
    if($excellent>0) $traits[]='Excellent 0x'.strtoupper(str_pad(dechex($excellent),2,'0',STR_PAD_LEFT)).' · '.substr_count(decbin($excellent),'1').' bit(s)';
    $ancient=(int)($snapshot['ancient_option'] ?? 0);
    if($ancient>0) $traits[]='Ancient raw '.$ancient;
    $harmony=(int)($snapshot['harmony_option'] ?? 0);
    if($harmony>0) $traits[]='Harmony raw '.$harmony;
    $socketCount=(int)($snapshot['socket_count'] ?? 0);
    if($socketCount>0) $traits[]='Socket '.$socketCount.'/5';
    if(!empty($snapshot['option_380'])) $traits[]='Opción 380';
    return $traits;
}

$shop=new ItemShop();
if(!$shop->schemaReady()) { message('warning','Primero instala las tablas desde Configuración.'); return; }

$filters=array(
    'order_id'=>trim((string)($_GET['order_id'] ?? '')),
    'account'=>trim((string)($_GET['account'] ?? '')),
    'serial'=>trim((string)($_GET['serial'] ?? '')),
    'item'=>trim((string)($_GET['item'] ?? '')),
    'status'=>(string)($_GET['status'] ?? 'all'),
);
if(!in_array($filters['status'],array('all','real','test'),true)) $filters['status']='all';
$limit=max(50,min(500,(int)($_GET['limit'] ?? 100)));
$orders=array();
try { $orders=$shop->searchSupportOrders($filters,$limit); }
catch(Throwable $e) { message('error',itemshopSupportEsc($e->getMessage())); }

$detail=null; $snapshot=array(); $currentItem=null;
$view=trim((string)($_GET['view'] ?? ''));
if($view!=='') {
    try {
        if(filter_var($view,FILTER_VALIDATE_INT)===false || (int)$view<1) throw new InvalidArgumentException('Order ID de detalle inválido.');
        $detail=$shop->getSupportOrder((int)$view);
        if(!is_array($detail)) throw new RuntimeException('La entrega solicitada no existe en este reino.');
        $snapshot=$shop->decodeOrderSnapshot($detail['item_snapshot'] ?? '');
        $currentItem=$shop->getItem((int)($detail['item_id'] ?? 0));
    } catch(Throwable $e) { message('error',itemshopSupportEsc($e->getMessage())); $detail=null; }
}
?>
<link rel="stylesheet" href="<?php echo itemshopSupportEsc(__PATH_ADMINCP_HOME__); ?>css/itemshop-admin.css?v=171">
<h1 class="page-header">Soporte Arsenal · <?php echo itemshopSupportEsc($shop->getRealmLabel()); ?></h1>
<p>Consola de trazabilidad de solo lectura. Busca entregas históricas sin modificar WCoin, stock, Warehouse, seriales ni estados.</p>
<div class="itemshop-admin-toolbar">
    <a href="index.php?module=itemshop&amp;page=logs">Entregas</a>
    <a href="index.php?module=itemshop&amp;page=analytics">Analytics</a>
    <a href="index.php?module=itemshop&amp;page=items">Catálogo</a>
    <a href="index.php?module=itemshop&amp;page=operations">Operaciones</a>
</div>

<div class="alert alert-info">
    <strong>Frontera de soporte:</strong> esta pantalla diagnostica una entrega ya registrada. No reentrega objetos, no devuelve moneda y no elimina historial. Para reclasificar compras QA usa <a href="index.php?module=itemshop&amp;page=logs&amp;status=test">Datos de prueba</a>.
</div>

<form method="get" class="itemshop-support-filter">
    <input type="hidden" name="module" value="itemshop">
    <input type="hidden" name="page" value="support">
    <div class="row">
        <div class="col-md-2"><div class="form-group"><label>Order ID</label><input class="form-control input-sm" name="order_id" value="<?php echo itemshopSupportEsc($filters['order_id']); ?>" placeholder="1452"></div></div>
        <div class="col-md-2"><div class="form-group"><label>Cuenta exacta</label><input class="form-control input-sm" name="account" maxlength="50" value="<?php echo itemshopSupportEsc($filters['account']); ?>" placeholder="account"></div></div>
        <div class="col-md-2"><div class="form-group"><label>Serial exacto</label><input class="form-control input-sm" name="serial" maxlength="19" value="<?php echo itemshopSupportEsc($filters['serial']); ?>" placeholder="35719"></div></div>
        <div class="col-md-2"><div class="form-group"><label>Producto contiene</label><input class="form-control input-sm" name="item" maxlength="100" value="<?php echo itemshopSupportEsc($filters['item']); ?>" placeholder="Sonic Blade"></div></div>
        <div class="col-md-2"><div class="form-group"><label>Estado</label><select class="form-control input-sm" name="status"><option value="all"<?php echo $filters['status']==='all'?' selected':''; ?>>Todos</option><option value="real"<?php echo $filters['status']==='real'?' selected':''; ?>>Compras reales</option><option value="test"<?php echo $filters['status']==='test'?' selected':''; ?>>Datos de prueba</option></select></div></div>
        <div class="col-md-2"><div class="form-group"><label>Máximo</label><select class="form-control input-sm" name="limit"><?php foreach(array(50,100,200,500) as $n) { ?><option value="<?php echo $n; ?>"<?php echo $limit===$n?' selected':''; ?>><?php echo $n; ?></option><?php } ?></select></div></div>
    </div>
    <button class="btn btn-primary btn-sm" type="submit">Buscar entregas</button>
    <a class="btn btn-default btn-sm" href="index.php?module=itemshop&amp;page=support">Limpiar</a>
</form>

<?php if(is_array($detail)) {
    $statusInfo=itemshopSupportStatus($detail['status'] ?? '');
    $traits=itemshopSupportTraits($snapshot);
    $code=isset($snapshot['item_section'],$snapshot['item_index']) ? ((int)$snapshot['item_section'].':'.(int)$snapshot['item_index']) : '—';
    $normalPrice=(int)($snapshot['price_wc'] ?? 0);
    $salePrice=isset($snapshot['sale_price_wc']) && $snapshot['sale_price_wc']!==null ? (int)$snapshot['sale_price_wc'] : 0;
?>
<section class="itemshop-support-detail">
    <div class="itemshop-support-detail__head">
        <div><small>ORDEN HISTÓRICA</small><h2>#<?php echo (int)$detail['id']; ?> · <?php echo itemshopSupportEsc($detail['item_name']); ?></h2></div>
        <span class="label label-<?php echo itemshopSupportEsc($statusInfo[0]); ?>"><?php echo itemshopSupportEsc($statusInfo[1]); ?></span>
    </div>
    <div class="row">
        <div class="col-md-4"><div class="well well-sm"><strong>Cuenta</strong><br><?php echo itemshopSupportEsc($detail['account_username']); ?><br><small>User ID <?php echo (int)$detail['user_id']; ?></small></div></div>
        <div class="col-md-4"><div class="well well-sm"><strong>Precio pagado</strong><br><?php echo number_format((int)$detail['price_paid']).' '.itemshopSupportEsc(itemshopSupportCurrency($detail['currency'])); ?><br><small>Precio normal snapshot: <?php echo number_format($normalPrice); ?><?php echo $salePrice>0?' · promo snapshot '.number_format($salePrice):''; ?></small></div></div>
        <div class="col-md-4"><div class="well well-sm"><strong>Fecha</strong><br><?php echo itemshopSupportEsc(itemshopSupportDate($detail['created_at'])); ?><br><small><?php echo itemshopSupportEsc($shop->getRealmLabel()); ?></small></div></div>
    </div>
    <table class="table table-bordered table-condensed">
        <tr><th style="width:220px">Section:Index</th><td><code><?php echo itemshopSupportEsc($code); ?></code></td></tr>
        <tr><th>Item ID histórico</th><td><?php echo (int)$detail['item_id']; ?> <?php if(is_array($currentItem)) { ?><a class="btn btn-xs btn-default" href="index.php?module=itemshop&amp;page=form&amp;id=<?php echo (int)$detail['item_id']; ?>">Abrir configuración actual</a><?php } else { ?><span class="label label-default">Configuración ya no existe</span><?php } ?></td></tr>
        <tr><th>Warehouse slot</th><td><?php echo (int)$detail['warehouse_slot']; ?></td></tr>
        <tr><th>Serial entregado</th><td><code><?php echo itemshopSupportEsc($detail['item_serial']); ?></code></td></tr>
        <tr><th>Estado administrativo</th><td><?php echo itemshopSupportEsc($statusInfo[2]); ?> · <code><?php echo itemshopSupportEsc($detail['status']); ?></code></td></tr>
        <tr><th>Configuración congelada</th><td><?php if(count($traits)>0) { foreach($traits as $trait) { ?><span class="label label-info itemshop-support-trait"><?php echo itemshopSupportEsc($trait); ?></span><?php } } else { ?>Sin rasgos decodificables.<?php } ?></td></tr>
    </table>
    <details class="itemshop-support-snapshot"><summary>Ver snapshot JSON histórico</summary><pre><?php echo itemshopSupportEsc(json_encode($snapshot,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)); ?></pre></details>
    <p><a class="btn btn-default btn-sm" href="index.php?module=itemshop&amp;page=logs&amp;account=<?php echo rawurlencode((string)$detail['account_username']); ?>">Ver historial de esta cuenta</a></p>
</section>
<?php } ?>

<h3>Resultados <small><?php echo number_format(count($orders)); ?> visibles</small></h3>
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
    <thead><tr><th>Orden</th><th>Fecha</th><th>Cuenta</th><th>Producto</th><th>Precio</th><th>Slot</th><th>Serial</th><th>Estado</th><th></th></tr></thead>
    <tbody>
    <?php if(count($orders)<1) { ?><tr><td colspan="9">No hay entregas para estos filtros.</td></tr><?php } ?>
    <?php foreach($orders as $row) { $st=itemshopSupportStatus($row['status'] ?? ''); ?>
        <tr>
            <td>#<?php echo (int)$row['id']; ?></td>
            <td><?php echo itemshopSupportEsc(itemshopSupportDate($row['created_at'])); ?></td>
            <td><?php echo itemshopSupportEsc($row['account_username']); ?></td>
            <td><?php echo itemshopSupportEsc($row['item_name']); ?><br><small>Item ID <?php echo (int)$row['item_id']; ?></small></td>
            <td><?php echo number_format((int)$row['price_paid']).' '.itemshopSupportEsc(itemshopSupportCurrency($row['currency'])); ?></td>
            <td><?php echo (int)$row['warehouse_slot']; ?></td>
            <td><code><?php echo itemshopSupportEsc($row['item_serial']); ?></code></td>
            <td><span class="label label-<?php echo itemshopSupportEsc($st[0]); ?>"><?php echo itemshopSupportEsc($st[1]); ?></span></td>
            <td><a class="btn btn-xs btn-primary" href="index.php?module=itemshop&amp;page=support&amp;view=<?php echo (int)$row['id']; ?>">Ver ficha</a></td>
        </tr>
    <?php } ?>
    </tbody>
</table>
</div>
