<?php
/** Nexora VE Networks — Benefits manager. */
if (!defined('access')) die('Direct access not permitted.');

$nexBenefitsConfigFile = __PATH_CONFIGS__ . 'benefits.json';
$nexBenefitsUploadDir = __PATH_TEMPLATE_ROOT__ . 'img/benefits/';

function nexBenefitsAdminLoad() {
    $cfg = loadConfig('benefits');
    if (!is_array($cfg)) $cfg = array();
    if (!isset($cfg['settings']) || !is_array($cfg['settings'])) $cfg['settings'] = array();
    if (!isset($cfg['items']) || !is_array($cfg['items'])) $cfg['items'] = array();
    $commerceDefaults = array(
        'commerce_enabled'=>true, 'commerce_title'=>'W Coins y bonificaciones',
        'commerce_subtitle'=>'Consulta la equivalencia vigente, compara paquetes y elige el canal de pago que corresponde.',
        'wc_per_usd'=>1000, 'whatsapp_number'=>'584242697163', 'whatsapp_label'=>'Consultar por WhatsApp',
        'whatsapp_message'=>'Hola Nexora, quiero consultar el paquete {package} de {price} para el reino {realm}.',
        'direct_promo_enabled'=>true, 'direct_promo_badge'=>'BONO DIRECTO',
        'direct_promo_title'=>'30% adicional por USDT o equivalencia en Bs.',
        'direct_promo_text'=>'Los pagos coordinados por USDT o su equivalencia en bolívares reciben 30% adicional sobre los WC base.',
        'direct_promo_bonus'=>30, 'direct_promo_start'=>date('Y-m-d'), 'direct_promo_end'=>''
    );
    $cfg['settings'] = array_merge($commerceDefaults, $cfg['settings']);
    if (!array_key_exists('packages', $cfg) || !is_array($cfg['packages'])) {
        $cfg['packages'] = array(
            array('id'=>'wc-5','enabled'=>true,'order'=>10,'name'=>'Paquete 5K','usd'=>5,'base_wc'=>5000,'bonus_percent'=>30,'payment'=>'USDT / Bs.','featured'=>false),
            array('id'=>'wc-10','enabled'=>true,'order'=>20,'name'=>'Paquete 10K','usd'=>10,'base_wc'=>10000,'bonus_percent'=>30,'payment'=>'USDT / Bs.','featured'=>true),
            array('id'=>'wc-20','enabled'=>true,'order'=>30,'name'=>'Paquete 20K','usd'=>20,'base_wc'=>20000,'bonus_percent'=>30,'payment'=>'USDT / Bs.','featured'=>false)
        );
    }
    return $cfg;
}
function nexBenefitsAdminText($value, $max = 500) {
    $value = trim(strip_tags((string)$value));
    return function_exists('mb_substr') ? mb_substr($value, 0, $max, 'UTF-8') : substr($value, 0, $max);
}
function nexBenefitsAdminUrl($value) {
    $value = trim((string)$value);
    if ($value === '') return '';
    if (preg_match('#^https?://#i', $value)) {
        if (!filter_var($value, FILTER_VALIDATE_URL)) throw new Exception('La URL externa no es válida.');
        return $value;
    }
    if (!preg_match('#^[a-zA-Z0-9/_-]+$#', $value)) throw new Exception('La ruta interna contiene caracteres no permitidos.');
    return ltrim($value, '/');
}
function nexBenefitsAdminSave($cfg) {
    $path = __PATH_CONFIGS__ . 'benefits.json';
    $json = json_encode($cfg, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($json === false || @file_put_contents($path, $json . "\n", LOCK_EX) === false) throw new Exception('No se pudo guardar benefits.json.');
}
function nexBenefitsAdminUpload($field, $id) {
    $uploadDir = __PATH_TEMPLATE_ROOT__ . 'img/benefits/';
    if (!isset($_FILES[$field]) || !is_array($_FILES[$field])) return '';
    $file = $_FILES[$field];
    $error = isset($file['error']) ? (int)$file['error'] : UPLOAD_ERR_NO_FILE;
    $tmpName = isset($file['tmp_name']) ? trim((string)$file['tmp_name']) : '';
    $originalName = isset($file['name']) ? trim((string)$file['name']) : '';
    /* En algunos hosts PHP reporta UPLOAD_ERR_OK aunque el selector quedó vacío.
       Debe significar "conservar imagen", nunca intentar validar una ruta vacía. */
    if ($error === UPLOAD_ERR_NO_FILE || $tmpName === '' || $originalName === '') return '';
    if ($error !== UPLOAD_ERR_OK) throw new Exception('La imagen no pudo cargarse. Código: ' . $error);
    if ((int)$file['size'] < 1 || (int)$file['size'] > 10 * 1024 * 1024) throw new Exception('La imagen debe pesar menos de 10 MB.');
    if (!is_uploaded_file($tmpName)) throw new Exception('Archivo cargado no válido.');
    $info = @getimagesize($tmpName);
    $map = array('image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp');
    if (!$info || !isset($map[strtolower($info['mime'])])) throw new Exception('Formatos permitidos: JPG, PNG y WebP.');
    if ((int)$info[0] > 7000 || (int)$info[1] > 7000) throw new Exception('Dimensiones máximas: 7000 × 7000 px.');
    if (!is_dir($uploadDir) && !@mkdir($uploadDir, 0755, true)) throw new Exception('No se pudo crear la carpeta de imágenes.');
    $safe = preg_replace('/[^a-z0-9_-]+/i', '-', $id);
    $name = trim($safe, '-') . '-' . date('YmdHis') . '.' . $map[strtolower($info['mime'])];
    if (!@move_uploaded_file($tmpName, $uploadDir . $name)) throw new Exception('No se pudo almacenar la imagen.');
    @chmod($uploadDir . $name, 0644);
    return $name;
}
function nexBenefitsAdminId($title) {
    $id = strtolower($title);
    if (function_exists('iconv')) { $tmp = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $id); if ($tmp !== false) $id = $tmp; }
    $id = trim(preg_replace('/[^a-z0-9]+/', '-', $id), '-');
    return ($id !== '' ? $id : 'beneficio') . '-' . substr(md5(uniqid('', true)), 0, 6);
}
function nexBenefitsAdminNumber($value, $min = 0, $max = 100000000) {
    if (!is_numeric($value)) return $min;
    return max($min, min($max, (float)$value));
}

