<?php
use Plugin\ItemShop\ItemShop;

function itemshopBulkEsc($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function itemshopBulkStatusLabel($status) {
    $status = (string)$status;
    if($status === 'ready') return '<span class="label label-success">Listo</span>';
    if($status === 'created') return '<span class="label label-success">Creado</span>';
    if($status === 'existing') return '<span class="label label-default">Ya existe</span>';
    if($status === 'failed') return '<span class="label label-danger">Error</span>';
    return '<span class="label label-warning">Bloqueado</span>';
}

$shop = new ItemShop();
if(!$shop->schemaReady()) { message('warning', 'Primero instala las tablas desde Arsenal Nexora → Configuración.'); return; }
if(!$shop->smartOptionsSchemaReady() || !ItemShop::smartOptionsCatalogReady()) { message('warning', 'Arsenal necesita actualizar o regenerar el motor de opciones inteligentes. Ve a Configuración y pulsa Instalar / validar tablas.'); return; }
$opsReady = $shop->catalogOpsSchemaReady();

if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['delete_bulk_preset'])) {
    try { $shop->deleteBulkPreset((int)($_POST['preset_id'] ?? 0)); message('success', 'Preset eliminado.'); }
    catch(Throwable $e) { message('error', itemshopBulkEsc($e->getMessage())); }
}

$preset = isset($_POST['preset']) ? (string)$_POST['preset'] : 'full_excellent_0';
if(!in_array($preset, array('full_excellent_0','full_excellent_socket5_0','skill_luck_0','skill_luck_socket5_0'), true)) $preset = 'full_excellent_0';
$price = isset($_POST['price_wc']) ? (int)$_POST['price_wc'] : 5000;
$stock = isset($_POST['stock']) ? (int)$_POST['stock'] : -1;
$maxPerAccount = isset($_POST['max_per_account']) ? (int)$_POST['max_per_account'] : 0;
$sortOrder = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 100;
$categoryOverride = isset($_POST['category_override']) ? trim((string)$_POST['category_override']) : '';
$selectedRaw = isset($_POST['selected_codes']) ? trim((string)$_POST['selected_codes']) : '';
$previewRows = array();
$importResult = null;

$bulkOptions = array(
    'preset'=>$preset,
    'price_wc'=>$price,
    'stock'=>$stock,
    'max_per_account'=>$maxPerAccount,
    'sort_order'=>$sortOrder,
    'category_override'=>$categoryOverride,
);


if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['save_bulk_preset'])) {
    try {
        $shop->saveBulkPreset($_POST);
        message('success', 'Preset guardado para '.$shop->getRealmLabel().'.');
    } catch(Throwable $e) { message('error', itemshopBulkEsc($e->getMessage())); }
}

if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['preview_bulk'])) {
    try {
        $previewRows = $shop->previewBulkItems($selectedRaw, $bulkOptions);
    } catch(Throwable $e) {
        message('error', itemshopBulkEsc($e->getMessage()));
    }
}

if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['import_bulk'])) {
    try {
        $importResult = $shop->bulkCreateItems($selectedRaw, $bulkOptions);
        $created = count($importResult['created']);
        $existing = count($importResult['existing']);
        $blocked = count($importResult['blocked']);
        $failed = count($importResult['failed']);
        $summary = number_format($created).' configuración'.($created === 1 ? '' : 'es').' creada'.($created === 1 ? '' : 's').' en modo oculto.';
        if($existing > 0) $summary .= ' '.number_format($existing).' ya existente'.($existing === 1 ? '' : 's').' omitida'.($existing === 1 ? '' : 's').'.';
        if($blocked > 0) $summary .= ' '.number_format($blocked).' bloqueada'.($blocked === 1 ? '' : 's').' por validación técnica.';
        if($failed > 0) $summary .= ' '.number_format($failed).' con error de guardado.';
        message($failed > 0 ? 'warning' : 'success', $summary);

        $remaining = array();
        foreach(array_merge($importResult['blocked'], $importResult['failed']) as $row) if(!empty($row['code'])) $remaining[] = (string)$row['code'];
        $selectedRaw = implode(',', $remaining);
        if(count($remaining) > 0) $previewRows = array_merge($importResult['blocked'], $importResult['failed']);
    } catch(Throwable $e) {
        message('error', itemshopBulkEsc($e->getMessage()));
    }
}

