<?php
/** Nexora VE Networks — Benefits public module. */
if (!defined('access') || !access) die();

$cfg = loadConfig('benefits');
if (!is_array($cfg)) $cfg = array();
$settings = isset($cfg['settings']) && is_array($cfg['settings']) ? $cfg['settings'] : array();
$items = isset($cfg['items']) && is_array($cfg['items']) ? $cfg['items'] : array();
$packages = isset($cfg['packages']) && is_array($cfg['packages']) ? $cfg['packages'] : array();
$activeRealm = class_exists('NexoraRealm') ? NexoraRealm::active() : 'legacy';
$today = date('Y-m-d');

function nexBenefitsText($value, $fallback = '') {
    $value = trim((string)$value);
    return htmlspecialchars($value !== '' ? $value : $fallback, ENT_QUOTES, 'UTF-8');
}
function nexBenefitsUrl($value) {
    $value = trim((string)$value);
    if ($value === '') return '';
    if (preg_match('#^https?://#i', $value)) return filter_var($value, FILTER_VALIDATE_URL) ? $value : '';
    return __BASE_URL__ . ltrim($value, '/');
}
function nexBenefitsImage($value) {
    $value = trim((string)$value);
    if ($value === '') return '';
    if (preg_match('#^https?://#i', $value)) return filter_var($value, FILTER_VALIDATE_URL) ? $value : '';
    $base = basename(str_replace('\\', '/', $value));
    return $base === $value ? __PATH_TEMPLATE_IMG__ . 'benefits/' . $base : '';
}
function nexBenefitsWhatsapp($number, $message) {
    $number = preg_replace('/[^0-9]/', '', (string)$number);
    if ($number === '') return '';
    return 'https://wa.me/' . $number . '?text=' . rawurlencode((string)$message);
}

if (isset($settings['enabled']) && !$settings['enabled']) {
    echo '<section class="nex-benefits-empty"><h1>Beneficios</h1><p>La información de beneficios se encuentra en actualización.</p></section>';
    return;
}

$visible = array();
foreach ($items as $item) {
    if (!is_array($item) || empty($item['enabled'])) continue;
    $realm = isset($item['realm']) ? strtolower((string)$item['realm']) : 'both';
    if (!in_array($realm, array('both', $activeRealm), true)) continue;
    $start = isset($item['start_at']) ? trim((string)$item['start_at']) : '';
    $end = isset($item['end_at']) ? trim((string)$item['end_at']) : '';
    if ($start !== '' && $today < $start) continue;
    if ($end !== '' && $today > $end) continue;
    $visible[] = $item;
}
usort($visible, function($a, $b) { return (int)($a['order'] ?? 999) <=> (int)($b['order'] ?? 999); });

$realmLabel = $activeRealm === 'seasonal' ? 'Seasonal' : 'Legado';
$commerceEnabled = !isset($settings['commerce_enabled']) || !empty($settings['commerce_enabled']);
$whatsappNumber = isset($settings['whatsapp_number']) ? $settings['whatsapp_number'] : '584242697163';
$whatsappTemplate = isset($settings['whatsapp_message']) && trim($settings['whatsapp_message']) !== ''
    ? $settings['whatsapp_message']
    : 'Hola Nexora, quiero consultar el paquete {package} de {price} para el reino {realm}.';