try {
    if (!file_exists($nexBenefitsConfigFile)) nexBenefitsAdminSave(array('settings'=>array(), 'items'=>array()));
    if (!is_writable($nexBenefitsConfigFile)) throw new Exception('benefits.json no tiene permisos de escritura.');
    if (!is_dir($nexBenefitsUploadDir)) @mkdir($nexBenefitsUploadDir, 0755, true);
    $cfg = nexBenefitsAdminLoad();
    /* Migra instalaciones anteriores sin alterar recompensas ni imágenes existentes. */
    $storedBenefitsCfg = loadConfig('benefits');
    if (!is_array($storedBenefitsCfg) || !array_key_exists('packages', $storedBenefitsCfg)) nexBenefitsAdminSave($cfg);

    if (isset($_POST['benefits_settings_save'])) {
        $cfg['settings'] = array(
            'enabled' => isset($_POST['enabled']),
            'eyebrow' => nexBenefitsAdminText($_POST['eyebrow'] ?? '', 80),
            'title' => nexBenefitsAdminText($_POST['section_title'] ?? '', 100),
            'subtitle' => nexBenefitsAdminText($_POST['subtitle'] ?? '', 320),
            'notice' => nexBenefitsAdminText($_POST['notice'] ?? '', 400),
            'cta_label' => nexBenefitsAdminText($_POST['main_cta_label'] ?? '', 60),
            'cta_url' => nexBenefitsAdminUrl($_POST['main_cta_url'] ?? ''),
            'commerce_enabled' => isset($_POST['commerce_enabled']),
            'commerce_title' => nexBenefitsAdminText($_POST['commerce_title'] ?? '', 100),
            'commerce_subtitle' => nexBenefitsAdminText($_POST['commerce_subtitle'] ?? '', 320),
            'wc_per_usd' => (int)nexBenefitsAdminNumber($_POST['wc_per_usd'] ?? 1000, 1, 10000000),
            'whatsapp_number' => preg_replace('/[^0-9]/', '', (string)($_POST['whatsapp_number'] ?? '')),
            'whatsapp_label' => nexBenefitsAdminText($_POST['whatsapp_label'] ?? '', 60),
            'whatsapp_message' => nexBenefitsAdminText($_POST['whatsapp_message'] ?? '', 400),
            'direct_promo_enabled' => isset($_POST['direct_promo_enabled']),
            'direct_promo_badge' => nexBenefitsAdminText($_POST['direct_promo_badge'] ?? '', 40),
            'direct_promo_title' => nexBenefitsAdminText($_POST['direct_promo_title'] ?? '', 140),
            'direct_promo_text' => nexBenefitsAdminText($_POST['direct_promo_text'] ?? '', 500),
            'direct_promo_bonus' => nexBenefitsAdminNumber($_POST['direct_promo_bonus'] ?? 30, 0, 1000),
            'direct_promo_start' => nexBenefitsAdminText($_POST['direct_promo_start'] ?? '', 10),
            'direct_promo_end' => nexBenefitsAdminText($_POST['direct_promo_end'] ?? '', 10)
        );
        nexBenefitsAdminSave($cfg); message('success', 'Configuración general actualizada.');
    }
    if (isset($_POST['benefit_add'])) {
        $title = nexBenefitsAdminText($_POST['title'] ?? '', 120);
        if ($title === '') throw new Exception('El título es obligatorio.');
        $id = nexBenefitsAdminId($title);
        $image = nexBenefitsAdminUpload('image', $id);
        if ($image === '') throw new Exception('Selecciona una imagen para el beneficio.');
        $cfg['items'][] = array(
            'id'=>$id, 'enabled'=>true, 'order'=>(int)($_POST['order'] ?? 100),
            'type'=>in_array($_POST['type'] ?? '', array('season','package','wc','news'), true) ? $_POST['type'] : 'package',
            'realm'=>in_array($_POST['realm'] ?? '', array('legacy','seasonal','both'), true) ? $_POST['realm'] : 'both',
            'badge'=>nexBenefitsAdminText($_POST['badge'] ?? '', 40), 'title'=>$title,
            'description'=>nexBenefitsAdminText($_POST['description'] ?? '', 700), 'image'=>$image,
            'start_at'=>nexBenefitsAdminText($_POST['start_at'] ?? '', 10), 'end_at'=>nexBenefitsAdminText($_POST['end_at'] ?? '', 10),
            'highlights'=>nexBenefitsAdminText($_POST['highlights'] ?? '', 1000),
            'cta_label'=>nexBenefitsAdminText($_POST['cta_label'] ?? '', 60), 'cta_url'=>nexBenefitsAdminUrl($_POST['cta_url'] ?? ''),
            'featured'=>isset($_POST['featured'])
        );
        nexBenefitsAdminSave($cfg);
        message('success', 'Beneficio publicado correctamente.');
    }
    if (isset($_POST['benefit_save'], $_POST['item_id'])) {
        $benefitSaved = false;
        foreach ($cfg['items'] as $i => $item) if (($item['id'] ?? '') === $_POST['item_id']) {
            $cfg['items'][$i]['enabled'] = isset($_POST['enabled']);
            $cfg['items'][$i]['featured'] = isset($_POST['featured']);
            $cfg['items'][$i]['order'] = (int)($_POST['order'] ?? 100);
            $cfg['items'][$i]['type'] = in_array($_POST['type'] ?? '', array('season','package','wc','news'), true) ? $_POST['type'] : 'package';
            $cfg['items'][$i]['realm'] = in_array($_POST['realm'] ?? '', array('legacy','seasonal','both'), true) ? $_POST['realm'] : 'both';
            foreach (array('badge'=>40,'title'=>120,'description'=>700,'start_at'=>10,'end_at'=>10,'highlights'=>1000,'cta_label'=>60) as $key=>$max) $cfg['items'][$i][$key] = nexBenefitsAdminText($_POST[$key] ?? '', $max);
            if ($cfg['items'][$i]['title'] === '') throw new Exception('El título es obligatorio.');
            $cfg['items'][$i]['cta_url'] = nexBenefitsAdminUrl($_POST['cta_url'] ?? '');
            $newImage = nexBenefitsAdminUpload('image', $item['id']); if ($newImage !== '') $cfg['items'][$i]['image'] = $newImage;
            nexBenefitsAdminSave($cfg);
            $benefitSaved = true;
            message('success', 'Beneficio actualizado correctamente.');
            break;
        }
        if (!$benefitSaved) throw new Exception('Beneficio no encontrado.');
    }
    if (isset($_POST['benefit_delete'], $_POST['item_id'])) {
        $benefitDeleted = false;
        foreach ($cfg['items'] as $i=>$item) if (($item['id'] ?? '') === $_POST['item_id']) {
            array_splice($cfg['items'], $i, 1);
            nexBenefitsAdminSave($cfg);
            $benefitDeleted = true;
            message('success', 'Beneficio eliminado correctamente.');
            break;
        }
        if (!$benefitDeleted) throw new Exception('Beneficio no encontrado.');
    }

    if (isset($_POST['package_add'])) {
        $name = nexBenefitsAdminText($_POST['package_name'] ?? '', 80);
        if ($name === '') throw new Exception('El nombre del paquete es obligatorio.');
        $cfg['packages'][] = array(
            'id' => nexBenefitsAdminId($name), 'enabled' => isset($_POST['package_enabled']),
            'order' => (int)($_POST['package_order'] ?? 100), 'name' => $name,
            'usd' => nexBenefitsAdminNumber($_POST['package_usd'] ?? 0, 0, 1000000),
            'base_wc' => (int)nexBenefitsAdminNumber($_POST['package_base_wc'] ?? 0, 0, 100000000),
            'bonus_percent' => nexBenefitsAdminNumber($_POST['package_bonus'] ?? 0, 0, 1000),
            'payment' => nexBenefitsAdminText($_POST['package_payment'] ?? '', 80),
            'featured' => isset($_POST['package_featured'])
        );
        nexBenefitsAdminSave($cfg); message('success', 'Paquete publicado correctamente.');
    }
    if (isset($_POST['package_save'], $_POST['package_id'])) {
        $packageSaved = false;
        foreach ($cfg['packages'] as $i => $package) if (($package['id'] ?? '') === $_POST['package_id']) {
            $name = nexBenefitsAdminText($_POST['package_name'] ?? '', 80);
            if ($name === '') throw new Exception('El nombre del paquete es obligatorio.');
            $cfg['packages'][$i] = array(
                'id' => $package['id'], 'enabled' => isset($_POST['package_enabled']),
                'order' => (int)($_POST['package_order'] ?? 100), 'name' => $name,
                'usd' => nexBenefitsAdminNumber($_POST['package_usd'] ?? 0, 0, 1000000),
                'base_wc' => (int)nexBenefitsAdminNumber($_POST['package_base_wc'] ?? 0, 0, 100000000),
                'bonus_percent' => nexBenefitsAdminNumber($_POST['package_bonus'] ?? 0, 0, 1000),
                'payment' => nexBenefitsAdminText($_POST['package_payment'] ?? '', 80),
                'featured' => isset($_POST['package_featured'])
            );
            nexBenefitsAdminSave($cfg); $packageSaved = true; message('success', 'Paquete actualizado correctamente.'); break;
        }
        if (!$packageSaved) throw new Exception('Paquete no encontrado.');
    }
    if (isset($_POST['package_delete'], $_POST['package_id'])) {
        $packageDeleted = false;
        foreach ($cfg['packages'] as $i => $package) if (($package['id'] ?? '') === $_POST['package_id']) {
            array_splice($cfg['packages'], $i, 1); nexBenefitsAdminSave($cfg); $packageDeleted = true; message('success', 'Paquete eliminado.'); break;
        }
        if (!$packageDeleted) throw new Exception('Paquete no encontrado.');
    }
} catch (Throwable $ex) {
    message('error', 'Beneficios Nexora: ' . $ex->getMessage());
    $cfg = nexBenefitsAdminLoad();
}

