<?php
use Plugin\ItemShop\ItemShop;

function itemshopAdminEsc($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function itemshopAdminChecked($value) { return !empty($value) ? ' checked' : ''; }

$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; }

$sectionLabels = ItemShop::itemSectionLabels();
$categories = array_values(array_unique(array_merge(
    array('Armas','Equipamiento','Alas y orbes','Accesorios','Consumibles','Especiales','Destacados'),
    $shop->getAdminCategories()
)));
$identityHints = $shop->getAdminIdentityHints();
$authoritativeItems = ItemShop::authoritativeAdminItems();

$defaults = array(
    'id'=>0,'name'=>'','category'=>'Destacados','description'=>'','item_section'=>0,'item_index'=>0,'item_level'=>0,
    'has_skill'=>0,'has_luck'=>0,'option_level'=>0,'excellent_mask'=>0,'ancient_option'=>0,'harmony_option'=>0,
    'socket_count'=>0,'option_380'=>0,'socket_bonus'=>0,'socket_option_1'=>255,'socket_option_2'=>255,'socket_option_3'=>255,'socket_option_4'=>255,'socket_option_5'=>255,
    'durability'=>255,'width'=>1,'height'=>1,'price_wc'=>1,'sale_price_wc'=>'',
    'sale_start'=>'','sale_end'=>'','stock'=>-1,'max_per_account'=>0,'active'=>0,'featured'=>0,'sort_order'=>100,'image_file'=>'',
);

$id = isset($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0;
$cloneId = ($id < 1 && isset($_GET['clone'])) ? (int)$_GET['clone'] : 0;
$cloneSource = null;
if($id > 0) {
    $item = $shop->getItem($id);
} elseif($cloneId > 0) {
    $cloneSource = $shop->getItem($cloneId);
    $item = $cloneSource;
} else {
    $item = $defaults;
}
if(!is_array($item)) { message('error', 'El ítem solicitado no existe.'); return; }
$item = array_merge($defaults, $item);

if(is_array($cloneSource)) {
    $item['id'] = 0;
    $item['name'] = mb_substr(trim((string)$item['name']).' · copia', 0, 100);
    $item['active'] = 0;
    $item['featured'] = 0;
    $item['image_file'] = '';
    $item['sort_order'] = min(100000, (int)$item['sort_order'] + 10);
    message('info', 'Copia preparada desde el ítem #'.$cloneId.'. Queda oculta hasta que decidas publicarla y no duplica la imagen promocional.');
}

if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['save_item'])) {
    try {
        $mask = 0;
        if(isset($_POST['excellent_options']) && is_array($_POST['excellent_options'])) {
            foreach($_POST['excellent_options'] as $bit) {
                $bit = (int)$bit;
                if(in_array($bit, array(1,2,4,8,16,32), true)) $mask |= $bit;
            }
        }
        $_POST['excellent_mask'] = $mask;
        $_POST['id'] = $id;
        $savedId = $shop->saveItem($_POST, isset($_FILES['image']) ? $_FILES['image'] : null);
        message('success', $id > 0 ? 'Ítem actualizado y validado.' : 'Ítem creado. Revisa su estado antes de publicarlo.');
        $id = $savedId;
        $item = array_merge($defaults, $shop->getItem($savedId));
        $cloneId = 0;
    } catch(Throwable $e) {
        message('error', itemshopAdminEsc($e->getMessage()));
        $item = array_merge($item, $_POST);
        foreach(array('has_skill','has_luck','active','featured','option_380') as $checkboxKey) $item[$checkboxKey] = !empty($_POST[$checkboxKey]) ? 1 : 0;
        $item['excellent_mask'] = isset($_POST['excellent_mask']) ? (int)$_POST['excellent_mask'] : 0;
    }
}