$savedPresets = $opsReady ? $shop->getBulkPresets() : array();
$sectionLabels = ItemShop::itemSectionLabels();
$existingMap = $shop->getAdminCodeMap();
$smartCatalog = ItemShop::smartOptionsCatalog();
$bulkCatalog = array();
foreach(ItemShop::authoritativeAdminItems() as $catalogItem) {
    if(!is_array($catalogItem)) continue;
    $section = (int)$catalogItem['section'];
    $index = (int)$catalogItem['index'];
    $code = $section.':'.$index;
    $excellentType = (int)($catalogItem['excellent_type'] ?? 0);
    $profile = isset($smartCatalog['excellent_profiles'][(string)$excellentType]) && is_array($smartCatalog['excellent_profiles'][(string)$excellentType])
        ? $smartCatalog['excellent_profiles'][(string)$excellentType]
        : array('name'=>'Sin Excellent','options'=>array());
    $excellentMask = 0;
    $excellentCount = 0;
    foreach(($profile['options'] ?? array()) as $excellentRow) {
        if(!is_array($excellentRow) || !isset($excellentRow['bit'])) continue;
        $bit = ((int)$excellentRow['bit'] & 0x3F);
        if($bit < 1) continue;
        $excellentMask |= $bit;
        $excellentCount++;
    }
    $bulkCatalog[] = array(
        'code'=>$code,
        'section'=>$section,
        'index'=>$index,
        'name'=>(string)$catalogItem['name'],
        'section_label'=>(string)($sectionLabels[$section] ?? ('Section '.$section)),
        'category'=>ItemShop::suggestedCategory($section),
        'width'=>(int)$catalogItem['width'],
        'height'=>(int)$catalogItem['height'],
        'skill'=>(int)($catalogItem['skill'] ?? 0) > 0 ? 1 : 0,
        'luck'=>(int)($catalogItem['have_option'] ?? 0) > 0 ? 1 : 0,
        'excellent_type'=>$excellentType,
        'excellent_count'=>$excellentCount,
        'excellent_pending'=>$excellentType > 0 && $excellentCount < 1 ? 1 : 0,
        'socket'=>!empty($catalogItem['socket_capable']) ? 1 : 0,
        'level380'=>!empty($catalogItem['level380']) ? 1 : 0,
        'dimension_conflict'=>!empty($catalogItem['dimension_conflict']) ? 1 : 0,
        'compatible'=>!empty($catalogItem['encoder_compatible']) ? 1 : 0,
        'existing_id'=>isset($existingMap[$code]) ? (int)$existingMap[$code]['id'] : 0,
    );
}

