<?php
/**
 * WebEngine CMS - PayPal Gateway (PAQUETES + IP en custom + ROUTER)
 * custom = userid|SITE|REALM|PACKID|IP|SIGNATURE
 * SITE = S6
 */

if(!isLoggedIn()) redirect(1,'login');
if(!mconfig('active')) throw new Exception(lang('error_47'));

// Title
echo '<div class="page-title"><span>'.lang('module_titles_txt_21').'</span></div>';

// Compat/Fallback display
echo '<span id="paypal_conversion_rate_value" style="display:none;">'.mconfig('paypal_conversion_rate').'</span>';

/** IP normalizada por la capa de proxies confiables de Nexora. */
$userIp = class_exists('NexoraSecurity') ? NexoraSecurity::clientIp() : ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
$realmId = NexoraRealm::accountRealm();
if(!NexoraRealm::exists($realmId)) throw new Exception('La sesión no tiene un reino válido.');

/**
 * Texto "Créditos/WC" desde lang, ya listo para JS
 */
$creditLabel = lang('donation_txt_2'); // por ejemplo: "Credits" o "WC"
$creditLabelJs = json_encode($creditLabel, JSON_UNESCAPED_UNICODE); // comillas y escapes seguros

/**
 * Paquetes
 */
$packages = [
    'P100'  => ['usd' => 1.00,  'base' => 1000,  'bonus' => 0,   'total' => 1000,  'label' => '1.000 WC — $1.00 — sin bonus — Total: 1.000 WC'],
    'P200'  => ['usd' => 1.99,  'base' => 2000,  'bonus' => 0,   'total' => 2000,  'label' => '2.000 WC — $1.99 — sin bonus — Total: 2.000 WC'],
    'P300'  => ['usd' => 2.99,  'base' => 3000,  'bonus' => 0,   'total' => 3000,  'label' => '3.000 WC — $2.99 — sin bonus — Total: 3.000 WC'],
    'P400'  => ['usd' => 3.99,  'base' => 4000,  'bonus' => 0,   'total' => 4000,  'label' => '4.000 WC — $3.99 — sin bonus — Total: 4.000 WC'],
    'P550'  => ['usd' => 4.99,  'base' => 5000,  'bonus' => 500,  'total' => 5500,  'label' => '5.000 WC — $4.99 — 10% (500 WC) — Total: 5.500 WC'],
    'P781'  => ['usd' => 6.99,  'base' => 7000,  'bonus' => 810,  'total' => 7810,  'label' => '7.000 WC — $6.99 — 11.5% (810 WC) — Total: 7.810 WC'],
    'P1125' => ['usd' => 9.99,  'base' => 10000, 'bonus' => 1250, 'total' => 11250, 'label' => '10.000 WC — $9.99 — 12.5% (1.250 WC) — Total: 11.250 WC'],
    'P1703' => ['usd' => 14.99, 'base' => 15000, 'bonus' => 2030, 'total' => 17030, 'label' => '15.000 WC — $14.99 — 13.5% (2.030 WC) — Total: 17.030 WC'],
    'P2290' => ['usd' => 19.99, 'base' => 20000, 'bonus' => 2900, 'total' => 22900, 'label' => '20.000 WC — $19.99 — 14.5% (2.900 WC) — Total: 22.900 WC'],
    'P2888' => ['usd' => 24.99, 'base' => 25000, 'bonus' => 3880, 'total' => 28880, 'label' => '25.000 WC — $24.99 — 15.5% (3.880 WC) — Total: 28.880 WC'],
    'P3495' => ['usd' => 29.99, 'base' => 30000, 'bonus' => 4950, 'total' => 34950, 'label' => '30.000 WC — $29.99 — 16.5% (4.950 WC) — Total: 34.950 WC'],
    'P5925' => ['usd' => 49.99, 'base' => 50000, 'bonus' => 9250, 'total' => 59250, 'label' => '50.000 WC — $49.99 — 18.5% (9.250 WC) — Total: 59.250 WC'],
];

// Default pack
reset($packages);
$defaultPackId = key($packages);
$defaultUsd    = number_format($packages[$defaultPackId]['usd'], 2, '.', '');
$defaultTotal  = (int)$packages[$defaultPackId]['total'];