$s = $cfg['settings'];
function nexBA($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function nexBenefitsAdminFields($item, $prefix) { ?>
    <div class="row"><div class="col-md-2 form-group"><label>Orden</label><input class="form-control" type="number" name="order" value="<?php echo nexBA($item['order'] ?? 100); ?>"></div>
    <div class="col-md-3 form-group"><label>Tipo</label><select class="form-control" name="type"><?php foreach(array('season'=>'Temporada','package'=>'Paquete','wc'=>'Promoción WC','news'=>'Novedad') as $v=>$l) echo '<option value="'.$v.'"'.(($item['type'] ?? '')===$v?' selected':'').'>'.$l.'</option>'; ?></select></div>
    <div class="col-md-3 form-group"><label>Reino</label><select class="form-control" name="realm"><?php foreach(array('legacy'=>'Legado','seasonal'=>'Seasonal','both'=>'Ambos') as $v=>$l) echo '<option value="'.$v.'"'.(($item['realm'] ?? '')===$v?' selected':'').'>'.$l.'</option>'; ?></select></div>
    <div class="col-md-4 form-group"><label>Etiqueta</label><input class="form-control" name="badge" value="<?php echo nexBA($item['badge'] ?? ''); ?>" placeholder="TEMPORADA 2"></div></div>
    <div class="form-group"><label>Título</label><input class="form-control" name="title" required value="<?php echo nexBA($item['title'] ?? ''); ?>"></div>
    <div class="form-group"><label>Descripción</label><textarea class="form-control" rows="2" name="description"><?php echo nexBA($item['description'] ?? ''); ?></textarea></div>
    <div class="form-group"><label>Puntos destacados <small>(uno por línea)</small></label><textarea class="form-control" rows="4" name="highlights"><?php echo nexBA($item['highlights'] ?? ''); ?></textarea></div>
    <div class="row"><div class="col-md-3 form-group"><label>Inicia</label><input type="date" class="form-control" name="start_at" value="<?php echo nexBA($item['start_at'] ?? ''); ?>"></div><div class="col-md-3 form-group"><label>Finaliza</label><input type="date" class="form-control" name="end_at" value="<?php echo nexBA($item['end_at'] ?? ''); ?>"></div><div class="col-md-3 form-group"><label>Texto del botón</label><input class="form-control" name="cta_label" value="<?php echo nexBA($item['cta_label'] ?? ''); ?>"></div><div class="col-md-3 form-group"><label>Ruta o URL</label><input class="form-control" name="cta_url" value="<?php echo nexBA($item['cta_url'] ?? ''); ?>"></div></div>
    <div class="form-group"><label>Imagen <?php echo $prefix==='edit' ? '(dejar vacía para conservar)' : ''; ?></label><input type="file" class="form-control" name="image" accept="image/jpeg,image/png,image/webp" <?php echo $prefix==='add'?'required':''; ?>></div>
    <label class="checkbox-inline"><input type="checkbox" name="enabled" <?php echo !isset($item['enabled'])||$item['enabled']?'checked':''; ?>> Visible</label>
    <label class="checkbox-inline"><input type="checkbox" name="featured" <?php echo !empty($item['featured'])?'checked':''; ?>> Destacado</label>
<?php } ?>
<h1 class="page-header">Beneficios Nexora</h1>
<p class="lead">Control central de recompensas de temporada, paquetes, novedades y promociones WC.</p>
<div class="panel panel-default"><div class="panel-heading"><strong>Configuración de la página</strong></div><div class="panel-body"><form method="post">
    <label class="checkbox"><input type="checkbox" name="enabled" <?php echo !isset($s['enabled'])||$s['enabled']?'checked':''; ?>> Página activa</label>
    <div class="row"><div class="col-md-4 form-group"><label>Antetítulo</label><input class="form-control" name="eyebrow" value="<?php echo nexBA($s['eyebrow'] ?? ''); ?>"></div><div class="col-md-8 form-group"><label>Título</label><input class="form-control" name="section_title" value="<?php echo nexBA($s['title'] ?? ''); ?>"></div></div>
    <div class="form-group"><label>Introducción</label><textarea class="form-control" name="subtitle"><?php echo nexBA($s['subtitle'] ?? ''); ?></textarea></div><div class="form-group"><label>Nota de transparencia</label><textarea class="form-control" name="notice"><?php echo nexBA($s['notice'] ?? ''); ?></textarea></div>
    <div class="row"><div class="col-md-6 form-group"><label>CTA principal</label><input class="form-control" name="main_cta_label" value="<?php echo nexBA($s['cta_label'] ?? ''); ?>"></div><div class="col-md-6 form-group"><label>Ruta o URL</label><input class="form-control" name="main_cta_url" value="<?php echo nexBA($s['cta_url'] ?? ''); ?>"></div></div>
    <hr><h3>W Coins y contacto</h3>
    <label class="checkbox"><input type="checkbox" name="commerce_enabled" <?php echo !isset($s['commerce_enabled'])||$s['commerce_enabled']?'checked':''; ?>> Mostrar precios y promociones WC</label>
    <div class="row"><div class="col-md-6 form-group"><label>Título del bloque</label><input class="form-control" name="commerce_title" value="<?php echo nexBA($s['commerce_title'] ?? 'W Coins y bonificaciones'); ?>"></div><div class="col-md-6 form-group"><label>WC por 1 USD</label><input class="form-control" type="number" min="1" name="wc_per_usd" value="<?php echo nexBA($s['wc_per_usd'] ?? 1000); ?>"></div></div>
    <div class="form-group"><label>Descripción del bloque</label><textarea class="form-control" name="commerce_subtitle"><?php echo nexBA($s['commerce_subtitle'] ?? ''); ?></textarea></div>
    <div class="row"><div class="col-md-4 form-group"><label>WhatsApp <small>(solo números)</small></label><input class="form-control" name="whatsapp_number" value="<?php echo nexBA($s['whatsapp_number'] ?? '584242697163'); ?>"></div><div class="col-md-4 form-group"><label>Texto del botón</label><input class="form-control" name="whatsapp_label" value="<?php echo nexBA($s['whatsapp_label'] ?? 'Consultar por WhatsApp'); ?>"></div><div class="col-md-4 form-group"><label>Mensaje automático</label><input class="form-control" name="whatsapp_message" value="<?php echo nexBA($s['whatsapp_message'] ?? 'Hola Nexora, quiero consultar el paquete {package} de {price} para el reino {realm}.'); ?>"></div></div>
    <p class="help-block">Variables disponibles en el mensaje: <code>{package}</code>, <code>{price}</code> y <code>{realm}</code>.</p>
    <hr><h3>Promoción por pago directo</h3>
    <label class="checkbox"><input type="checkbox" name="direct_promo_enabled" <?php echo !empty($s['direct_promo_enabled'])?'checked':''; ?>> Promoción activa</label>
    <div class="row"><div class="col-md-3 form-group"><label>Etiqueta</label><input class="form-control" name="direct_promo_badge" value="<?php echo nexBA($s['direct_promo_badge'] ?? 'BONO DIRECTO'); ?>"></div><div class="col-md-6 form-group"><label>Título</label><input class="form-control" name="direct_promo_title" value="<?php echo nexBA($s['direct_promo_title'] ?? '30% adicional por USDT o equivalencia en Bs.'); ?>"></div><div class="col-md-3 form-group"><label>Bonus %</label><input class="form-control" type="number" step="0.01" min="0" name="direct_promo_bonus" value="<?php echo nexBA($s['direct_promo_bonus'] ?? 30); ?>"></div></div>
    <div class="form-group"><label>Condiciones</label><textarea class="form-control" name="direct_promo_text"><?php echo nexBA($s['direct_promo_text'] ?? ''); ?></textarea></div>
    <div class="row"><div class="col-md-3 form-group"><label>Inicia</label><input class="form-control" type="date" name="direct_promo_start" value="<?php echo nexBA($s['direct_promo_start'] ?? ''); ?>"></div><div class="col-md-3 form-group"><label>Finaliza</label><input class="form-control" type="date" name="direct_promo_end" value="<?php echo nexBA($s['direct_promo_end'] ?? ''); ?>"></div></div>
    <button class="btn btn-primary" name="benefits_settings_save" value="1">Guardar configuración</button>
</form></div></div>

<h2>Paquetes de W Coins</h2>
<p class="text-muted">El total se calcula automáticamente: WC base + porcentaje de bonus. Cada botón de WhatsApp incluye paquete, precio y reino seleccionado.</p>
<?php foreach ($cfg['packages'] as $package) { ?>
<div class="panel panel-info"><div class="panel-heading"><strong><?php echo nexBA($package['name'] ?? 'Paquete WC'); ?></strong></div><div class="panel-body"><form method="post">
    <input type="hidden" name="package_id" value="<?php echo nexBA($package['id']); ?>">
    <div class="row"><div class="col-md-1 form-group"><label>Orden</label><input class="form-control" type="number" name="package_order" value="<?php echo nexBA($package['order'] ?? 100); ?>"></div><div class="col-md-3 form-group"><label>Nombre</label><input class="form-control" name="package_name" required value="<?php echo nexBA($package['name'] ?? ''); ?>"></div><div class="col-md-2 form-group"><label>Precio USD</label><input class="form-control" type="number" step="0.01" min="0" name="package_usd" value="<?php echo nexBA($package['usd'] ?? 0); ?>"></div><div class="col-md-2 form-group"><label>WC base</label><input class="form-control" type="number" min="0" name="package_base_wc" value="<?php echo nexBA($package['base_wc'] ?? 0); ?>"></div><div class="col-md-2 form-group"><label>Bonus %</label><input class="form-control" type="number" step="0.01" min="0" name="package_bonus" value="<?php echo nexBA($package['bonus_percent'] ?? 0); ?>"></div><div class="col-md-2 form-group"><label>Método</label><input class="form-control" name="package_payment" value="<?php echo nexBA($package['payment'] ?? 'USDT / Bs.'); ?>"></div></div>
    <label class="checkbox-inline"><input type="checkbox" name="package_enabled" <?php echo !isset($package['enabled'])||$package['enabled']?'checked':''; ?>> Visible</label><label class="checkbox-inline"><input type="checkbox" name="package_featured" <?php echo !empty($package['featured'])?'checked':''; ?>> Destacado</label><hr>
    <button class="btn btn-primary" name="package_save" value="1">Guardar paquete</button><button class="btn btn-danger pull-right" name="package_delete" value="1" onclick="return confirm('¿Eliminar este paquete?');">Eliminar</button>
</form></div></div>
<?php } ?>
<div class="panel panel-success"><div class="panel-heading"><strong>Crear paquete WC</strong></div><div class="panel-body"><form method="post"><div class="row"><div class="col-md-1 form-group"><label>Orden</label><input class="form-control" type="number" name="package_order" value="100"></div><div class="col-md-3 form-group"><label>Nombre</label><input class="form-control" name="package_name" required></div><div class="col-md-2 form-group"><label>Precio USD</label><input class="form-control" type="number" step="0.01" min="0" name="package_usd"></div><div class="col-md-2 form-group"><label>WC base</label><input class="form-control" type="number" min="0" name="package_base_wc"></div><div class="col-md-2 form-group"><label>Bonus %</label><input class="form-control" type="number" step="0.01" min="0" name="package_bonus" value="30"></div><div class="col-md-2 form-group"><label>Método</label><input class="form-control" name="package_payment" value="USDT / Bs."></div></div><label class="checkbox-inline"><input type="checkbox" name="package_enabled" checked> Visible</label><label class="checkbox-inline"><input type="checkbox" name="package_featured"> Destacado</label><hr><button class="btn btn-success" name="package_add" value="1">Crear paquete</button></form></div></div>

<hr><h2>Recompensas, novedades y piezas visuales</h2>

<?php foreach ($cfg['items'] as $item) { ?><div class="panel panel-default"><div class="panel-heading"><strong><?php echo nexBA($item['title'] ?? 'Beneficio'); ?></strong> <span class="label label-info"><?php echo nexBA($item['realm'] ?? 'both'); ?></span></div><div class="panel-body"><form method="post" enctype="multipart/form-data"><input type="hidden" name="item_id" value="<?php echo nexBA($item['id']); ?>"><?php nexBenefitsAdminFields($item, 'edit'); ?><hr><button class="btn btn-primary" name="benefit_save" value="1">Guardar</button> <button class="btn btn-danger pull-right" name="benefit_delete" value="1" onclick="return confirm('¿Eliminar este beneficio?');">Eliminar</button></form></div></div><?php } ?>

<div class="panel panel-success"><div class="panel-heading"><strong>Crear beneficio</strong></div><div class="panel-body"><form method="post" enctype="multipart/form-data"><?php nexBenefitsAdminFields(array('enabled'=>true,'order'=>100,'realm'=>'both','type'=>'package'), 'add'); ?><hr><button class="btn btn-success" name="benefit_add" value="1">Publicar beneficio</button></form></div></div>