$bulkJson = json_encode($bulkCatalog, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
if(!is_string($bulkJson)) $bulkJson = '[]';
$previewReady = 0;
$previewExisting = 0;
$previewBlocked = 0;
foreach($previewRows as $row) {
    if(($row['status'] ?? '') === 'ready') $previewReady++;
    elseif(($row['status'] ?? '') === 'existing') $previewExisting++;
    else $previewBlocked++;
}
?>
<link rel="stylesheet" href="<?php echo itemshopBulkEsc(__PATH_ADMINCP_HOME__); ?>css/itemshop-admin.css?v=170">
<div id="itemshop-admin-bulk" data-page-size="48" data-preset="<?php echo itemshopBulkEsc($preset); ?>" data-render-base="<?php echo itemshopBulkEsc(__PATH_TEMPLATE_IMG__.'itemshop-renders-v1/'); ?>">
    <h1 class="page-header">Carga masiva · <?php echo itemshopBulkEsc($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=form">Nuevo ítem individual</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>
        <a href="index.php?module=itemshop&amp;page=analytics">Analytics</a>
        <a href="<?php echo itemshopBulkEsc(__BASE_URL__); ?>shop/" target="_blank" rel="noopener">Abrir Arsenal público ↗</a>
    </div>

    <div class="alert alert-info itemshop-admin-principle">
        <strong>Selección técnica:</strong> marca los ítems directamente desde el catálogo del servidor. El lote reutiliza las mismas validaciones del editor individual y siempre se crea <strong>Oculto</strong> para que puedas revisar precio, artwork y publicación antes de exponerlo al jugador.
    </div>

    <?php if(!$opsReady) { ?>
        <div class="alert alert-warning"><strong>Presets personalizados pendientes:</strong> ve a Configuración y pulsa <strong>Instalar / validar tablas</strong> para habilitarlos. La carga masiva base continúa disponible.</div>
    <?php } elseif(count($savedPresets) > 0) { ?>
        <div class="itemshop-saved-presets-bar">
            <div><strong>Presets guardados · <?php echo itemshopBulkEsc($shop->getRealmLabel()); ?></strong><span>Se aplican al formulario; no importan nada por sí solos.</span></div>
            <div class="itemshop-saved-presets-list">
                <?php foreach($savedPresets as $savedPreset) { ?>
                    <form method="post" onsubmit="return confirm('Eliminar el preset <?php echo itemshopBulkEsc($savedPreset['name']); ?>?');">
                        <input type="hidden" name="preset_id" value="<?php echo (int)$savedPreset['id']; ?>">
                        <span><?php echo itemshopBulkEsc($savedPreset['name']); ?></span>
                        <button class="btn btn-link btn-xs" type="submit" name="delete_bulk_preset" value="1">Eliminar</button>
                    </form>
                <?php } ?>
            </div>
        </div>
    <?php } ?>

    <form method="post" id="itemshop-bulk-form">
        <input id="itemshop-bulk-selected-input" type="hidden" name="selected_codes" value="<?php echo itemshopBulkEsc($selectedRaw); ?>">
        <div class="row">
            <div class="col-lg-8">
                <div class="panel panel-default itemshop-admin-panel">
                    <div class="panel-heading"><strong>1 · Selecciona el inventario</strong><span><?php echo number_format(count($bulkCatalog)); ?> códigos técnicos disponibles.</span></div>
                    <div class="panel-body">
                        <div class="itemshop-bulk-controls">
                            <div class="form-group itemshop-bulk-search-wrap">
                                <label for="itemshop-bulk-search">Buscar</label>
                                <input id="itemshop-bulk-search" class="form-control" type="search" placeholder="Nombre o código, ej. HolyAngel o 0:350" autocomplete="off">
                            </div>
                            <div class="form-group">
                                <label for="itemshop-bulk-section">Section</label>
                                <select id="itemshop-bulk-section" class="form-control">
                                    <option value="">Todas</option>
                                    <?php foreach($sectionLabels as $section=>$label) { ?><option value="<?php echo (int)$section; ?>"><?php echo (int)$section; ?> · <?php echo itemshopBulkEsc($label); ?></option><?php } ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="itemshop-bulk-capability">Capacidad</label>
                                <select id="itemshop-bulk-capability" class="form-control">
                                    <option value="">Todas</option>
                                    <option value="excellent">Excellent validado</option>
                                    <option value="skill">Skill</option>
                                    <option value="luck">Luck</option>
                                    <option value="socket">Socket</option>
                                    <option value="380">Level 380</option>
                                </select>
                            </div>
                            <label class="itemshop-bulk-selected-only"><input id="itemshop-bulk-selected-only" type="checkbox"> Solo seleccionados</label>
                        </div>

                        <div class="itemshop-bulk-actions">
                            <div>
                                <button id="itemshop-bulk-select-visible" class="btn btn-default btn-sm" type="button">Seleccionar visibles</button>
                                <button id="itemshop-bulk-clear" class="btn btn-default btn-sm" type="button">Limpiar selección</button>
                            </div>
                            <div class="itemshop-bulk-counter"><strong id="itemshop-bulk-selected-count">0</strong> seleccionados · <span id="itemshop-bulk-visible-count">0</span> resultados</div>
                        </div>

                        <div id="itemshop-bulk-grid" class="itemshop-bulk-grid" aria-live="polite"></div>
                        <div class="itemshop-bulk-pagination">
                            <button id="itemshop-bulk-prev" class="btn btn-default btn-sm" type="button">← Anterior</button>
                            <span id="itemshop-bulk-page-label">Página 1</span>
                            <button id="itemshop-bulk-next" class="btn btn-default btn-sm" type="button">Siguiente →</button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="panel panel-default itemshop-admin-panel itemshop-sticky-panel itemshop-bulk-config">
                    <div class="panel-heading"><strong>2 · Configuración del lote</strong><span>Se aplica a todos los seleccionados.</span></div>
                    <div class="panel-body">
                        <?php if($opsReady && count($savedPresets) > 0) { ?>
                            <div class="form-group">
                                <label for="itemshop-bulk-saved-preset">Preset guardado</label>
                                <select id="itemshop-bulk-saved-preset" class="form-control">
                                    <option value="">— Aplicar uno guardado —</option>
                                    <?php foreach($savedPresets as $savedPreset) { ?>
                                        <option value="<?php echo (int)$savedPreset['id']; ?>"
                                            data-preset-key="<?php echo itemshopBulkEsc($savedPreset['preset_key']); ?>"
                                            data-price="<?php echo (int)$savedPreset['price_wc']; ?>"
                                            data-stock="<?php echo (int)$savedPreset['stock']; ?>"
                                            data-limit="<?php echo (int)$savedPreset['max_per_account']; ?>"
                                            data-order="<?php echo (int)$savedPreset['sort_order']; ?>"
                                            data-category="<?php echo itemshopBulkEsc($savedPreset['category_override'] ?? ''); ?>"><?php echo itemshopBulkEsc($savedPreset['name']); ?></option>
                                    <?php } ?>
                                </select>
                                <p class="help-block">Carga configuración técnica + precio + disponibilidad + categoría opcional.</p>
                            </div>
                        <?php } ?>

                        <div class="form-group">
                            <label for="itemshop-bulk-preset">Preset</label>
                            <select id="itemshop-bulk-preset" class="form-control" name="preset">
                                <option value="full_excellent_0"<?php echo $preset === 'full_excellent_0' ? ' selected' : ''; ?>>Full Excellent +0 · Skill/Luck auto</option>
                                <option value="full_excellent_socket5_0"<?php echo $preset === 'full_excellent_socket5_0' ? ' selected' : ''; ?>>Full Excellent +0 · 5 Sockets si corresponde</option>
                                <option value="skill_luck_0"<?php echo $preset === 'skill_luck_0' ? ' selected' : ''; ?>>+0 · Skill/Luck auto · sin Excellent</option>
                                <option value="skill_luck_socket5_0"<?php echo $preset === 'skill_luck_socket5_0' ? ' selected' : ''; ?>>+0 · 5 Sockets si corresponde · sin Excellent</option>
                            </select>
                            <p class="help-block">Los presets Socket abren cinco slots vacíos (Free Slot) únicamente cuando Items.xml declara el ítem como compatible. Full Excellent activa todos los bits del perfil técnico validado; alas/Fenrir con mapa Excellent especial pendiente continúan protegidos.</p>
                        </div>

                        <div class="itemshop-bulk-preset-summary">
                            <span>Nivel</span><strong>+0</strong>
                            <span>Skill</span><strong>Automático</strong>
                            <span>Luck</span><strong>Automático</strong>
                            <span>Additional</span><strong>+0</strong>
                            <span>Ancient / Harmony</span><strong>Ninguno</strong>
                            <span>Socket</span><strong id="itemshop-bulk-preset-socket"><?php echo in_array($preset, array('full_excellent_socket5_0','skill_luck_socket5_0'), true) ? '5 slots si corresponde' : 'Ninguno'; ?></strong>
                            <span>380</span><strong>Ninguno</strong>
                            <span>Estado</span><strong>Oculto</strong>
                        </div>

                        <hr>
                        <div class="form-group"><label>Precio normal</label><div class="input-group"><input class="form-control" type="number" min="1" name="price_wc" required value="<?php echo (int)$price; ?>"><span class="input-group-addon"><?php echo itemshopBulkEsc($shop->currencyLabel()); ?></span></div></div>
                        <div class="form-group"><label>Stock</label><input class="form-control" type="number" min="-1" name="stock" required value="<?php echo (int)$stock; ?>"><p class="help-block">-1 = ilimitado · 0 = agotado.</p></div>
                        <div class="form-group"><label>Límite histórico por cuenta</label><input class="form-control" type="number" min="0" name="max_per_account" required value="<?php echo (int)$maxPerAccount; ?>"><p class="help-block">0 = sin límite histórico.</p></div>
                        <div class="form-group"><label>Orden inicial</label><input class="form-control" type="number" min="-100000" max="100000" name="sort_order" required value="<?php echo (int)$sortOrder; ?>"></div>
                        <div class="form-group"><label>Categoría forzada <small>(opcional)</small></label><input class="form-control" type="text" maxlength="50" name="category_override" value="<?php echo itemshopBulkEsc($categoryOverride); ?>" placeholder="Vacío = categoría automática por Section"><p class="help-block">Útil para colecciones comerciales; si queda vacío Arsenal conserva la categoría técnica automática.</p></div>

                        <?php if($opsReady) { ?>
                            <div class="itemshop-preset-save-box">
                                <label>Guardar esta configuración como preset</label>
                                <div class="input-group">
                                    <input class="form-control" type="text" maxlength="80" name="preset_name" placeholder="Ej. Seasonal · Full EXC Socket">
                                    <span class="input-group-btn"><button class="btn btn-default" type="submit" name="save_bulk_preset" value="1">Guardar preset</button></span>
                                </div>
                                <small>El preset guarda configuración del lote, no la selección de ítems.</small>
                            </div>
                        <?php } ?>

                        <div class="alert alert-warning itemshop-bulk-safety-note">
                            <strong>Protección del catálogo</strong><br>
                            Los códigos ya existentes se omiten. No se crean promociones, destacados ni publicaciones automáticas.
                        </div>
                        <button id="itemshop-bulk-preview-button" class="btn btn-primary btn-lg btn-block" type="submit" name="preview_bulk" value="1">Revisar lote seleccionado</button>
                    </div>
                </div>
            </div>
        </div>

        <?php if(count($previewRows) > 0) { ?>
            <div class="panel panel-default itemshop-admin-panel itemshop-bulk-preview-panel" id="itemshop-bulk-preview">
                <div class="panel-heading">
                    <strong>3 · Previsualización del lote</strong>
                    <span><?php echo number_format($previewReady); ?> listos · <?php echo number_format($previewExisting); ?> existentes · <?php echo number_format($previewBlocked); ?> bloqueados</span>
                </div>
                <div class="panel-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered itemshop-bulk-preview-table">
                            <thead><tr><th>Estado</th><th>Código</th><th>Ítem</th><th>Categoría</th><th>Preset aplicado</th><th>Validación</th></tr></thead>
                            <tbody>
                            <?php foreach($previewRows as $row) { ?>
                                <tr>
                                    <td><?php echo itemshopBulkStatusLabel($row['status'] ?? 'blocked'); ?></td>
                                    <td><code><?php echo itemshopBulkEsc($row['code'] ?? ''); ?></code></td>
                                    <td><strong><?php echo itemshopBulkEsc($row['name'] ?? ''); ?></strong><br><small><?php echo (int)($row['width'] ?? 0); ?>×<?php echo (int)($row['height'] ?? 0); ?></small></td>
                                    <td><?php echo itemshopBulkEsc($row['category'] ?? ''); ?></td>
                                    <td>
                                        +0
                                        <?php if(!empty($row['skill'])) { ?> · Skill<?php } ?>
                                        <?php if(!empty($row['luck'])) { ?> · Luck<?php } ?>
                                        <?php if((int)($row['excellent_count'] ?? 0) > 0) { ?> · Excellent <?php echo (int)$row['excellent_count']; ?>/6<?php } ?>
                                        <?php if((int)($row['socket_count'] ?? 0) > 0) { ?> · Socket <?php echo (int)$row['socket_count']; ?>/5<?php } ?>
                                    </td>
                                    <td><small><?php echo itemshopBulkEsc($row['message'] ?? ''); ?></small></td>
                                </tr>
                            <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <?php if($previewReady > 0) { ?>
                        <div class="itemshop-bulk-import-bar">
                            <div><strong><?php echo number_format($previewReady); ?> configuraciones listas.</strong><span>Se crearán ocultas en <?php echo itemshopBulkEsc($shop->getRealmLabel()); ?>.</span></div>
                            <button class="btn btn-success btn-lg" type="submit" name="import_bulk" value="1" onclick="return confirm('Crear <?php echo (int)$previewReady; ?> configuraciones ocultas en Arsenal?\n\nLos códigos existentes se omitirán y cada ítem volverá a validarse antes de guardar.');">Importar <?php echo number_format($previewReady); ?> configuraciones</button>
                        </div>
                    <?php } ?>
                </div>
            </div>
        <?php } ?>
    </form>

    <script id="itemshop-bulk-data" type="application/json"><?php echo $bulkJson; ?></script>
</div>
<script src="<?php echo itemshopBulkEsc(__PATH_ADMINCP_HOME__); ?>js/itemshop-admin.js?v=170"></script>