// Form action
$formAction = (mconfig('paypal_enable_sandbox') ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr');

// Order id
$order_id = hash('sha256', uniqid((string)$_SESSION['userid'].'_', true));

// SITE CODE para router
$siteCode = 'S6';

// Cada paquete lleva una firma propia; el navegador no puede fabricar otra combinación.
$customByPack = array();
foreach($packages as $packId => $packageData) {
	$signature = nexoraPaypalCustomSignature($_SESSION['userid'], $siteCode, $realmId, $packId, $userIp, $order_id);
	$customByPack[$packId] = (int)$_SESSION['userid'].'|'.$siteCode.'|'.$realmId.'|'.$packId.'|'.$userIp.'|'.$signature;
}
$defaultCustom = $customByPack[$defaultPackId];

// ROUTER URL (IPN GLOBAL / BOTÓN)
$routerUrl = 'https://s6.nexoravenetworks.com/api/ipn-router.php';

echo '
<style>
.paypal-gateway-container{max-width:980px;margin:0 auto;}
.paypal-gateway-content{padding:18px;border-radius:12px;background:rgba(255,255,255,.92);border:1px solid rgba(0,0,0,.08);}
.paypal-gateway-logo{height:70px;background-position:center;background-repeat:no-repeat;background-size:contain;margin-bottom:8px;}
.paypal-pack-title{font-weight:700;font-size:16px;margin:10px 0 12px;color:#1a1a1a;}
.paypal-pack-list{display:flex;flex-direction:column;gap:10px;margin:0;padding:0;list-style:none;}
.paypal-pack-item{display:flex;align-items:center;gap:12px;padding:12px 14px;border-radius:12px;border:1px solid rgba(0,0,0,.12);background:#fff;cursor:pointer;transition:transform .08s ease, box-shadow .08s ease, border-color .08s ease;}
.paypal-pack-item:hover{transform:translateY(-1px);box-shadow:0 6px 18px rgba(0,0,0,.08);border-color:rgba(0,0,0,.22);}
.paypal-pack-item input{transform:scale(1.15);cursor:pointer;}
.paypal-pack-text{font-size:14px;color:#111;line-height:1.2;}
.paypal-pack-badges{margin-left:auto;display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end;}
.badge{display:inline-block;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:700;background:rgba(0,0,0,.06);color:#111;}
.badge.usd{background:rgba(0,123,255,.12);color:#0b4ea3;}
.badge.total{background:rgba(255,193,7,.18);color:#7a5200;}
.paypal-summary{margin-top:14px;padding:12px 14px;border-radius:12px;background:rgba(0,0,0,.04);border:1px solid rgba(0,0,0,.10);display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;}
.paypal-summary b{font-size:14px;color:#111;}
.paypal-summary .muted{font-size:12px;color:#555;}
.paypal-btn{appearance:none;border:0;border-radius:12px;padding:12px 16px;font-weight:800;cursor:pointer;background:#ffc439;color:#111;box-shadow:0 10px 22px rgba(0,0,0,.14);transition:transform .08s ease;}
.paypal-btn:hover{transform:translateY(-1px);}
.paypal-note{margin-top:10px;font-size:12px;color:#666;}
</style>
';

echo '<div class="paypal-gateway-container">';
echo '  <div class="paypal-gateway-content">';
echo '    <div class="paypal-gateway-logo"></div>';
echo '    <div class="paypal-pack-title">Selecciona tu paquete:</div>';

echo '    <form action="'.$formAction.'" method="post" id="paypalPackForm">';

echo '      <input type="hidden" name="cmd" value="_xclick" />';
echo '      <input type="hidden" name="business" value="'.htmlspecialchars(mconfig('paypal_email'), ENT_QUOTES, 'UTF-8').'" />';
echo '      <input type="hidden" name="item_name" value="'.htmlspecialchars(mconfig('paypal_title'), ENT_QUOTES, 'UTF-8').'" />';
echo '      <input type="hidden" name="item_number" value="'.$order_id.'" />';
echo '      <input type="hidden" name="currency_code" value="'.htmlspecialchars(mconfig('paypal_currency'), ENT_QUOTES, 'UTF-8').'" />';

echo '      <input type="hidden" name="no_shipping" value="1" />';
echo '      <input type="hidden" name="shipping" value="0.00" />';
echo '      <input type="hidden" name="return" value="'.htmlspecialchars(mconfig('paypal_return_url'), ENT_QUOTES, 'UTF-8').'" />';
echo '      <input type="hidden" name="cancel_return" value="'.htmlspecialchars(mconfig('paypal_return_url'), ENT_QUOTES, 'UTF-8').'" />';

// ✅ IMPORTANTE: notify_url ahora apunta al ROUTER
echo '      <input type="hidden" name="notify_url" value="'.htmlspecialchars($routerUrl, ENT_QUOTES, 'UTF-8').'" />';

echo '      <input type="hidden" name="no_note" value="1" />';
echo '      <input type="hidden" name="tax" value="0.00" />';

// amount + custom firmado (userid|SITE|realm|pack|ip|signature)
echo '      <input type="hidden" name="amount" id="paypal_amount" value="'.$defaultUsd.'" />';
echo '      <input type="hidden" name="custom" id="paypal_custom" value="'.htmlspecialchars($defaultCustom, ENT_QUOTES, 'UTF-8').'" />';

echo '      <ul class="paypal-pack-list" id="paypalPackList">';
foreach($packages as $packId => $p) {
    $usd     = number_format((float)$p['usd'], 2, '.', '');
    $total   = (int)$p['total'];
    $checked = ($packId === $defaultPackId) ? 'checked' : '';
    $safeLabel = htmlspecialchars($p['label'], ENT_QUOTES, 'UTF-8');

    echo '
      <li class="paypal-pack-item" data-pack="'.$packId.'" data-usd="'.$usd.'" data-total="'.$total.'" data-custom="'.htmlspecialchars($customByPack[$packId], ENT_QUOTES, 'UTF-8').'">
        <input type="radio" name="pack_radio" '.$checked.' />
        <div class="paypal-pack-text">'.$safeLabel.'</div>
        <div class="paypal-pack-badges">
            <span class="badge usd">$'.$usd.' '.htmlspecialchars(mconfig('paypal_currency'), ENT_QUOTES, 'UTF-8').'</span>
            <span class="badge total">Total: '.$total.' '.htmlspecialchars($creditLabel, ENT_QUOTES, 'UTF-8').'</span>
        </div>
      </li>
    ';
}
echo '      </ul>';

echo '
      <div class="paypal-summary">
        <div>
          <b>Seleccionado:</b>
          <span id="paypal_selected_text">$'.$defaultUsd.' = '.$defaultTotal.' '.htmlspecialchars($creditLabel, ENT_QUOTES, 'UTF-8').'</span><br>
          <span class="muted">Nota: El crédito se acredita automáticamente cuando PayPal confirme el pago (IPN).</span>
        </div>
        <button type="submit" class="paypal-btn">Continuar a PayPal</button>
      </div>
    </form>
  </div>
</div>
';

// JS seguro: creditLabel viene en JSON ya escapado
echo '
<script>
(function(){
  const creditLabel = '.$creditLabelJs.';
  const list = document.getElementById("paypalPackList");
  const amountEl = document.getElementById("paypal_amount");
  const customEl = document.getElementById("paypal_custom");
  const selectedText = document.getElementById("paypal_selected_text");

  function setSelected(li){
    const packId = li.getAttribute("data-pack");
    const usd = li.getAttribute("data-usd");
    const total = li.getAttribute("data-total");

    // radios
    const radios = list.querySelectorAll("input[type=radio]");
    radios.forEach(r => r.checked = false);
    li.querySelector("input[type=radio]").checked = true;

    // amount
    amountEl.value = usd;

    // Firma ya generada por PHP para esta cuenta, reino, orden y paquete.
    customEl.value = li.getAttribute("data-custom") || "";

    // UI
    selectedText.textContent = "$" + usd + " = " + total + " " + creditLabel;
  }

  list.querySelectorAll(".paypal-pack-item").forEach(li => {
    li.addEventListener("click", function(){ setSelected(li); });
  });
})();
</script>
';
