<?php
use Plugin\ItemShop\ItemShop;

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

$shop = new ItemShop();
if(!$shop->schemaReady()) { message('warning', 'Primero instala las tablas desde Arsenal Nexora → Configuración.'); return; }
if(!$shop->campaignSchemaReady()) {
    message('warning', 'Colecciones y Campañas requieren Arsenal 1.7.0. Ve a Configuración y pulsa Instalar / validar tablas en este reino.');
    return;
}

if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if(isset($_POST['save_collection'])) {
            $id = $shop->saveCollection($_POST);
            $count = $shop->setCollectionItems($id, (string)($_POST['selected_ids'] ?? ''));
            message('success', 'Colección guardada con '.number_format($count).' configuración'.($count===1?'':'es').' en '.$shop->getRealmLabel().'.');
            $_GET['id'] = $id;
        } elseif(isset($_POST['delete_collection'])) {
            $shop->deleteCollection((int)($_POST['collection_id'] ?? 0));
            message('success', 'Colección eliminada. El catálogo y las campañas históricas no fueron borrados.');
            unset($_GET['id']);
        }
    } catch(Throwable $e) { message('error', itemshopCollectionsEsc($e->getMessage())); }
}

$editId = isset($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT)!==false ? (int)$_GET['id'] : 0;
$editing = $editId > 0 ? $shop->getCollection($editId) : null;
$selected = $editing ? array_flip($shop->getCollectionItemIds($editId)) : array();
$collections = $shop->getCollections();
$items = $shop->getAdminItems();
$categories = array();
foreach($items as $item) {
    $category=trim((string)($item['category']??''));
    if($category!=='') $categories[$category]=true;
}
$categories=array_keys($categories); natcasesort($categories);
?>
<link rel="stylesheet" href="<?php echo itemshopCollectionsEsc(__PATH_ADMINCP_HOME__); ?>css/itemshop-admin.css?v=170">
<div id="itemshop-admin-collections">
    <h1 class="page-header">Colecciones · <?php echo itemshopCollectionsEsc($shop->getRealmLabel()); ?></h1>
    <div class="itemshop-admin-toolbar">
        <a href="index.php?module=itemshop&amp;page=items">← Catálogo</a>
        <a href="index.php?module=itemshop&amp;page=campaigns">Campañas</a>
        <a href="index.php?module=itemshop&amp;page=operations">Operaciones</a>
        <a href="index.php?module=itemshop&amp;page=settings">Configuración</a>
    </div>

    <div class="alert alert-info"><strong>Colecciones no cambian productos.</strong> Son agrupaciones administrativas reutilizables. Una misma configuración puede pertenecer a varias colecciones y cada reino mantiene las suyas.</div>

    <div class="row">
        <div class="col-lg-4">
            <div class="panel panel-default itemshop-admin-panel">
                <div class="panel-heading"><strong>Colecciones del reino</strong><span><?php echo number_format(count($collections)); ?> definidas</span></div>
                <div class="panel-body">
                    <a class="btn btn-success btn-sm" href="index.php?module=itemshop&amp;page=collections" style="margin-bottom:12px">Nueva colección</a>
                    <?php if(!$collections) { ?><p class="text-muted">Todavía no hay colecciones.</p><?php } ?>
                    <div class="itemshop-collection-list">
                    <?php foreach($collections as $collection) { ?>
                        <div class="itemshop-collection-card<?php echo $editId===(int)$collection['id']?' is-active':''; ?>">
                            <div>
                                <strong><?php echo itemshopCollectionsEsc($collection['name']); ?></strong>
                                <span><?php echo number_format((int)$collection['item_count']); ?> ítems<?php if((int)$collection['live_campaigns']>0) echo ' · '.number_format((int)$collection['live_campaigns']).' campaña activa/programada'; ?></span>
                            </div>
                            <a class="btn btn-default btn-xs" href="index.php?module=itemshop&amp;page=collections&amp;id=<?php echo (int)$collection['id']; ?>">Editar</a>
                        </div>
                    <?php } ?>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-8">
            <form method="post" id="itemshop-collection-form">
                <input type="hidden" name="collection_id" value="<?php echo $editing?(int)$editing['id']:0; ?>">
                <input type="hidden" name="selected_ids" id="itemshop-collection-selected" value="<?php echo itemshopCollectionsEsc(implode(',',array_keys($selected))); ?>">
                <div class="panel panel-default itemshop-admin-panel">
                    <div class="panel-heading"><strong><?php echo $editing?'Editar colección':'Nueva colección'; ?></strong><span>La selección se guarda en <?php echo itemshopCollectionsEsc($shop->getRealmLabel()); ?></span></div>
                    <div class="panel-body">
                        <div class="form-group"><label>Nombre</label><input class="form-control" name="name" maxlength="100" required value="<?php echo itemshopCollectionsEsc($editing['name']??''); ?>" placeholder="Ej. Socket Weapons"></div>
                        <div class="form-group"><label>Descripción</label><textarea class="form-control" name="description" maxlength="300" rows="2" placeholder="Uso interno de la colección"><?php echo itemshopCollectionsEsc($editing['description']??''); ?></textarea></div>

                        <div class="itemshop-collection-picker-toolbar">
                            <div class="form-group"><label>Buscar catálogo</label><input id="itemshop-collection-search" class="form-control" type="search" placeholder="Nombre, categoría o código 0:50"></div>
                            <div class="form-group"><label>Categoría</label><select id="itemshop-collection-category" class="form-control"><option value="">Todas</option><?php foreach($categories as $category) { ?><option value="<?php echo itemshopCollectionsEsc($category); ?>"><?php echo itemshopCollectionsEsc($category); ?></option><?php } ?></select></div>
                            <div class="itemshop-collection-picker-actions"><button class="btn btn-default btn-sm" type="button" id="itemshop-collection-select-visible">Seleccionar visibles</button><button class="btn btn-default btn-sm" type="button" id="itemshop-collection-clear">Limpiar</button><strong><span id="itemshop-collection-count">0</span> seleccionados</strong></div>
                        </div>

                        <div class="table-responsive itemshop-collection-picker">
                            <table class="table table-striped table-bordered table-condensed">
                                <thead><tr><th style="width:36px"></th><th>Ítem</th><th>Código</th><th>Categoría</th><th>Estado</th></tr></thead>
                                <tbody>
                                <?php foreach($items as $item) {
                                    $id=(int)$item['id']; $code=(int)$item['item_section'].':'.(int)$item['item_index'];
                                    $searchText=mb_strtolower((string)$item['name'].' '.(string)$item['category'].' '.$code,'UTF-8');
                                ?>
                                    <tr data-collection-row data-search="<?php echo itemshopCollectionsEsc($searchText); ?>" data-category="<?php echo itemshopCollectionsEsc($item['category']); ?>">
                                        <td><input type="checkbox" data-collection-check value="<?php echo $id; ?>"<?php echo isset($selected[$id])?' checked':''; ?>></td>
                                        <td><strong><?php echo itemshopCollectionsEsc($item['name']); ?></strong></td>
                                        <td><code><?php echo itemshopCollectionsEsc($code); ?></code></td>
                                        <td><?php echo itemshopCollectionsEsc($item['category']); ?></td>
                                        <td><span class="label label-<?php echo !empty($item['active'])?'success':'default'; ?>"><?php echo !empty($item['active'])?'Publicado':'Oculto'; ?></span></td>
                                    </tr>
                                <?php } ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="itemshop-collection-form-actions">
                            <button class="btn btn-primary" type="submit" name="save_collection" value="1">Guardar colección</button>
                            <?php if($editing) { ?>
                                <button class="btn btn-danger pull-right" type="submit" name="delete_collection" value="1" onclick="return confirm('¿Eliminar la colección <?php echo itemshopCollectionsEsc(addslashes($editing['name'])); ?>?\n\nNo se eliminarán productos. No puede borrarse si participa en una campaña activa o programada.');">Eliminar colección</button>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
(function(){
    var rows=[].slice.call(document.querySelectorAll('[data-collection-row]'));
    var checks=[].slice.call(document.querySelectorAll('[data-collection-check]'));
    var search=document.getElementById('itemshop-collection-search');
    var category=document.getElementById('itemshop-collection-category');
    var hidden=document.getElementById('itemshop-collection-selected');
    var count=document.getElementById('itemshop-collection-count');
    function sync(){var ids=[]; checks.forEach(function(c){if(c.checked) ids.push(c.value);}); hidden.value=ids.join(','); count.textContent=ids.length;}
    function filter(){var q=(search.value||'').trim().toLowerCase(); var cat=category.value||''; rows.forEach(function(row){var ok=(!q || (row.getAttribute('data-search')||'').indexOf(q)!==-1) && (!cat || row.getAttribute('data-category')===cat); row.style.display=ok?'':'none';});}
    checks.forEach(function(c){c.addEventListener('change',sync);});
    search.addEventListener('input',filter); category.addEventListener('change',filter);
    document.getElementById('itemshop-collection-select-visible').addEventListener('click',function(){rows.forEach(function(row){if(row.style.display!=='none'){var c=row.querySelector('[data-collection-check]'); if(c)c.checked=true;}});sync();});
    document.getElementById('itemshop-collection-clear').addEventListener('click',function(){checks.forEach(function(c){c.checked=false;});sync();});
    sync(); filter();
})();
</script>
