<?php
use Plugin\ItemShop\ItemShop;

function itemshopLogsEsc($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }

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

if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if(isset($_POST['mark_test_orders'])) {
            $result = $shop->setOrdersTestMode($_POST['order_ids'] ?? array(), true);
            $affected = (int)($result['affected'] ?? 0);
            message('success', $affected > 0
                ? number_format($affected).' entrega'.($affected === 1 ? '' : 's').' marcada'.($affected === 1 ? '' : 's').' como datos de prueba. Ya no cuentan en Analytics ni en el límite histórico por cuenta.'
                : 'Las entregas seleccionadas ya estaban marcadas como prueba o no podían cambiarse.');
        } elseif(isset($_POST['restore_test_orders'])) {
            $result = $shop->setOrdersTestMode($_POST['order_ids'] ?? array(), false);
            $affected = (int)($result['affected'] ?? 0);
            message('success', $affected > 0
                ? number_format($affected).' entrega'.($affected === 1 ? '' : 's').' restaurada'.($affected === 1 ? '' : 's').' como compra real.'
                : 'Las entregas seleccionadas ya estaban como compras reales o no podían restaurarse.');
        }
    } catch(Throwable $e) { message('error', itemshopLogsEsc($e->getMessage())); }
}

$account = trim((string)($_GET['account'] ?? ''));
$status = (string)($_GET['status'] ?? 'all');
if(!in_array($status,array('all','real','test'),true)) $status='all';
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 300;
$limit = max(50,min(1000,$limit));
try {
    $orders = $shop->getOrders($limit,array('account'=>$account,'status'=>$status));
} catch(Throwable $e) {
    message('error', itemshopLogsEsc($e->getMessage()));
    $account='';
    $orders=$shop->getOrders($limit,array('status'=>$status));
}
$realCount=0; $testCount=0; $visibleValue=0;
foreach($orders as $row) {
    if((string)($row['status'] ?? '') === 'delivered_test') $testCount++;
    elseif((string)($row['status'] ?? '') === 'delivered') $realCount++;
    $visibleValue += (int)($row['price_paid'] ?? 0);
}
?>
<link rel="stylesheet" href="<?php echo itemshopLogsEsc(__PATH_ADMINCP_HOME__); ?>css/itemshop-admin.css?v=170">
<h1 class="page-header">Entregas / Datos de prueba · <?php echo itemshopLogsEsc($shop->getRealmLabel()); ?></h1>
<p>El historial de entrega se conserva. Las compras marcadas como prueba quedan fuera de Analytics y dejan de consumir el límite histórico <code>max_per_account</code>.</p>
<div class="itemshop-admin-toolbar">
    <a href="index.php?module=itemshop&amp;page=analytics">← Analytics</a>
    <a href="index.php?module=itemshop&amp;page=support">Soporte</a>
    <a href="index.php?module=itemshop&amp;page=items">Catálogo</a>
    <a href="index.php?module=itemshop&amp;page=collections">Colecciones</a>
    <a href="index.php?module=itemshop&amp;page=campaigns">Campañas</a>
    <a href="index.php?module=itemshop&amp;page=operations">Operaciones</a>
</div>

<div class="alert alert-warning">
    <strong>Esta limpieza no revierte la compra física.</strong>
    No devuelve WCoinC, no elimina el ítem del Warehouse, no restaura stock y no reutiliza seriales. Solo reclasifica el registro administrativo entre <code>delivered</code> y <code>delivered_test</code>.
</div>

<form method="get" class="form-inline" style="margin-bottom:12px">
    <input type="hidden" name="module" value="itemshop">
    <input type="hidden" name="page" value="logs">
    <div class="form-group" style="margin-right:6px">
        <label for="itemshop-log-account">Cuenta exacta</label>
        <input id="itemshop-log-account" class="form-control input-sm" type="text" name="account" maxlength="50" value="<?php echo itemshopLogsEsc($account); ?>" placeholder="Cuenta de prueba">
    </div>
    <div class="form-group" style="margin-right:6px">
        <label for="itemshop-log-status">Estado</label>
        <select id="itemshop-log-status" class="form-control input-sm" name="status">
            <option value="all"<?php echo $status==='all'?' selected':''; ?>>Todos</option>
            <option value="real"<?php echo $status==='real'?' selected':''; ?>>Compras reales</option>
            <option value="test"<?php echo $status==='test'?' selected':''; ?>>Datos de prueba</option>
        </select>
    </div>
    <div class="form-group" style="margin-right:6px">
        <label for="itemshop-log-limit">Mostrar</label>
        <select id="itemshop-log-limit" class="form-control input-sm" name="limit">
            <?php foreach(array(50,100,300,500,1000) as $opt) { ?><option value="<?php echo $opt; ?>"<?php echo $limit===$opt?' selected':''; ?>><?php echo $opt; ?></option><?php } ?>
        </select>
    </div>
    <button class="btn btn-primary btn-sm" type="submit">Filtrar</button>
    <a class="btn btn-default btn-sm" href="index.php?module=itemshop&amp;page=logs">Limpiar filtro</a>
