<?php
require_once 'auth.php';
require_once __DIR__ . '/billing.php';
require_once __DIR__ . '/kyc_helpers.php';
//
$auth = getAuth();
$auth->requireAuth();
$user = $auth->getCurrentUser();
$db = getDatabaseConnection();
$sub = getUserSubscription($db, $user['id']);
$active = isSubscriptionActive($sub);
$kyc = getUserKyc($db, $user['id']); 
$needsKyc = ($kyc['kyc_estado'] ?? 'no_iniciado') !== 'verificado';
$msg = isset($_GET['message']) ? htmlspecialchars($_GET['message']) : null; 
$plans = getPlanCatalog();
$selectedPlan = getPlanByCode($_GET['plan'] ?? null);
$provider = getenv('PAYMENT_PROVIDER');
if (!$provider) {
  // Auto-pick provider based on available keys: Wompi > MP > Stripe 
  if (getenv('WOMPI_PUBLIC_KEY')) {
    $provider = 'wompi';
  } elseif (getenv('MP_ACCESS_TOKEN')) {
    $provider = 'mercadopago';
  } else {
    $provider = 'stripe';  
  } 
}
$subscribePath = $provider === 'mercadopago'
    ? 'create_mp_preapproval.php'
    : ($provider === 'wompi' ? 'create_wompi_checkout.php' : 'create_checkout_session.php');
?> 
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Suscripción</title>
  <style>
    body { margin:0; font-family: Segoe UI, Tahoma, sans-serif; background:#f6f8fb; }
    .container { max-width: 760px; margin: 40px auto; background:#fff; border-radius:12px; box-shadow: 0 8px 30px rgba(0,0,0,.08); overflow:hidden; }
    .header { background: linear-gradient(135deg, #29648D 0%, #29648D 100%); padding:22px; color:#fff; }
    .content { padding: 24px; }
    .btn { display:inline-block; padding:12px 18px; border-radius:8px; text-decoration:none; font-weight:600; }
    .btn-primary { background:#29648D; color:#fff; }
    .btn-outline { border:2px solid #29648D; color:#29648D; }
    .alert { padding:12px 14px; border-radius:8px; margin-bottom:14px; }
    .alert.info { background:#eef2ff; color:#1e3a8a; border:1px solid #c7d2fe; }
    .alert.success { background:#ecfdf5; color:#065f46; border:1px solid #a7f3d0; }
    .row { display:flex; gap:16px; align-items:center; }
    .row > div { flex:1; }
    .label { color:#6b7280; font-size:.9rem; }
    .value { font-weight:600; }
    .plans-grid { display:grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap:16px; margin-top:16px; }
    .plan-card { border:1px solid #e5e7eb; border-radius:12px; padding:16px; background:#f9fbff; position:relative; box-shadow:0 10px 24px rgba(41,100,141,0.08); }
    .plan-card.selected { border-color:#29648D; box-shadow:0 10px 30px rgba(41,100,141,0.14); }
    .plan-badge { position:absolute; top:12px; right:12px; background:#e0e7ff; color:#1e3a8a; padding:6px 10px; border-radius:999px; font-size:0.85rem; font-weight:700; }
    .plan-name { font-size:1.1rem; font-weight:700; color:#1f2937; margin-bottom:6px; }
    .plan-price { font-size:1.4rem; color:#29648D; font-weight:800; }
    .plan-meta { color:#4b5563; margin:4px 0; }
    .plan-foot { margin-top:12px; display:flex; align-items:center; justify-content:space-between; gap:8px; flex-wrap:wrap; }
    .plan-btn { width:100%; text-align:center; }
    .info-note { background:#f1f5f9; color:#475569; border:1px solid #e2e8f0; border-radius:10px; padding:12px 14px; margin-top:18px; }
    @media (max-width: 600px) {
      .container { margin: 16px; }
    }
  </style>
  <?php if (($provider === 'stripe') && defined('STRIPE_PUBLISHABLE_KEY')): ?>
    <script src="https://js.stripe.com/v3/"></script>
    <script>
      const pk = '<?php echo htmlspecialchars(STRIPE_PUBLISHABLE_KEY); ?>';
    </script>
  <?php endif; ?>
  </head>
<body>
  <div class="container">
    <div class="header">
      <h2>Suscripción</h2>
    </div>
    <div class="content">
      <?php if ($msg): ?>
        <div class="alert info"><?php echo $msg; ?></div>
      <?php endif; ?>
      <?php if ($active): ?>
        <div class="alert success">Tu suscripción está activa.</div>
        <div class="row">
          <div>
            <div class="label">Estado</div>
            <div class="value"><?php echo htmlspecialchars($sub['status']); ?></div>
          </div>
          <div>
            <div class="label">Vence</div>
            <div class="value"><?php echo htmlspecialchars($sub['current_period_end']); ?></div>
          </div>
        </div>
        <?php if ($provider === 'stripe'): ?>
          <p style="margin-top:16px;">
            <a class="btn btn-outline" href="create_billing_portal_session.php">Administrar Facturación</a>
          </p>
        <?php else: ?>
          <p style="margin-top:16px; color:#555;">
            Para gestionar tu suscripción usa el portal de tu medio de pago o contáctanos.
          </p>
        <?php endif; ?>
      <?php else: ?>
        <?php if ($needsKyc): ?>
          <div class="alert info">Primero debemos verificar tu identidad (Didit). No almacenamos tu documento, solo el resultado.</div>
          <p>
            <a class="btn btn-primary" href="kyc.php">Verificar identidad</a>
          </p>
        <?php else: ?>
          <p>Para usar todas las funciones, activa una suscripción.</p>
          <p>
            <?php if ($provider === 'mercadopago'): ?>
              <a class="btn btn-primary" href="create_mp_preapproval.php">Suscribirme</a>
            <?php elseif ($provider === 'wompi'): ?>
              <a class="btn btn-primary" href="create_wompi_checkout.php">Suscribirme</a>
            <?php else: ?>
              <a class="btn btn-primary" href="create_checkout_session.php">Suscribirme</a>
            <?php endif; ?>
          </p>
        <?php endif; ?>
      <?php endif; ?>
      <p style="margin-top:24px;"><a href="index.php">Volver</a></p>
    </div>
  </div>
</body>
</html>
