<?php
use Plugin\ItemShop\ItemShop;
$shop = new ItemShop();
if(!$shop->schemaReady()) { message('warning', 'Primero instala las tablas desde Arsenal Nexora → Configuración.'); return; }
$opsReady = $shop->catalogOpsSchemaReady();
$selectedIdsPost = trim((string)($_POST['selected_ids'] ?? ''));
$bulkEditPreview = null;

if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['toggle_item'])) {
    try {
        $shop->setItemActive((int)($_POST['item_id'] ?? 0), (int)($_POST['active'] ?? -1));
        message('success', 'Estado del ítem actualizado.');
    } catch(Throwable $e) { message('error', htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')); }
}
if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['bulk_visibility'])) {
    try {
        $action = (string)($_POST['bulk_action'] ?? '');
        if(!in_array($action, array('publish','hide'), true)) throw new InvalidArgumentException('Selecciona una acción masiva válida.');
        $active = $action === 'publish' ? 1 : 0;
        $affected = $shop->setItemsActive((string)($_POST['selected_ids'] ?? ''), $active);
        message('success', number_format($affected).' configuración'.($affected === 1 ? '' : 'es').' '.($active ? 'publicada'.($affected === 1 ? '' : 's') : 'ocultada'.($affected === 1 ? '' : 's')).'.');
    } catch(Throwable $e) { message('error', htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')); }
}
if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['publish_all_hidden'])) {
    try {
        $affected = $shop->setAllItemsActive(1);
        message('success', $affected > 0 ? number_format($affected).' configuración'.($affected === 1 ? '' : 'es').' publicada'.($affected === 1 ? '' : 's').' en '.$shop->getRealmLabel().'.' : 'No había configuraciones ocultas pendientes de publicación.');
    } catch(Throwable $e) { message('error', htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')); }
}
if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['preview_bulk_edit'])) {
    try { $bulkEditPreview = $shop->previewBulkEdit($selectedIdsPost, $_POST); }
    catch(Throwable $e) { message('error', htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')); }
}
if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['apply_bulk_edit'])) {
    try {
        $result = $shop->bulkEditItems($selectedIdsPost, $_POST);
        $affected = (int)($result['affected'] ?? 0);
        message('success', $affected > 0 ? number_format($affected).' configuración'.($affected === 1 ? '' : 'es').' actualizada'.($affected === 1 ? '' : 's').'. Snapshot #'.(int)($result['history_id'] ?? 0).' disponible en Operaciones.' : 'La selección ya tenía esos valores; no fue necesario modificarla.');
        $selectedIdsPost = '';
    } catch(Throwable $e) { message('error', htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')); }
}
if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['delete_item'])) {
    try {
        $result = $shop->deleteItem((int)($_POST['item_id'] ?? 0));
        $history = (int)($result['orders_preserved'] ?? 0);
        $message = 'Ítem eliminado del catálogo.';
        if($history > 0) $message .= ' Se conservaron '.number_format($history).' entrega'.($history === 1 ? '' : 's').' histórica'.($history === 1 ? '' : 's').'.';
        message('success', $message);
    } catch(Throwable $e) { message('error', htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')); }
}
$items = $shop->getAdminItems();
$categories = array();
foreach($items as $row) {
    $category = trim((string)($row['category'] ?? ''));
    if($category !== '') $categories[$category] = true;
}
$categories = array_keys($categories);
natcasesort($categories);
$publishedCount = 0;
$hiddenCount = 0;
foreach($items as $row) {
    if(!empty($row['active'])) $publishedCount++;
    else $hiddenCount++;
}
?>
<link rel="stylesheet" href="<?php echo htmlspecialchars(__PATH_ADMINCP_HOME__, ENT_QUOTES, 'UTF-8'); ?>css/itemshop-admin.css?v=170">
<div id="itemshop-admin-catalog" data-selected-ids="<?php echo htmlspecialchars($selectedIdsPost, ENT_QUOTES, 'UTF-8'); ?>">
    <h1 class="page-header">Catálogo · <?php echo htmlspecialchars($shop->getRealmLabel(), ENT_QUOTES, 'UTF-8'); ?></h1>
    <div class="itemshop-admin-toolbar">
        <a class="btn btn-success" href="index.php?module=itemshop&amp;page=form">Nuevo ítem</a>
        <a class="btn btn-primary" href="index.php?module=itemshop&amp;page=bulk">Carga masiva</a>
        <a class="btn btn-default" href="index.php?module=itemshop&amp;page=collections">Colecciones</a>
        <a class="btn btn-default" href="index.php?module=itemshop&amp;page=campaigns">Campañas</a>
        <a class="btn btn-default" href="index.php?module=itemshop&amp;page=operations">Operaciones / Readiness</a>
        <a class="btn btn-default" href="index.php?module=itemshop&amp;page=analytics">Analytics</a>
        <a class="btn btn-default" href="<?php echo htmlspecialchars(__BASE_URL__, ENT_QUOTES, 'UTF-8'); ?>shop/" target="_blank" rel="noopener">Abrir Arsenal público ↗</a>
    </div>

    <div class="itemshop-catalog-controls">
        <div class="form-group">
            <label for="itemshop-catalog-search">Buscar</label>
            <input id="itemshop-catalog-search" class="form-control" type="search" placeholder="Nombre, categoría o código 12:36" autocomplete="off">
        </div>
        <div class="form-group">
            <label for="itemshop-catalog-category">Categoría</label>
            <select id="itemshop-catalog-category" class="form-control">
                <option value="">Todas</option>
                <?php foreach($categories as $category) { ?><option value="<?php echo htmlspecialchars($category, ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($category, ENT_QUOTES, 'UTF-8'); ?></option><?php } ?>
            </select>
        </div>
        <div class="form-group">
            <label for="itemshop-catalog-state">Estado</label>
            <select id="itemshop-catalog-state" class="form-control">
                <option value="">Todos</option>
                <option value="published">Publicados</option>
                <option value="hidden">Ocultos</option>
                <option value="soldout">Agotados</option>
            </select>
        </div>
        <div id="itemshop-catalog-count" class="itemshop-catalog-count"><?php echo count($items); ?> ítems</div>
    </div>

    <div class="itemshop-catalog-bulkbar">
        <div class="itemshop-catalog-bulkbar__status">
            <strong><?php echo number_format($publishedCount); ?> publicados</strong>
            <span><?php echo number_format($hiddenCount); ?> ocultos · acciones limitadas a <?php echo htmlspecialchars($shop->getRealmLabel(), ENT_QUOTES, 'UTF-8'); ?></span>
        </div>
        <form method="post" id="itemshop-catalog-bulk-form" class="itemshop-catalog-bulk-form">
            <input id="itemshop-catalog-selected-input" data-itemshop-selected-input type="hidden" name="selected_ids" value="<?php echo htmlspecialchars($selectedIdsPost, ENT_QUOTES, 'UTF-8'); ?>">
            <button id="itemshop-catalog-select-visible" class="btn btn-default btn-sm" type="button">Seleccionar visibles</button>
            <button id="itemshop-catalog-clear-selection" class="btn btn-default btn-sm" type="button">Limpiar</button>
            <span class="itemshop-catalog-selected-count"><strong id="itemshop-catalog-selected-count">0</strong> seleccionados</span>
            <select class="form-control input-sm" name="bulk_action" aria-label="Acción masiva">
                <option value="publish">Publicar seleccionados</option>
                <option value="hide">Ocultar seleccionados</option>
            </select>
            <button class="btn btn-primary btn-sm" type="submit" name="bulk_visibility" value="1">Aplicar</button>
        </form>
        <?php if($hiddenCount > 0) { ?>
            <form method="post" class="itemshop-catalog-publish-all" onsubmit="return confirm('Publicar las <?php echo (int)$hiddenCount; ?> configuraciones ocultas de <?php echo htmlspecialchars($shop->getRealmLabel(), ENT_QUOTES, 'UTF-8'); ?>?\n\nSe marcarán como publicados inmediatamente. Los ítems con stock 0 seguirán agotados. El otro reino no será modificado.');">
                <button class="btn btn-success btn-sm" type="submit" name="publish_all_hidden" value="1">Publicar todos los ocultos · <?php echo number_format($hiddenCount); ?></button>
            </form>
        <?php } ?>
    </div>

    <div class="panel panel-default itemshop-admin-panel itemshop-bulk-edit-panel">
        <div class="panel-heading"><strong>Edición masiva</strong><span>Selecciona filas arriba, define solo los campos que quieras cambiar y revisa el impacto antes de aplicar.</span></div>
        <div class="panel-body">
            <?php if(!$opsReady) { ?>
                <div class="alert alert-warning" style="margin-bottom:0">La edición masiva con rollback requiere <a href="index.php?module=itemshop&amp;page=settings">Instalar / validar tablas</a> una vez en este reino.</div>
            <?php } else { ?>
                <form method="post" id="itemshop-bulk-edit-form">
                    <input data-itemshop-selected-input type="hidden" name="selected_ids" value="<?php echo htmlspecialchars($selectedIdsPost, ENT_QUOTES, 'UTF-8'); ?>">
                    <div class="itemshop-bulk-edit-grid">
                        <label><span><input type="checkbox" name="edit_price_enabled" value="1"<?php echo !empty($_POST['edit_price_enabled'])?' checked':''; ?>> Precio</span><input class="form-control input-sm" type="number" min="1" name="edit_price_wc" value="<?php echo isset($_POST['edit_price_wc'])?(int)$_POST['edit_price_wc']:5000; ?>"></label>
                        <label><span><input type="checkbox" name="edit_stock_enabled" value="1"<?php echo !empty($_POST['edit_stock_enabled'])?' checked':''; ?>> Stock</span><input class="form-control input-sm" type="number" min="-1" name="edit_stock" value="<?php echo isset($_POST['edit_stock'])?(int)$_POST['edit_stock']:-1; ?>"></label>
                        <label><span><input type="checkbox" name="edit_limit_enabled" value="1"<?php echo !empty($_POST['edit_limit_enabled'])?' checked':''; ?>> Límite/cuenta</span><input class="form-control input-sm" type="number" min="0" name="edit_max_per_account" value="<?php echo isset($_POST['edit_max_per_account'])?(int)$_POST['edit_max_per_account']:0; ?>"></label>
                        <label><span><input type="checkbox" name="edit_category_enabled" value="1"<?php echo !empty($_POST['edit_category_enabled'])?' checked':''; ?>> Categoría</span><input class="form-control input-sm" type="text" maxlength="50" name="edit_category" value="<?php echo htmlspecialchars((string)($_POST['edit_category'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" placeholder="Ej. Socket Tier 1"></label>
                        <label><span><input type="checkbox" name="edit_order_enabled" value="1"<?php echo !empty($_POST['edit_order_enabled'])?' checked':''; ?>> Orden</span><input class="form-control input-sm" type="number" min="-100000" max="100000" name="edit_sort_order" value="<?php echo isset($_POST['edit_sort_order'])?(int)$_POST['edit_sort_order']:100; ?>"></label>
                        <label><span><input type="checkbox" name="edit_featured_enabled" value="1"<?php echo !empty($_POST['edit_featured_enabled'])?' checked':''; ?>> Destacado</span><select class="form-control input-sm" name="edit_featured"><option value="1"<?php echo (string)($_POST['edit_featured'] ?? '0')==='1'?' selected':''; ?>>Sí</option><option value="0"<?php echo (string)($_POST['edit_featured'] ?? '0')!=='1'?' selected':''; ?>>No</option></select></label>
                    </div>
                    <div class="itemshop-bulk-promo-row">
                        <label>Promoción
                            <select class="form-control input-sm" name="edit_promotion_mode" id="itemshop-bulk-edit-promotion-mode">
                                <option value="keep"<?php echo (string)($_POST['edit_promotion_mode'] ?? 'keep')==='keep'?' selected':''; ?>>No modificar</option>
                                <option value="clear"<?php echo (string)($_POST['edit_promotion_mode'] ?? '')==='clear'?' selected':''; ?>>Quitar promoción</option>
                                <option value="set"<?php echo (string)($_POST['edit_promotion_mode'] ?? '')==='set'?' selected':''; ?>>Establecer promoción</option>
                            </select>
                        </label>
                        <label>Precio promo<input class="form-control input-sm" type="number" min="1" name="edit_sale_price_wc" value="<?php echo isset($_POST['edit_sale_price_wc'])?(int)$_POST['edit_sale_price_wc']:4000; ?>"></label>
                        <label>Inicio<input class="form-control input-sm" type="datetime-local" name="edit_sale_start" value="<?php echo htmlspecialchars((string)($_POST['edit_sale_start'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"></label>
                        <label>Fin<input class="form-control input-sm" type="datetime-local" name="edit_sale_end" value="<?php echo htmlspecialchars((string)($_POST['edit_sale_end'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"></label>
                    </div>
                    <div class="itemshop-bulk-edit-footer">
                        <p><strong>Máximo 500 configuraciones por edición.</strong> No modifica Section:Index, opciones del ítem, artwork ni publicación. Cada aplicación crea un snapshot reversible.</p>
                        <button class="btn btn-primary" type="submit" name="preview_bulk_edit" value="1">Previsualizar cambios</button>
                    </div>
                </form>
            <?php } ?>
        </div>
    </div>

    <?php if(is_array($bulkEditPreview) && !empty($bulkEditPreview['rows'])) { ?>
        <?php $editReady=0; $editBlocked=0; $editUnchanged=0; foreach($bulkEditPreview['rows'] as $r){ if(($r['status']??'')==='ready')$editReady++; elseif(($r['status']??'')==='blocked')$editBlocked++; else $editUnchanged++; } ?>
        <div class="panel panel-default itemshop-admin-panel itemshop-bulk-edit-preview">
            <div class="panel-heading"><strong>Previsualización de edición</strong><span><?php echo number_format($editReady); ?> cambiarán · <?php echo number_format($editUnchanged); ?> sin cambios · <?php echo number_format($editBlocked); ?> bloqueados</span></div>
            <div class="panel-body">
                <div class="table-responsive"><table class="table table-striped table-bordered"><thead><tr><th>Estado</th><th>ID</th><th>Ítem</th><th>Cambios</th><th>Validación</th></tr></thead><tbody>
                <?php foreach(array_slice($bulkEditPreview['rows'],0,150) as $row) { ?>
                    <tr><td><span class="label label-<?php echo ($row['status']??'')==='ready'?'success':(($row['status']??'')==='blocked'?'danger':'default'); ?>"><?php echo ($row['status']??'')==='ready'?'Listo':(($row['status']??'')==='blocked'?'Bloqueado':'Sin cambios'); ?></span></td><td>#<?php echo (int)$row['id']; ?></td><td><strong><?php echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'); ?></strong><br><code><?php echo htmlspecialchars($row['code'], ENT_QUOTES, 'UTF-8'); ?></code></td><td><?php if(!empty($row['diff'])) { foreach($row['diff'] as $field=>$diff) { ?><div><code><?php echo htmlspecialchars($field, ENT_QUOTES, 'UTF-8'); ?></code>: <?php echo htmlspecialchars($diff['before']===null?'—':(string)$diff['before'], ENT_QUOTES, 'UTF-8'); ?> → <strong><?php echo htmlspecialchars($diff['after']===null?'—':(string)$diff['after'], ENT_QUOTES, 'UTF-8'); ?></strong></div><?php } } else echo '—'; ?></td><td><?php echo htmlspecialchars($row['message'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php } ?>
                </tbody></table></div>
                <?php if(count($bulkEditPreview['rows'])>150) { ?><p class="help-block">Se muestran las primeras 150 filas; la aplicación vuelve a validar el lote completo.</p><?php } ?>
                <?php if($editReady > 0 && $editBlocked === 0) { ?>
                    <form method="post" class="itemshop-bulk-edit-apply" onsubmit="return confirm('Aplicar esta edición masiva a <?php echo (int)$editReady; ?> configuraciones de <?php echo htmlspecialchars($shop->getRealmLabel(), ENT_QUOTES, 'UTF-8'); ?>?\n\nSe creará un snapshot de rollback antes de modificar los datos.');">
                        <input type="hidden" name="selected_ids" value="<?php echo htmlspecialchars($selectedIdsPost, ENT_QUOTES, 'UTF-8'); ?>">
                        <?php foreach(array('edit_price_enabled','edit_price_wc','edit_stock_enabled','edit_stock','edit_limit_enabled','edit_max_per_account','edit_category_enabled','edit_category','edit_order_enabled','edit_sort_order','edit_featured_enabled','edit_featured','edit_promotion_mode','edit_sale_price_wc','edit_sale_start','edit_sale_end') as $field) { if(isset($_POST[$field])) { ?><input type="hidden" name="<?php echo htmlspecialchars($field, ENT_QUOTES, 'UTF-8'); ?>" value="<?php echo htmlspecialchars((string)$_POST[$field], ENT_QUOTES, 'UTF-8'); ?>"><?php } } ?>
                        <button class="btn btn-success" type="submit" name="apply_bulk_edit" value="1">Aplicar <?php echo number_format($editReady); ?> cambios</button>
                    </form>
                <?php } elseif($editBlocked > 0) { ?><div class="alert alert-danger" style="margin-bottom:0"><strong>No se aplicará parcialmente.</strong> Corrige los bloqueos y vuelve a previsualizar.</div><?php } ?>
            </div>
        </div>
    <?php } ?>

    <div class="table-responsive">
        <table class="table table-striped table-bordered itemshop-catalog-table">
            <thead><tr><th class="itemshop-catalog-select-col">Sel.</th><th>ID</th><th>Ítem</th><th>Código</th><th>Valor</th><th>Disponibilidad</th><th>Estado</th><th>Acciones</th></tr></thead>
            <tbody>
            <?php if(count($items)<1) { ?><tr><td colspan="8">Todavía no hay ítems. Crea la primera configuración desde “Nuevo ítem”.</td></tr><?php } ?>
            <?php foreach($items as $item) {
                $isSoldOut = (int)$item['stock'] === 0;
                $visibility = !empty($item['active']) ? 'published' : 'hidden';
                $stockState = $isSoldOut ? 'soldout' : 'available';
                $searchText = trim((string)$item['name'].' '.(string)$item['category'].' '.(int)$item['item_section'].':'.(int)$item['item_index'].' '.(int)$item['id']);
                $currentPrice = $shop->currentPrice($item);
            ?>
                <tr data-itemshop-row
                    data-item-id="<?php echo (int)$item['id']; ?>"
                    data-search="<?php echo htmlspecialchars($searchText, ENT_QUOTES, 'UTF-8'); ?>"
                    data-category="<?php echo htmlspecialchars((string)$item['category'], ENT_QUOTES, 'UTF-8'); ?>"
                    data-visibility="<?php echo $visibility; ?>"
                    data-stock-state="<?php echo $stockState; ?>">
                    <td class="itemshop-catalog-select-cell"><input type="checkbox" data-itemshop-catalog-check data-id="<?php echo (int)$item['id']; ?>" aria-label="Seleccionar <?php echo htmlspecialchars($item['name'], ENT_QUOTES, 'UTF-8'); ?>"></td>
                    <td><?php echo (int)$item['id']; ?></td>
                    <td>
                        <strong><?php echo htmlspecialchars($item['name'], ENT_QUOTES, 'UTF-8'); ?></strong><br>
                        <small><?php echo htmlspecialchars($item['category'], ENT_QUOTES, 'UTF-8'); ?><?php echo !empty($item['featured'])?' · Destacado':''; ?></small>
                    </td>
                    <td><span class="itemshop-code-badge"><?php echo (int)$item['item_section']; ?>:<?php echo (int)$item['item_index']; ?></span><br><small>+<?php echo (int)$item['item_level']; ?> · <?php echo (int)$item['width']; ?>×<?php echo (int)$item['height']; ?></small></td>
                    <td>
                        <?php if($shop->isOnSale($item)) { ?>
                            <strong><?php echo number_format($currentPrice); ?> <?php echo htmlspecialchars($shop->currencyLabel(), ENT_QUOTES, 'UTF-8'); ?></strong><br>
                            <small><s><?php echo number_format((int)$item['price_wc']); ?></s> · -<?php echo $shop->discountPercent($item); ?>%</small>
                        <?php } else { ?>
                            <strong><?php echo number_format((int)$item['price_wc']); ?> <?php echo htmlspecialchars($shop->currencyLabel(), ENT_QUOTES, 'UTF-8'); ?></strong>
                        <?php } ?>
                    </td>
                    <td>
                        <?php if((int)$item['stock'] < 0) { ?>Ilimitado<?php } elseif($isSoldOut) { ?><span class="text-danger itemshop-stock-low">Agotado</span><?php } else { echo number_format((int)$item['stock']); } ?>
                        <?php if((int)$item['max_per_account'] > 0) { ?><br><small>Límite: <?php echo number_format((int)$item['max_per_account']); ?>/cuenta</small><?php } ?>
                    </td>
                    <td class="itemshop-state-stack">
                        <span class="label label-<?php echo !empty($item['active'])?'success':'default'; ?>"><?php echo !empty($item['active'])?'Publicado':'Oculto'; ?></span>
                        <?php if($isSoldOut) { ?><span class="label label-danger">Sin stock</span><?php } ?>
                        <?php if(!empty($item['featured'])) { ?><span class="label label-info">Destacado</span><?php } ?>
                    </td>
                    <td style="white-space:nowrap">
                        <a class="btn btn-primary btn-xs" href="index.php?module=itemshop&amp;page=form&amp;id=<?php echo (int)$item['id']; ?>">Editar</a>
                        <a class="btn btn-default btn-xs" href="index.php?module=itemshop&amp;page=form&amp;clone=<?php echo (int)$item['id']; ?>">Duplicar</a>
                        <form method="post" style="display:inline">
                            <input type="hidden" name="item_id" value="<?php echo (int)$item['id']; ?>">
                            <input type="hidden" name="active" value="<?php echo !empty($item['active'])?0:1; ?>">
                            <button class="btn btn-<?php echo !empty($item['active'])?'warning':'success'; ?> btn-xs" type="submit" name="toggle_item" value="1"><?php echo !empty($item['active'])?'Ocultar':'Publicar'; ?></button>
                        </form>
                        <form method="post" style="display:inline" onsubmit="return confirm('Eliminar esta configuración de Arsenal de forma permanente?\n\nLas entregas históricas se conservarán. Esta acción no se puede deshacer.');">
                            <input type="hidden" name="item_id" value="<?php echo (int)$item['id']; ?>">
                            <button class="btn btn-danger btn-xs" type="submit" name="delete_item" value="1">Eliminar</button>
                        </form>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</div>
<script src="<?php echo htmlspecialchars(__PATH_ADMINCP_HOME__, ENT_QUOTES, 'UTF-8'); ?>js/itemshop-admin.js?v=170"></script>