</form>

<div class="row" style="margin-bottom:12px">
    <div class="col-sm-4"><div class="well well-sm" style="margin-bottom:0"><strong><?php echo number_format(count($orders)); ?></strong><br><small>registros visibles</small></div></div>
    <div class="col-sm-4"><div class="well well-sm" style="margin-bottom:0"><strong><?php echo number_format($realCount); ?></strong> reales · <strong><?php echo number_format($testCount); ?></strong> prueba<br><small>según filtro actual</small></div></div>
    <div class="col-sm-4"><div class="well well-sm" style="margin-bottom:0"><strong><?php echo number_format($visibleValue); ?></strong><br><small>valor histórico visible, todas las monedas mezcladas</small></div></div>
</div>

<form method="post" id="itemshop-testdata-form">
    <div style="margin-bottom:8px">
        <button class="btn btn-default btn-sm" type="button" id="itemshop-orders-select-all">Seleccionar visibles</button>
        <button class="btn btn-default btn-sm" type="button" id="itemshop-orders-clear">Limpiar selección</button>
        <button class="btn btn-warning btn-sm" type="submit" name="mark_test_orders" value="1" onclick="return confirm('Estas entregas dejarán de contar en Analytics y en max_per_account. El WCoinC y los ítems entregados NO se revertirán. ¿Continuar?');">Marcar como prueba</button>
        <button class="btn btn-success btn-sm" type="submit" name="restore_test_orders" value="1" onclick="return confirm('Las entregas seleccionadas volverán a contar como compras reales en Analytics y max_per_account. ¿Continuar?');">Restaurar como compra real</button>
        <span id="itemshop-orders-selected" style="margin-left:8px;color:#777">0 seleccionadas</span>
    </div>
    <div class="table-responsive">
        <table class="table table-striped table-bordered">
            <thead><tr><th style="width:28px"><input type="checkbox" id="itemshop-orders-master" aria-label="Seleccionar todas"></th><th>ID</th><th>Fecha UTC</th><th>Cuenta</th><th>Ítem</th><th>Precio</th><th>Slot</th><th>Serial</th><th>Estado</th></tr></thead>
            <tbody>
            <?php if(count($orders)<1) { ?><tr><td colspan="9">No hay entregas para este filtro.</td></tr><?php } ?>
            <?php foreach($orders as $row) {
                $isTest=(string)($row['status'] ?? '')==='delivered_test';
            ?>
                <tr>
                    <td><input class="itemshop-order-check" type="checkbox" name="order_ids[]" value="<?php echo (int)$row['id']; ?>" aria-label="Seleccionar entrega <?php echo (int)$row['id']; ?>"></td>
                    <td><a href="index.php?module=itemshop&amp;page=support&amp;view=<?php echo (int)$row['id']; ?>">#<?php echo (int)$row['id']; ?></a></td>
                    <td><?php echo itemshopLogsEsc($row['created_at']); ?></td>
                    <td><?php echo itemshopLogsEsc($row['account_username']); ?></td>
                    <td><?php echo itemshopLogsEsc($row['item_name']); ?></td>
                    <td><?php echo number_format((int)$row['price_paid']).' '.itemshopLogsEsc($row['currency']); ?></td>
                    <td><?php echo (int)$row['warehouse_slot']; ?></td>
                    <td><?php echo itemshopLogsEsc($row['item_serial']); ?></td>
                    <td><?php if($isTest) { ?><span class="label label-warning">Prueba</span><br><small>delivered_test</small><?php } else { ?><span class="label label-success">Real</span><br><small><?php echo itemshopLogsEsc($row['status']); ?></small><?php } ?></td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</form>
<script>
(function(){
    var checks=Array.prototype.slice.call(document.querySelectorAll('.itemshop-order-check'));
    var master=document.getElementById('itemshop-orders-master');
    var count=document.getElementById('itemshop-orders-selected');
    function update(){
        var selected=checks.filter(function(c){return c.checked;}).length;
        if(count) count.textContent=selected+' seleccionada'+(selected===1?'':'s');
        if(master) master.checked=checks.length>0 && selected===checks.length;
    }
    checks.forEach(function(c){c.addEventListener('change',update);});
    if(master) master.addEventListener('change',function(){checks.forEach(function(c){c.checked=master.checked;});update();});
    var all=document.getElementById('itemshop-orders-select-all');
    if(all) all.addEventListener('click',function(){checks.forEach(function(c){c.checked=true;});update();});
    var clear=document.getElementById('itemshop-orders-clear');
    if(clear) clear.addEventListener('click',function(){checks.forEach(function(c){c.checked=false;});update();});
    update();
})();
</script>