$authoritativeCurrent = ItemShop::authoritativeItem((int)$item['item_section'], (int)$item['item_index']);
$smartCatalog = ItemShop::smartOptionsCatalog();
$smartCurrent = ItemShop::smartOptionsForItem((int)$item['item_section'], (int)$item['item_index']);
$excellentProfile = isset($smartCurrent['excellent_profile']) && is_array($smartCurrent['excellent_profile']) ? $smartCurrent['excellent_profile'] : array('name'=>'Sin Excellent','options'=>array());
$excellentLabels = array();
foreach(($excellentProfile['options'] ?? array()) as $excellentRow) if(is_array($excellentRow) && isset($excellentRow['bit'])) $excellentLabels[(int)$excellentRow['bit']] = (string)($excellentRow['name'] ?? ('Opción '.(int)$excellentRow['bit']));
$currentAncientOptions = array(0=>'Ninguno');
if(isset($smartCurrent['ancient']['a']) && is_array($smartCurrent['ancient']['a'])) {
    $ancientName = (string)($smartCurrent['ancient']['a']['name'] ?? 'Ancient A');
    $currentAncientOptions[5] = $ancientName.' · variante A · +5';
    $currentAncientOptions[9] = $ancientName.' · variante A · +10';
}
if(isset($smartCurrent['ancient']['b']) && is_array($smartCurrent['ancient']['b'])) {
    $ancientName = (string)($smartCurrent['ancient']['b']['name'] ?? 'Ancient B');
    $currentAncientOptions[6] = $ancientName.' · variante B · +5';
    $currentAncientOptions[10] = $ancientName.' · variante B · +10';
}
$currentHarmonyOptions = array(0=>'Ninguno');
foreach(($smartCurrent['harmony'] ?? array()) as $harmonyGroup) {
    if(!is_array($harmonyGroup) || empty($harmonyGroup['levels']) || !is_array($harmonyGroup['levels'])) continue;
    foreach($harmonyGroup['levels'] as $harmonyLevel) {
        if(!is_array($harmonyLevel) || !isset($harmonyLevel['raw'])) continue;
        $raw = (int)$harmonyLevel['raw'];
        $currentHarmonyOptions[$raw] = (string)($harmonyLevel['name'] ?? (($harmonyGroup['name'] ?? 'Harmony').' · nivel '.($harmonyLevel['level'] ?? 0)));
    }
}
$currentSocketOptions = array(255=>'Sin slot',254=>'Slot vacío');
foreach(($smartCurrent['socket_options'] ?? array()) as $socketRow) {
    if(!is_array($socketRow) || !isset($socketRow['index'])) continue;
    $socketIndex = (int)$socketRow['index'];
    if($socketIndex === 254 || $socketIndex === 255) continue;
    $currentSocketOptions[$socketIndex] = (string)($socketRow['name'] ?? ('Socket #'.$socketIndex));
}
$currentSocketBonuses = array(0=>'Ninguno');
foreach(($smartCurrent['socket_bonuses'] ?? array()) as $socketRow) {
    if(!is_array($socketRow) || !isset($socketRow['index'])) continue;
    $socketBonusIndex = (int)$socketRow['index'];
    if($socketBonusIndex === 50) continue;
    $currentSocketBonuses[$socketBonusIndex] = (string)($socketRow['name'] ?? ('Bonus #'.$socketBonusIndex));
}
$saleStart = $shop->localDateValue($item['sale_start']);
$saleEnd = $shop->localDateValue($item['sale_end']);
$assetInfo = $shop->itemAssetInfo((int)$item['item_section'], (int)$item['item_index']);
$initialImage = is_array($assetInfo) ? (string)$assetInfo['url'] : '';
$customImage = '';
if(!empty($item['image_file'])) {
    $promoFile = basename((string)$item['image_file']);
    $promoPath = __PATH_TEMPLATE_ROOT__.'img/itemshop/'.$promoFile;
    if(is_file($promoPath)) $customImage = __PATH_TEMPLATE_IMG__.'itemshop/'.rawurlencode($promoFile);
}
$hintJson = json_encode($identityHints, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT);
$sectionJson = json_encode($sectionLabels, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT);
$smartJson = json_encode($smartCatalog, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
?>
<link rel="stylesheet" href="<?php echo itemshopAdminEsc(__PATH_ADMINCP_HOME__); ?>css/itemshop-admin.css?v=168">
<div id="itemshop-admin-form"
     data-image-base="<?php echo itemshopAdminEsc(__PATH_TEMPLATE_IMG__.'item_images/'); ?>"
     data-is-new="<?php echo $id < 1 ? '1' : '0'; ?>"
     data-currency="<?php echo itemshopAdminEsc($shop->currencyLabel()); ?>">

    <h1 class="page-header"><?php echo $id > 0 ? 'Editar ítem' : 'Nuevo ítem'; ?> · <?php echo itemshopAdminEsc($shop->getRealmLabel()); ?></h1>
    <div class="itemshop-admin-toolbar">
        <a href="index.php?module=itemshop&amp;page=items">← Catálogo</a>
        <?php if($id > 0) { ?><a href="index.php?module=itemshop&amp;page=form&amp;clone=<?php echo (int)$id; ?>">Duplicar configuración</a><?php } ?>
        <a href="<?php echo itemshopAdminEsc(__BASE_URL__); ?>shop/" target="_blank" rel="noopener">Abrir Arsenal público ↗</a>
    </div>

    <div class="alert alert-info itemshop-admin-principle">
        <strong>Flujo seguro:</strong> identifica el código del ítem, valida el asset y sus medidas, configura sus opciones y publica al final. El formulario no modifica la lógica de entrega del baúl.
    </div>

    <form method="post" enctype="multipart/form-data" id="itemshop-item-form">
        <input type="hidden" name="id" value="<?php echo (int)$id; ?>">

        <div class="row">
            <div class="col-md-8">
                <div class="panel panel-default itemshop-admin-panel">
                    <div class="panel-heading"><strong>1 · Identidad del ítem</strong><span>El código real manda; la interfaz solo te ayuda a verificarlo.</span></div>
                    <div class="panel-body">
                        <div class="itemshop-authoritative-picker">
                            <label for="itemshop-authoritative-search">Catálogo oficial del servidor</label>
                            <input id="itemshop-authoritative-search" class="form-control" list="itemshop-authoritative-list" autocomplete="off" placeholder="Busca por nombre o código, ej. 0:10 · Light Saber">
                            <datalist id="itemshop-authoritative-list">
                                <?php foreach($authoritativeItems as $catalogItem) { ?>
                                    <option value="<?php echo itemshopAdminEsc((int)$catalogItem['section'].':'.(int)$catalogItem['index'].' · '.$catalogItem['name']); ?>"
                                            data-section="<?php echo (int)$catalogItem['section']; ?>"
                                            data-index="<?php echo (int)$catalogItem['index']; ?>"
                                            data-name="<?php echo itemshopAdminEsc($catalogItem['name']); ?>"
                                            data-width="<?php echo (int)$catalogItem['width']; ?>"
                                            data-height="<?php echo (int)$catalogItem['height']; ?>"
                                            data-compatible="<?php echo !empty($catalogItem['encoder_compatible']) ? '1' : '0'; ?>"
                                            data-dimension-conflict="<?php echo !empty($catalogItem['dimension_conflict']) ? '1' : '0'; ?>"
                                            data-txt-width="<?php echo $catalogItem['txt_width'] === null ? '' : (int)$catalogItem['txt_width']; ?>"
                                            data-txt-height="<?php echo $catalogItem['txt_height'] === null ? '' : (int)$catalogItem['txt_height']; ?>"
                                            data-excellent-type="<?php echo (int)$catalogItem['excellent_type']; ?>"
                                            data-socket-capable="<?php echo !empty($catalogItem['socket_capable']) ? '1' : '0'; ?>"
                                            data-level380="<?php echo !empty($catalogItem['level380']) ? '1' : '0'; ?>"
                                            data-skill="<?php echo (int)$catalogItem['skill']; ?>"
                                            data-have-option="<?php echo (int)$catalogItem['have_option']; ?>"></option>
                                <?php } ?>
                            </datalist>
                            <div id="itemshop-authoritative-status" class="itemshop-authoritative-status <?php echo is_array($authoritativeCurrent) ? (empty($authoritativeCurrent['encoder_compatible']) ? 'is-blocked' : (!empty($authoritativeCurrent['dimension_conflict']) ? 'is-warning' : 'is-valid')) : 'is-neutral'; ?>">
                                <?php if(is_array($authoritativeCurrent)) { ?>
                                    <strong><?php echo itemshopAdminEsc($authoritativeCurrent['name']); ?></strong> · Warehouse Editor: <?php echo (int)$authoritativeCurrent['width']; ?>×<?php echo (int)$authoritativeCurrent['height']; ?> casillas<?php if(!empty($authoritativeCurrent['dimension_conflict'])) { ?> · Item.txt difiere: <?php echo (int)$authoritativeCurrent['txt_width']; ?>×<?php echo (int)$authoritativeCurrent['txt_height']; ?>; Arsenal usa la huella del editor<?php } ?><?php echo empty($authoritativeCurrent['encoder_compatible']) ? ' · Index fuera del rango DbVersion 3 confirmado' : ''; ?>.
                                <?php } else { ?>
                                    Busca un ítem para aplicar nombre, Section, Index y dimensiones desde el catálogo técnico. El formato DbVersion 3 confirmado permite Index 0–511.
                                <?php } ?>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-sm-7">
                                <div class="form-group">
                                    <label for="itemshop-name">Nombre visible</label>
                                    <input id="itemshop-name" class="form-control" name="name" maxlength="100" required value="<?php echo itemshopAdminEsc($item['name']); ?>" autocomplete="off">
                                    <p class="help-block">Nombre mostrado al jugador. Al seleccionar desde el catálogo técnico se completa con el nombre real; puedes ajustar solo la presentación si lo necesitas.</p>
                                </div>
                                <div class="row">
                                    <div class="col-xs-7">
                                        <div class="form-group">
                                            <label for="itemshop-section">Section</label>
                                            <select id="itemshop-section" class="form-control" name="item_section" required>
                                                <?php foreach($sectionLabels as $section=>$label) { ?>
                                                    <option value="<?php echo (int)$section; ?>"<?php echo (int)$item['item_section']===(int)$section?' selected':''; ?>><?php echo (int)$section; ?> · <?php echo itemshopAdminEsc($label); ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-xs-5">
                                        <div class="form-group">
                                            <label for="itemshop-index">Index</label>
                                            <input id="itemshop-index" class="form-control" type="number" min="0" max="511" name="item_index" required value="<?php echo (int)$item['item_index']; ?>">
                                        </div>
                                    </div>
                                </div>
                                <div class="itemshop-code-line">
                                    Código de entrega: <strong id="itemshop-code-preview"><?php echo (int)$item['item_section']; ?>:<?php echo (int)$item['item_index']; ?></strong>
                                    <span id="itemshop-section-label"><?php echo itemshopAdminEsc(isset($sectionLabels[(int)$item['item_section']]) ? $sectionLabels[(int)$item['item_section']] : ''); ?></span>
                                </div>
                                <div class="form-group itemshop-category-group">
                                    <label for="itemshop-category">Categoría del Arsenal</label>
                                    <input id="itemshop-category" class="form-control" name="category" maxlength="50" required list="itemshop-category-list" value="<?php echo itemshopAdminEsc($item['category']); ?>" autocomplete="off">
                                    <datalist id="itemshop-category-list">
                                        <?php foreach($categories as $category) { ?><option value="<?php echo itemshopAdminEsc($category); ?>"><?php } ?>
                                    </datalist>
                                </div>
                            </div>
                            <div class="col-sm-5">
                                <div class="itemshop-asset-card">
                                    <div class="itemshop-asset-stage">
                                        <img id="itemshop-asset-image" src="<?php echo itemshopAdminEsc($initialImage); ?>" alt=""<?php echo $initialImage === '' ? ' hidden' : ''; ?>>
                                        <span id="itemshop-asset-empty"<?php echo $initialImage !== '' ? ' hidden' : ''; ?>>Sin asset localizado</span>
                                    </div>
                                    <strong id="itemshop-asset-status"><?php
                                        if(is_array($assetInfo)) {
                                            echo 'Asset localizado';
                                            if(!empty($assetInfo['pixel_width']) && !empty($assetInfo['pixel_height'])) echo ' · '.(int)$assetInfo['pixel_width'].'×'.(int)$assetInfo['pixel_height'].' px';
                                        } else echo 'Verificando asset del cliente';
                                    ?></strong>
                                    <span id="itemshop-dimension-status"><?php
                                        if(is_array($assetInfo) && !empty($assetInfo['grid_reliable'])) echo 'Medida verificable: '.(int)$assetInfo['grid_width'].'×'.(int)$assetInfo['grid_height'].' casillas';
                                        elseif(is_array($assetInfo)) echo 'La imagen no permite deducir el tamaño del baúl con seguridad.';
                                        else echo 'Introduce Section e Index para buscar la imagen instalada.';
                                    ?></span>
                                    <button type="button" class="btn btn-default btn-sm" id="itemshop-apply-dimensions"<?php echo !(is_array($assetInfo) && !empty($assetInfo['grid_reliable'])) ? ' disabled' : ''; ?>
                                            data-width="<?php echo is_array($assetInfo) && !empty($assetInfo['grid_reliable']) ? (int)$assetInfo['grid_width'] : ''; ?>"
                                            data-height="<?php echo is_array($assetInfo) && !empty($assetInfo['grid_reliable']) ? (int)$assetInfo['grid_height'] : ''; ?>">Aplicar medida de imagen</button>
                                </div>
                            </div>
                        </div>

                        <div class="form-group" style="margin-top:16px">
                            <label for="itemshop-description">Descripción</label>
                            <textarea id="itemshop-description" class="form-control" name="description" maxlength="500" rows="3"><?php echo itemshopAdminEsc($item['description']); ?></textarea>
                            <p class="help-block"><span id="itemshop-description-count">0</span>/500 caracteres. Explica función o procedencia; evita repetir las opciones técnicas.</p>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default itemshop-admin-panel">
                    <div class="panel-heading"><strong>2 · Configuración jugable</strong><span>La interfaz traduce los XML del servidor a controles seguros; los bytes quedan detrás.</span></div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-sm-4">
                                <div class="form-group"><label>Nivel</label><input class="form-control" type="number" min="0" max="15" name="item_level" required value="<?php echo (int)$item['item_level']; ?>"></div>
                            </div>
                            <div class="col-sm-4">
                                <div class="form-group"><label for="itemshop-option-level">Opción adicional</label><select id="itemshop-option-level" class="form-control" name="option_level"><?php for($n=0;$n<=7;$n++) { ?><option value="<?php echo $n; ?>"<?php echo (int)$item['option_level']===$n?' selected':''; ?>>Nivel <?php echo $n; ?></option><?php } ?></select><p class="help-block" id="itemshop-option-help">Disponibilidad según Item.txt.</p></div>
                            </div>
                            <div class="col-sm-4">
                                <div class="form-group"><label>Durabilidad</label><input class="form-control" type="number" min="0" max="255" name="durability" required value="<?php echo (int)$item['durability']; ?>"></div>
                            </div>
                        </div>

                        <div class="itemshop-option-row">
                            <label class="checkbox-inline"><input id="itemshop-has-skill" type="checkbox" name="has_skill" value="1"<?php echo itemshopAdminChecked($item['has_skill']); ?>> Skill</label>
                            <label class="checkbox-inline"><input id="itemshop-has-luck" type="checkbox" name="has_luck" value="1"<?php echo itemshopAdminChecked($item['has_luck']); ?>> Luck</label>
                            <label class="checkbox-inline itemshop-380-toggle"><input id="itemshop-option-380" type="checkbox" name="option_380" value="1"<?php echo itemshopAdminChecked($item['option_380']); ?>> Opción 380</label>
                            <button type="button" class="btn btn-link btn-xs" id="itemshop-reset-options">Restablecer opciones base</button>
                        </div>
                        <div id="itemshop-capability-note" class="itemshop-capability-note">Leyendo capacidades del catálogo técnico…</div>

                        <div class="form-group itemshop-excellent-options">
                            <label>Excellent <span class="label label-info" id="itemshop-excellent-profile"><?php echo itemshopAdminEsc($excellentProfile['name'] ?? 'Sin perfil'); ?></span> <span class="label label-default" id="itemshop-excellent-count">0 seleccionadas</span></label>
                            <div class="itemshop-smart-grid itemshop-excellent-grid">
                                <?php $optNo=1; foreach(array(1,2,4,8,16,32) as $bit) { ?>
                                    <label class="checkbox itemshop-excellent-choice"><input type="checkbox" name="excellent_options[]" data-excellent-bit value="<?php echo $bit; ?>"<?php echo (((int)$item['excellent_mask'] & $bit) === $bit)?' checked':''; ?>> <span data-excellent-label><?php echo itemshopAdminEsc($excellentLabels[$bit] ?? ('Opción Excellent '.$optNo)); ?></span> <small>bit <?php echo $bit; ?></small></label>
                                <?php $optNo++; } ?>
                            </div>
                            <p class="help-block">Arsenal usa el perfil Excellent declarado por <code>Items.xml</code>. Los perfiles especiales sin mapa de bits verificable permanecen bloqueados en lugar de asumir opciones.</p>
                        </div>

                        <div class="row itemshop-smart-selects">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="itemshop-ancient">Ancient</label>
                                    <select id="itemshop-ancient" class="form-control" name="ancient_option">
                                        <?php foreach($currentAncientOptions as $raw=>$label) { ?><option value="<?php echo (int)$raw; ?>"<?php echo (int)$item['ancient_option']===(int)$raw?' selected':''; ?>><?php echo itemshopAdminEsc($label); ?></option><?php } ?>
                                    </select>
                                    <p class="help-block" id="itemshop-ancient-help">Opciones vinculadas a este código en Ancient_Items.xml.</p>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="itemshop-harmony">Harmony</label>
                                    <select id="itemshop-harmony" class="form-control" name="harmony_option">
                                        <?php foreach($currentHarmonyOptions as $raw=>$label) { ?><option value="<?php echo (int)$raw; ?>"<?php echo (int)$item['harmony_option']===(int)$raw?' selected':''; ?>><?php echo itemshopAdminEsc($label); ?></option><?php } ?>
                                    </select>
                                    <p class="help-block" id="itemshop-harmony-help">Familia automática según Section. Los ítems Socket reservan este byte para Socket Bonus.</p>
                                </div>
                            </div>
                        </div>

                        <div class="itemshop-socket-panel" id="itemshop-socket-panel">
                            <div class="itemshop-socket-heading">
                                <div><strong>Socket</strong> <span class="label <?php echo !empty($smartCurrent['socket_capable']) ? 'label-success' : 'label-default'; ?>" id="itemshop-socket-status"><?php echo !empty($smartCurrent['socket_capable']) ? 'Compatible' : 'No compatible'; ?></span></div>
                                <span id="itemshop-socket-count-label"><?php echo (int)$item['socket_count']; ?> / 5 slots configurados</span>
                            </div>
                            <div class="row">
                                <?php for($slot=1;$slot<=5;$slot++) { ?>
                                    <div class="col-sm-6 col-md-4">
                                        <div class="form-group">
                                            <label for="itemshop-socket-<?php echo $slot; ?>">Slot <?php echo $slot; ?></label>
                                            <select id="itemshop-socket-<?php echo $slot; ?>" class="form-control" name="socket_option_<?php echo $slot; ?>" data-socket-slot>
                                                <?php foreach($currentSocketOptions as $raw=>$label) { ?><option value="<?php echo (int)$raw; ?>"<?php echo (int)$item['socket_option_'.$slot]===(int)$raw?' selected':''; ?>><?php echo itemshopAdminEsc($label); ?></option><?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                <?php } ?>
                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label for="itemshop-socket-bonus">Bonus Socket</label>
                                        <select id="itemshop-socket-bonus" class="form-control" name="socket_bonus">
                                            <?php foreach($currentSocketBonuses as $raw=>$label) { ?><option value="<?php echo (int)$raw; ?>"<?php echo (int)$item['socket_bonus']===(int)$raw?' selected':''; ?>><?php echo itemshopAdminEsc($label); ?></option><?php } ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <p class="help-block">255 = sin slot · 254 = slot vacío · una semilla usa su Index de <code>Socket_Options.xml</code>. Los slots deben ser contiguos desde el Slot 1.</p>
                        </div>

                        <div class="row itemshop-dimensions-row">
                            <div class="col-sm-6">
                                <label>Espacio en baúl</label>
                                <div class="row">
                                    <div class="col-xs-6"><input id="itemshop-width" class="form-control" type="number" min="1" max="8" name="width" required value="<?php echo (int)$item['width']; ?>" placeholder="Ancho"></div>
                                    <div class="col-xs-6"><input id="itemshop-height" class="form-control" type="number" min="1" max="15" name="height" required value="<?php echo (int)$item['height']; ?>" placeholder="Alto"></div>
                                </div>
                                <p class="help-block">La huella X/Y de <code>Items.xml</code> es la autoridad del Warehouse; la imagen se usa solo como contraste visual.</p>
                            </div>
                            <div class="col-sm-6">
                                <div class="itemshop-byte-summary">
                                    <strong>Control estructural</strong>
                                    <span id="itemshop-smart-byte-summary">Excellent, Ancient, Harmony/Socket y 380 se validan contra el catálogo antes de guardar.</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default itemshop-admin-panel">
                    <div class="panel-heading"><strong>3 · Presentación</strong><span>La imagen subida define el artwork público; sin carga se usa el render técnico.</span></div>
                    <div class="panel-body">
                        <div class="form-group">
                            <label>Imagen promocional</label>
                            <input id="itemshop-promo-input" type="file" name="image" accept="image/webp,image/jpeg,image/png,image/gif">
                            <div class="itemshop-promo-guideline">
                                <strong>Estándar visual Nexora</strong>
                                <span><b>1600 × 900 px · 16:9</b> · WEBP recomendado · objetivo 250–600 KB · máximo técnico 2 MB.</span>
                                <small>Mantén personaje, alas u objeto principal dentro del 70% central. Arsenal usa la imagen subida como artwork; sin imagen, usa el render técnico del cliente.</small>
                            </div>
                            <div class="itemshop-current-promo" id="itemshop-promo-preview"<?php echo $customImage === '' ? ' hidden' : ''; ?>>
                                <div class="itemshop-promo-stage">
                                    <img id="itemshop-promo-preview-image" src="<?php echo itemshopAdminEsc($customImage); ?>" alt="">
                                    <span class="itemshop-promo-safe" aria-hidden="true">Zona segura 70%</span>
                                </div>
                                <div class="itemshop-promo-meta">
                                    <strong id="itemshop-promo-preview-label"><?php echo $customImage !== '' ? 'Imagen promocional actual' : ''; ?></strong>
                                    <span id="itemshop-promo-preview-spec"><?php echo $customImage !== '' ? 'Analizando resolución…' : ''; ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="panel panel-default itemshop-admin-panel itemshop-sticky-panel">
                    <div class="panel-heading"><strong>Control de publicación</strong><span>Economía y disponibilidad del reino.</span></div>
                    <div class="panel-body">
                        <div class="itemshop-admin-summary">
                            <span>Reino</span><strong><?php echo itemshopAdminEsc($shop->getRealmLabel()); ?></strong>
                            <span>Código</span><strong id="itemshop-summary-code"><?php echo (int)$item['item_section']; ?>:<?php echo (int)$item['item_index']; ?></strong>
                            <span>Valor</span><strong id="itemshop-summary-price"><?php echo number_format((int)$item['price_wc']); ?> <?php echo itemshopAdminEsc($shop->currencyLabel()); ?></strong>
                            <span>Stock</span><strong id="itemshop-summary-stock"><?php echo (int)$item['stock'] < 0 ? 'Ilimitado' : number_format((int)$item['stock']); ?></strong>
                        </div>

                        <hr>
                        <div class="form-group"><label>Precio normal</label><div class="input-group"><input id="itemshop-price" class="form-control" type="number" min="1" name="price_wc" required value="<?php echo (int)$item['price_wc']; ?>"><span class="input-group-addon"><?php echo itemshopAdminEsc($shop->currencyLabel()); ?></span></div></div>
                        <div class="form-group"><label>Precio promocional</label><div class="input-group"><input id="itemshop-sale-price" class="form-control" type="number" min="1" name="sale_price_wc" value="<?php echo $item['sale_price_wc'] === null ? '' : (int)$item['sale_price_wc']; ?>" placeholder="Sin promoción"><span class="input-group-addon"><?php echo itemshopAdminEsc($shop->currencyLabel()); ?></span></div><p class="help-block" id="itemshop-sale-help">Vacío = sin descuento.</p></div>
                        <div class="row">
                            <div class="col-sm-6"><div class="form-group"><label>Inicio promo</label><input id="itemshop-sale-start" class="form-control" type="datetime-local" name="sale_start" value="<?php echo itemshopAdminEsc($saleStart); ?>"></div></div>
                            <div class="col-sm-6"><div class="form-group"><label>Fin promo</label><input id="itemshop-sale-end" class="form-control" type="datetime-local" name="sale_end" value="<?php echo itemshopAdminEsc($saleEnd); ?>"></div></div>
                        </div>

                        <hr>
                        <div class="form-group"><label>Stock</label><input id="itemshop-stock" class="form-control" type="number" min="-1" name="stock" required value="<?php echo (int)$item['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)$item['max_per_account']; ?>"><p class="help-block">0 = sin límite histórico.</p></div>
                        <div class="form-group"><label>Orden</label><input class="form-control" type="number" min="-100000" max="100000" name="sort_order" required value="<?php echo (int)$item['sort_order']; ?>"></div>

                        <div class="itemshop-publish-switches">
                            <label><input id="itemshop-active" type="checkbox" name="active" value="1"<?php echo itemshopAdminChecked($item['active']); ?>> Publicado</label>
                            <label><input type="checkbox" name="featured" value="1"<?php echo itemshopAdminChecked($item['featured']); ?>> Destacado</label>
                        </div>

                        <div id="itemshop-form-health" class="alert alert-warning">
                            Verificando coherencia del formulario…
                        </div>
                        <button class="btn btn-success btn-lg btn-block" type="submit" name="save_item" value="1">Guardar configuración</button>
                        <p class="itemshop-save-note">Guardar no obliga a publicar. Para nuevas configuraciones, mantener el ítem oculto hasta validar una compra controlada reduce riesgo operativo.</p>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<script>
window.NEXORA_ITEMSHOP_ADMIN = {
    hints: <?php echo $hintJson !== false ? $hintJson : '{}'; ?>,
    sections: <?php echo $sectionJson !== false ? $sectionJson : '{}'; ?>,
    options: <?php echo $smartJson !== false ? $smartJson : '{}'; ?>
};
</script>
<script src="<?php echo itemshopAdminEsc(__PATH_ADMINCP_HOME__); ?>js/itemshop-admin.js?v=168"></script>
