<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(dirname(__DIR__)))); }
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';
require_once BASE_PATH . '/api/shared/ApiLoader.php';
if (!isLoggedIn()) { header('Location: ' . route_url(['module'=>'auth','action'=>'login'])); exit; }
$page_title = 'Checkout Big4pay';
$active = 'checkout_big4pay';
ob_start();
?>
<div class="checkout-page">
  <h3 class="page-title">Checkout Big4pay</h3>
  <p class="page-subtitle">Inicia el pago con tus datos de depósito</p>
  <div class="card">
    <div class="card-body">
      <div class="filters-grid">
        <input id="amountInput" class="form-input" type="number" step="0.01" min="1" placeholder="Monto" />
        <select id="currencySelect" class="form-select"><option value="USD">USD</option><option value="MXN">MXN</option></select>
      </div>
      <div id="statusBox" class="alert" style="display:none"></div>
      <div class="checkout-actions"><button id="startCheckoutBtn" class="btn btn-primary">Iniciar Checkout</button></div>
    </div>
  </div>
</div>
<script>
const BASE_PFX = (location.pathname.indexOf('/simple_crm/') !== -1) ? '/simple_crm' : ''
function qs(id){ return document.getElementById(id) }
document.addEventListener('DOMContentLoaded', ()=>{
  const qp = new URLSearchParams(location.search)
  const amtQ = qp.get('amount')
  const curQ = qp.get('currency')
  const clientQ = qp.get('client_id')
  const accQ = qp.get('account_number')
  if (amtQ) { const a = parseFloat(amtQ); if (Number.isFinite(a) && a>0) { qs('amountInput').value = String(a) } }
  if (curQ) { const c = String(curQ).toUpperCase(); if (qs('currencySelect')) qs('currencySelect').value = c }
  window.CP_CLIENT_ID = clientQ ? parseInt(clientQ,10) : null
  window.CP_ACCOUNT_NUMBER = accQ || null
  qs('startCheckoutBtn').addEventListener('click', async ()=>{
    const status = qs('statusBox'); status.style.display='none'
    const amt = parseFloat(qs('amountInput').value||'0')
    const cur = String(qs('currencySelect').value||'USD').toUpperCase()
    if (!Number.isFinite(amt) || amt<=0){ status.className='alert alert-error'; status.textContent='Monto inválido'; status.style.display='block'; return }
    try{
      const params = new URLSearchParams()
      params.set('currency', cur)
      params.set('amount', String(amt))
      if (window.CP_CLIENT_ID) params.set('client_id', String(window.CP_CLIENT_ID))
      if (window.CP_ACCOUNT_NUMBER) params.set('account_number', String(window.CP_ACCOUNT_NUMBER))
      const r = await fetch(BASE_PFX + '/modules/checkout/big4pay/actions.php?action=initiate_big4pay_checkout', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: params.toString() })
      const d = await r.json()
      if (d && d.success){
        const url = d.redirect_url || d.checkout_url || (d.json && (d.json.redirect_url || d.json.checkout_url || d.json.payment_link))
        if (url){ window.open(url, '_blank', 'noopener'); status.className='alert alert-success'; status.textContent='Checkout iniciado'; status.style.display='block' } else { status.className='alert alert-error'; status.textContent='No se recibió URL de checkout'; status.style.display='block' }
      } else { status.className='alert alert-error'; status.textContent = d.message || 'Error iniciando checkout'; status.style.display='block' }
    }catch(e){ status.className='alert alert-error'; status.textContent='Error de conexión'; status.style.display='block' }
  })
})
</script>
<style>
.checkout-page .filters-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-bottom:10px}
.form-input,.form-select{padding:10px;border:1px solid #e5e7eb;border-radius:10px;background:#fff;color:#111}
.form-input::placeholder{color:#777}
.btn.btn-primary{background:linear-gradient(180deg,#2ea6ff,#1b7bd3);border:0;border-radius:10px;padding:10px 12px;color:#fff}
.alert{margin-top:10px}
</style>
<?php
$content = ob_get_clean();
include BASE_PATH . '/modules/checkout/layout_public.php';
?>
