<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/billing.php';
require_once __DIR__ . '/kyc_helpers.php';

$auth = getAuth();
$auth->requireAuth();
$user = $auth->getCurrentUser();
$db = getDatabaseConnection();
requireKycVerified($db, $user['id']);

$plan      = getPlanByCode($_GET['plan'] ?? null);
$pub       = getenv('WOMPI_PUBLIC_KEY');
$secret    = getenv('WOMPI_INTEGRITY_SECRET');
$currency  = getenv('WOMPI_CURRENCY') ?: 'COP';
$amount    = (int) ($plan['wompi_amount_cents'] ?? 0); // en centavos
if ($amount <= 0) {
    // Fallback: usa valor general o el total del plan.
    $amount = envInt('WOMPI_PLAN_AMOUNT_IN_CENTS', (int)($plan['total_cop'] * 100));
}

if (!$pub || !$secret) {
    http_response_code(500);
    echo 'Wompi no está configurado. Falta WOMPI_PUBLIC_KEY o WOMPI_INTEGRITY_SECRET.';
    exit;
}  

$reference = 'sub_' . $plan['code'] . '_uid_' . $user['id'] . '_' . bin2hex(random_bytes(6));
$redirect  = rtrim(getenv('BASE_URL') ?: '', '/') . '/subscription?message=' . urlencode('Pago realizado. Procesando activación...');

// Wompi integrity signature: SHA256(reference + amountInCents + currency + integritySecret)
$signature = hash('sha256', $reference . $amount . $currency . $secret);
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="icon" href="graphics/signatureicon.ico" type="image/x-icon">
  <link rel="shortcut icon" href="graphics/signatureicon.ico" type="image/x-icon">
  <title>Activar Suscripción - Wompi</title>
  <script src="https://checkout.wompi.co/widget.js"></script>
  <style>
    body { font-family: Segoe UI, Tahoma, sans-serif; background:#f6f8fb; padding:40px; }
    .card { max-width:560px; margin:0 auto; background:#fff; border-radius:12px; padding:24px; box-shadow:0 8px 30px rgba(0,0,0,.08); }
    .btn { display:inline-block; padding:12px 18px; border-radius:8px; background:#29648D; color:#fff; text-decoration:none; font-weight:600; border:none; cursor:pointer; }
    .btn-secondary { background:#6b7280; }
    .hint { color:#6b7280; font-size:.9rem; margin-top:12px; }
  </style>
</head>
<body>
  <div class="card">
    <h2>Activar Suscripción</h2>
    <p>Serás dirigido a Wompi para completar el pago del plan <?php echo htmlspecialchars($plan['name']); ?>.</p>

    <button class="btn" type="button" id="wompiCheckoutBtn">
      Pagar con Wompi
    </button>
    <a class="btn btn-secondary" href="subscription" style="margin-left:8px; text-decoration:none;">
      Volver
    </a>

    <p class="hint">Si no se abre automáticamente, haz clic en el botón.</p>
  </div>

  <script>
    const publicKey   = <?php echo json_encode($pub); ?>;
    const currency    = <?php echo json_encode($currency); ?>;
    const amountCents = <?php echo (int)$amount; ?>;
    const reference   = <?php echo json_encode($reference); ?>;
    const redirectUrl = <?php echo json_encode($redirect); ?>;
    const integrity   = <?php echo json_encode($signature); ?>;

    function openWompiCheckout() {
      if (typeof WidgetCheckout === 'undefined') {
        alert('No se pudo cargar el checkout de Wompi. Revisa tu conexión o desactiva bloqueadores de anuncios.');
        return;
      }

      const checkout = new WidgetCheckout({
        currency: currency,
        amountInCents: amountCents,
        reference: reference,
        publicKey: publicKey,
        redirectUrl: redirectUrl,
        signature: {
          integrity: integrity
        }
      });

      checkout.open(function (result) {
        console.log('Wompi result:', result);
      });
    }

    document.addEventListener('DOMContentLoaded', function () {
      const btn = document.getElementById('wompiCheckoutBtn');
      if (btn) {
        btn.addEventListener('click', openWompiCheckout);
        openWompiCheckout();
      }
    });
  </script>
</body>
</html>