$visiblePackages = array();
foreach ($packages as $package) {
    if (!is_array($package) || empty($package['enabled'])) continue;
    $visiblePackages[] = $package;
}
usort($visiblePackages, function($a, $b) { return (int)($a['order'] ?? 999) <=> (int)($b['order'] ?? 999); });
?>
<section class="nex-benefits" aria-labelledby="nex-benefits-title">
    <header class="nex-benefits-hero">
        <div class="nex-benefits-hero__flare" aria-hidden="true"></div>
        <span class="nex-benefits-kicker"><?php echo nexBenefitsText($settings['eyebrow'] ?? '', 'ECOSISTEMA NEXORA'); ?></span>
        <h1 id="nex-benefits-title"><?php echo nexBenefitsText($settings['title'] ?? '', 'Beneficios'); ?></h1>
        <p><?php echo nexBenefitsText($settings['subtitle'] ?? '', 'Información activa para cada reino.'); ?></p>
        <div class="nex-benefits-realm"><span>Reino consultado</span><strong><?php echo nexBenefitsText($realmLabel); ?></strong></div>
    </header>

    <?php if ($commerceEnabled) { ?>
    <section class="nex-benefits-commerce" aria-labelledby="nex-commerce-title">
        <div class="nex-benefits-commerce__head">
            <div><span>VALOR OFICIAL</span><h2 id="nex-commerce-title"><?php echo nexBenefitsText($settings['commerce_title'] ?? '', 'W Coins y bonificaciones'); ?></h2><p><?php echo nexBenefitsText($settings['commerce_subtitle'] ?? '', 'Compara paquetes y consulta el canal de pago correspondiente.'); ?></p></div>
            <div class="nex-wc-rate"><small>Equivalencia base</small><strong>1 USD</strong><i>=</i><strong><?php echo number_format((int)($settings['wc_per_usd'] ?? 1000), 0, ',', '.'); ?> WC</strong></div>
        </div>

        <?php if (!empty($settings['direct_promo_enabled'])) {
            $promoStart = trim((string)($settings['direct_promo_start'] ?? ''));
            $promoEnd = trim((string)($settings['direct_promo_end'] ?? ''));
            $promoActive = ($promoStart === '' || $today >= $promoStart) && ($promoEnd === '' || $today <= $promoEnd);
            if ($promoActive) { ?>
            <article class="nex-direct-promo">
                <div class="nex-direct-promo__bonus"><strong>+<?php echo (int)($settings['direct_promo_bonus'] ?? 30); ?>%</strong><span>WC BONUS</span></div>
                <div><span><?php echo nexBenefitsText($settings['direct_promo_badge'] ?? '', 'BONO DIRECTO'); ?></span><h3><?php echo nexBenefitsText($settings['direct_promo_title'] ?? '', 'Bonificación por USDT o equivalencia en Bs.'); ?></h3><p><?php echo nexBenefitsText($settings['direct_promo_text'] ?? ''); ?></p></div>
                <?php $promoMsg = str_replace(array('{package}','{price}','{realm}'), array('promoción directa','USDT/Bs.',$realmLabel), $whatsappTemplate); $promoWa = nexBenefitsWhatsapp($whatsappNumber, $promoMsg); if ($promoWa !== '') { ?><a href="<?php echo nexBenefitsText($promoWa); ?>" target="_blank" rel="noopener noreferrer">Consultar promoción</a><?php } ?>
            </article>
        <?php } } ?>

        <?php if (!empty($visiblePackages)) { ?><div class="nex-wc-packages">
        <?php foreach ($visiblePackages as $package) {
            $base = max(0, (int)($package['base_wc'] ?? 0));
            $bonusPct = max(0, (float)($package['bonus_percent'] ?? 0));
            $bonus = (int)round($base * $bonusPct / 100);
            $total = $base + $bonus;
            $usd = (float)($package['usd'] ?? 0);
            $priceLabel = '$' . number_format($usd, 2, '.', '') . ' USD';
            $message = str_replace(array('{package}','{price}','{realm}'), array($package['name'] ?? 'WC', $priceLabel, $realmLabel), $whatsappTemplate);
            $wa = nexBenefitsWhatsapp($whatsappNumber, $message);
        ?>
            <article class="nex-wc-package<?php echo !empty($package['featured']) ? ' is-featured' : ''; ?>">
                <?php if (!empty($package['featured'])) { ?><span class="nex-wc-package__featured">DESTACADO</span><?php } ?>
                <small><?php echo nexBenefitsText($package['payment'] ?? '', 'USDT / Bs.'); ?></small>
                <h3><?php echo nexBenefitsText($package['name'] ?? '', 'Paquete WC'); ?></h3>
                <div class="nex-wc-package__price"><strong>$<?php echo number_format($usd, 2, '.', ''); ?></strong><span>USD</span></div>
                <dl><div><dt>Base</dt><dd><?php echo number_format($base, 0, ',', '.'); ?> WC</dd></div><div><dt>Bonus</dt><dd>+<?php echo number_format($bonus, 0, ',', '.'); ?> WC</dd></div></dl>
                <div class="nex-wc-package__total"><span>Total</span><strong><?php echo number_format($total, 0, ',', '.'); ?> WC</strong></div>
                <?php if ($wa !== '') { ?><a href="<?php echo nexBenefitsText($wa); ?>" target="_blank" rel="noopener noreferrer"><?php echo nexBenefitsText($settings['whatsapp_label'] ?? '', 'Consultar por WhatsApp'); ?></a><?php } ?>
            </article>
        <?php } ?></div><?php } ?>
    </section>
    <?php } ?>

    <?php if (empty($visible)) { ?>
        <div class="nex-benefits-empty">
            <h2>Sin beneficios publicados para <?php echo nexBenefitsText($realmLabel); ?></h2>
            <p>Cuando una recompensa o promoción entre en vigencia aparecerá aquí con sus condiciones.</p>
        </div>
    <?php } else { ?>
        <div class="nex-benefits-grid">
        <?php foreach ($visible as $item) {
            $image = nexBenefitsImage($item['image'] ?? '');
            $type = preg_replace('/[^a-z]/', '', strtolower((string)($item['type'] ?? 'benefit')));
            $highlights = preg_split('/\r\n|\r|\n/', (string)($item['highlights'] ?? ''));
            $ctaUrl = nexBenefitsUrl($item['cta_url'] ?? '');
        ?>
            <article class="nex-benefit-card nex-benefit-card--<?php echo nexBenefitsText($type, 'benefit'); ?><?php echo !empty($item['featured']) ? ' is-featured' : ''; ?>">
                <?php if ($image !== '') { ?>
                    <button class="nex-benefit-card__visual" type="button" data-nex-benefit-open data-image="<?php echo nexBenefitsText($image); ?>" data-title="<?php echo nexBenefitsText($item['title'] ?? 'Beneficio'); ?>">
                        <img src="<?php echo nexBenefitsText($image); ?>" alt="<?php echo nexBenefitsText($item['title'] ?? 'Beneficio Nexora'); ?>" loading="lazy" decoding="async">
                        <span>Ampliar información</span>
                    </button>
                <?php } ?>
                <div class="nex-benefit-card__body">
                    <div class="nex-benefit-card__meta">
                        <span class="nex-benefit-badge"><?php echo nexBenefitsText($item['badge'] ?? '', strtoupper($type)); ?></span>
                        <span><?php echo nexBenefitsText(($item['realm'] ?? '') === 'both' ? 'Legado + Seasonal' : $realmLabel); ?></span>
                    </div>
                    <h2><?php echo nexBenefitsText($item['title'] ?? '', 'Beneficio Nexora'); ?></h2>
                    <p><?php echo nexBenefitsText($item['description'] ?? ''); ?></p>
                    <?php if (!empty($highlights)) { ?><ul>
                        <?php foreach ($highlights as $line) { if (trim($line) !== '') { ?><li><?php echo nexBenefitsText($line); ?></li><?php } } ?>
                    </ul><?php } ?>
                    <div class="nex-benefit-card__footer">
                        <?php if (!empty($item['end_at'])) { ?><span>Vigente hasta <strong><?php echo nexBenefitsText($item['end_at']); ?></strong></span><?php } else { ?><span>Estado <strong>Activo</strong></span><?php } ?>
                        <?php if ($ctaUrl !== '') { ?><a href="<?php echo nexBenefitsText($ctaUrl); ?>"><?php echo nexBenefitsText($item['cta_label'] ?? '', 'Consultar'); ?></a><?php } ?>
                    </div>
                </div>
            </article>
        <?php } ?>
        </div>
    <?php } ?>

    <footer class="nex-benefits-trust">
        <div><span>Información oficial</span><p><?php echo nexBenefitsText($settings['notice'] ?? '', 'Consulta las condiciones antes de elegir.'); ?></p></div>
        <?php $mainCta = nexBenefitsUrl($settings['cta_url'] ?? ''); if ($mainCta !== '') { ?><a class="nex-benefits-main-cta" href="<?php echo nexBenefitsText($mainCta); ?>"><?php echo nexBenefitsText($settings['cta_label'] ?? '', 'Ir a donaciones'); ?></a><?php } ?>
    </footer>

    <div class="nex-benefit-lightbox" data-nex-benefit-lightbox aria-hidden="true" role="dialog" aria-modal="true">
        <button type="button" class="nex-benefit-lightbox__backdrop" data-nex-benefit-close aria-label="Cerrar"></button>
        <div class="nex-benefit-lightbox__panel"><button type="button" data-nex-benefit-close aria-label="Cerrar">&times;</button><strong data-nex-benefit-title></strong><img src="" alt="" data-nex-benefit-image></div>
    </div>
</section>
<script>
(function(){
  var box=document.querySelector('[data-nex-benefit-lightbox]'); if(!box)return;
  var img=box.querySelector('[data-nex-benefit-image]'), title=box.querySelector('[data-nex-benefit-title]');
  document.querySelectorAll('[data-nex-benefit-open]').forEach(function(btn){btn.addEventListener('click',function(){img.src=btn.getAttribute('data-image');img.alt=btn.getAttribute('data-title');title.textContent=btn.getAttribute('data-title');box.setAttribute('aria-hidden','false');document.body.classList.add('nex-modal-open');});});
  box.querySelectorAll('[data-nex-benefit-close]').forEach(function(btn){btn.addEventListener('click',function(){box.setAttribute('aria-hidden','true');img.src='';document.body.classList.remove('nex-modal-open');});});
  document.addEventListener('keydown',function(e){if(e.key==='Escape'&&box.getAttribute('aria-hidden')==='false')box.querySelector('[data-nex-benefit-close]').click();});
})();
</script>
