<?php
/**
 * upgrade_modal() — modal de selección de plan con precios
 * Incluir antes de </body>. Se abre con: document.getElementById('upgrade-modal').style.display='flex'
 */
function upgrade_modal(): void {
    $pub_key = defined('STRIPE_PUBLISHABLE_KEY') ? STRIPE_PUBLISHABLE_KEY : '';
    $plans = [
        'starter'    => ['name'=>'Starter',    'price'=>49,  'color'=>'#3b82f6', 'features'=>['1 cliente','3 módulos a elegir','1 usuario','Soporte email']],
        'pro'        => ['name'=>'Pro',         'price'=>200, 'color'=>'#8b5cf6', 'features'=>['5 clientes','Todos los módulos','3 usuarios','Soporte prioritario'], 'popular'=>true],
        'agency'     => ['name'=>'Agency',      'price'=>280, 'color'=>'#f59e0b', 'features'=>['7 clientes','Todos los módulos','8 usuarios','Soporte prioritario']],
        'enterprise' => ['name'=>'Enterprise',  'price'=>500, 'color'=>'#10b981', 'features'=>['15 clientes','Todos los módulos','20 usuarios','Soporte WhatsApp incluido']],
    ];
?>
<div id="upgrade-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:9999;align-items:center;justify-content:center;padding:20px">
  <div style="background:#111;border-radius:16px;padding:32px;max-width:900px;width:100%;max-height:90vh;overflow-y:auto">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
      <h2 style="margin:0;color:#fff;font-size:22px">Elige tu plan</h2>
      <span onclick="document.getElementById('upgrade-modal').style.display='none'" style="cursor:pointer;color:#888;font-size:24px">×</span>
    </div>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:16px">
      <?php foreach ($plans as $plan_id => $p): ?>
      <div style="border:2px solid <?=$p['color']?>;border-radius:12px;padding:20px;position:relative;<?=($p['popular']??false)?'background:rgba(139,92,246,.1)':''?>">
        <?php if ($p['popular']??false): ?>
        <div style="position:absolute;top:-12px;left:50%;transform:translateX(-50%);background:<?=$p['color']?>;color:#fff;padding:3px 12px;border-radius:20px;font-size:11px;font-weight:700;white-space:nowrap">MÁS POPULAR</div>
        <?php endif; ?>
        <div style="color:<?=$p['color']?>;font-weight:700;font-size:16px;margin-bottom:6px"><?=$p['name']?></div>
        <div style="font-size:28px;font-weight:800;color:#fff;margin-bottom:12px">$<?=$p['price']?><span style="font-size:14px;color:#888">/mes</span></div>
        <?php foreach ($p['features'] as $f): ?>
        <div style="font-size:13px;color:#aaa;margin-bottom:4px">✓ <?=$f?></div>
        <?php endforeach; ?>
        <button
          onclick="startCheckout('<?=$plan_id?>')"
          style="width:100%;margin-top:16px;padding:10px;background:<?=$p['color']?>;color:#fff;border:none;border-radius:8px;font-weight:700;cursor:pointer;font-size:14px">
          Activar <?=$p['name']?>
        </button>
      </div>
      <?php endforeach; ?>
    </div>
    <p style="color:#555;font-size:12px;text-align:center;margin-top:20px">Todos los planes incluyen 7 días de prueba gratis. Cancela cuando quieras.</p>
  </div>
</div>
<script>
async function startCheckout(plan) {
  const btn = event.target;
  btn.disabled = true; btn.textContent = 'Procesando...';
  try {
    const r = await fetch('/supercerebro/api/billing.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: 'action=create_checkout&plan='+plan+'&csrf_token='+(document.querySelector('meta[name="dm-csrf"]')?.content||'')
    });
    const d = await r.json();
    if (d.url) window.location.href = d.url;
    else alert(d.error || 'Error al crear sesión de pago.');
  } catch(e) { alert('Error de conexión.'); }
  btn.disabled = false;
}

async function openBillingPortal() {
  try {
    const csrf = document.querySelector('meta[name="dm-csrf"]')?.content || '';
    const r = await fetch('/supercerebro/api/billing.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: 'action=portal&csrf_token=' + encodeURIComponent(csrf)
    });
    const d = await r.json();
    if (d.url) window.location.href = d.url;
    else alert(d.error || 'No se pudo abrir el portal de facturación.');
  } catch(e) { alert('Error de conexión.'); }
}

// Mostrar modal upgrade automáticamente si viene de ?upgrade=1
if (new URLSearchParams(location.search).get('upgrade') === '1') {
  document.addEventListener('DOMContentLoaded', () => {
    const m = document.getElementById('upgrade-modal');
    if (m) m.style.display = 'flex';
    // limpiar el parámetro para que un reload no reabra el modal
    try { history.replaceState({}, '', location.pathname); } catch(e) {}
  });
}

// Cerrar el modal al hacer clic en el fondo (backdrop) o con la tecla Escape
document.addEventListener('DOMContentLoaded', () => {
  const m = document.getElementById('upgrade-modal');
  if (!m) return;
  m.addEventListener('click', (e) => { if (e.target === m) m.style.display = 'none'; });
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape') m.style.display = 'none'; });
});

// Mostrar toast si viene de ?checkout=success
if (new URLSearchParams(location.search).get('checkout') === 'success') {
  document.addEventListener('DOMContentLoaded', () => {
    const plan = new URLSearchParams(location.search).get('plan') || '';
    const msg = '🎉 ¡Suscripción activada' + (plan ? ' — plan ' + plan.charAt(0).toUpperCase()+plan.slice(1) : '') + '! Bienvenido a Brain.';
    if (typeof showToast === 'function') showToast(msg, 'var(--g)');
    else { const b=document.createElement('div'); b.style.cssText='position:fixed;bottom:24px;right:24px;background:#166534;color:#fff;padding:14px 22px;border-radius:10px;font-size:14px;z-index:99999;box-shadow:0 4px 20px rgba(0,0,0,.4)'; b.textContent=msg; document.body.appendChild(b); setTimeout(()=>b.remove(),6000); }
    history.replaceState({}, '', location.pathname);
  });
}

async function requestImplementation() {
  const btn = event.target;
  const orig = btn.textContent;
  btn.disabled = true; btn.textContent = 'Procesando...';
  try {
    const csrf = document.querySelector('meta[name="dm-csrf"]')?.content || '';
    const r = await fetch('/supercerebro/api/billing.php', {
      method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: 'action=request_implementation&csrf_token=' + csrf
    });
    const d = await r.json();
    if (d.url) window.location.href = d.url;
    else alert(d.error || 'Error al procesar.');
  } catch(e) { alert('Error de conexion.'); }
  btn.disabled = false; btn.textContent = orig;
}

async function buyModulesAddon() {
  const csrf = document.querySelector('meta[name="dm-csrf"]')?.content || '';
  try {
    const r = await fetch('/supercerebro/api/billing.php', {
      method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: 'action=create_checkout&plan=starter&addons=%7B%22modules_extra%22%3Atrue%7D&csrf_token=' + csrf
    });
    const d = await r.json();
    if (d.url) window.location.href = d.url;
    else alert(d.error || 'Error.');
  } catch(e) { alert('Error de conexion.'); }
}

async function buyProposals(qty) {
  const csrf = document.querySelector('meta[name="dm-csrf"]')?.content || '';
  try {
    const r = await fetch('/supercerebro/api/billing.php', {
      method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: 'action=buy_proposal&qty=' + qty + '&csrf_token=' + csrf
    });
    const d = await r.json();
    if (d.url) window.location.href = d.url;
    else alert(d.error || 'Error.');
  } catch(e) { alert('Error de conexion.'); }
}

async function loadBillingInfo() {
  const el = document.getElementById('billing-info');
  if (!el) return;
  try {
    const d = await fetch('/supercerebro/api/billing.php?action=get_status').then(r => r.json());
    const s = d.subscription;
    if (!s) { el.innerHTML = '<span style="color:var(--m)">Sin suscripcion activa.</span>'; return; }
    const sc = {trial:'#60a5fa',active:'#4ade80',past_due:'#f87171',canceled:'#94a3b8'};
    const sl = {trial:'Trial activo',active:'Activo',past_due:'Pago pendiente',canceled:'Cancelado'};
    el.innerHTML = '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px">'
      + '<div><div style="font-size:11px;color:var(--m);text-transform:uppercase;letter-spacing:.5px">Plan</div><div style="font-size:15px;font-weight:700;text-transform:capitalize;margin-top:2px">'+(s.plan||'—')+'</div></div>'
      + '<div><div style="font-size:11px;color:var(--m);text-transform:uppercase;letter-spacing:.5px">Estado</div><div style="font-size:15px;font-weight:700;color:'+(sc[s.status]||'#aaa')+';margin-top:2px">'+(sl[s.status]||s.status)+'</div></div>'
      + '<div><div style="font-size:11px;color:var(--m);text-transform:uppercase;letter-spacing:.5px">Propuestas</div><div style="font-size:15px;font-weight:700;margin-top:2px">'+(s.proposals_used||0)+' / '+(s.proposals_limit||0)+'<button onclick="buyProposals(5)" style="font-size:11px;padding:2px 8px;border-radius:5px;background:rgba(147,51,234,.15);border:1px solid rgba(147,51,234,.3);color:var(--p);cursor:pointer;margin-left:6px">+5 por $15</button></div></div>'
      + '</div>';
    if (s.plan === 'starter' && !(s.addons && s.addons.modules_extra)) {
      el.innerHTML += '<div style="margin-top:12px;padding:12px;border-radius:8px;background:rgba(147,51,234,.08);border:1px solid rgba(147,51,234,.2)"><div style="font-size:12px;color:#aaa;margin-bottom:8px">Tu plan Starter incluye <b style="color:#fff">3 módulos</b>. Amplía con 5 módulos extra.</div><button onclick="buyModulesAddon()" style="padding:6px 14px;border-radius:6px;font-size:12px;font-weight:700;background:rgba(147,51,234,.2);border:1px solid rgba(147,51,234,.4);color:#c084fc;cursor:pointer">+ 5 módulos extra &#8212; $25/mes</button></div>';
    }
  } catch(e) { el.innerHTML = '<span style="color:var(--red)">Error al cargar.</span>'; }
}

// Toast propuesta comprada
(function(){
  const params = new URLSearchParams(location.search);
  if (params.get('proposal_purchased')) {
    document.addEventListener('DOMContentLoaded', function() {
      const qty = params.get('proposal_purchased');
      const msg = qty + ' propuesta' + (qty>1?'s':'') + ' agregada' + (qty>1?'s':'') + ' a tu cuenta.';
      if (typeof showToast === 'function') showToast('✅ ' + msg, 'var(--g)');
      history.replaceState({}, '', location.pathname);
    });
  }
  if (params.get('impl_requested')) {
    document.addEventListener('DOMContentLoaded', function() {
      if (typeof showToast === 'function') showToast('🛠 Implementacion solicitada. Te contactamos en menos de 24h.', 'var(--teal)');
      history.replaceState({}, '', location.pathname);
    });
  }
})();

</script>
<?php
}
