<?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) {
    if (getenv('WOMPI_PUBLIC_KEY')) {
        $provider = 'wompi';
    } elseif (getenv('MP_ACCESS_TOKEN')) {
        $provider = 'mercadopago';
    } else {
        $provider = 'stripe';
    }
} 
 
$subscribePath = $provider === 'mercadopago'
    ? 'create_mp_preapproval'
    : ($provider === 'wompi' ? 'create_wompi_checkout' : 'create_checkout_session');
?>
<!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>Suscripción</title>
  <style>
    body { margin:0; font-family: Segoe UI, Tahoma, sans-serif; background:#f6f8fb; }
    .container { max-width: 780px; margin: 40px auto; background:#fff; border-radius:0 0 8px 8px; 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(240px, 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; display:flex; align-items:baseline; gap:6px; flex-wrap:wrap; }
    .plan-price-note { font-size:0.9rem; color:#4b5563; font-weight:700; }
    .plan-meta { color:#374151; margin:6px 0 4px; font-weight:600; line-height:1.4; }
    .plan-meta-muted { color:#4b5563; font-weight:500; margin-left:6px; }
    .plan-meta-label { font-size:0.9rem; color:#4b5563; font-weight:700; margin-top:8px; }
    .plan-features { margin:6px 0 10px; padding-left:18px; color:#374151; }
    .plan-features li { margin:2px 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">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">Verificar identidad</a>
          </p>
        <?php else: ?>
          <p>Elige un plan y activa tu suscripción.</p>
          <div class="plans-grid">
            <?php foreach ($plans as $plan): ?>
              <?php
                $isSelected = $plan['code'] === $selectedPlan['code'];
                $subscriptionLabel = ($plan['months'] ?? 0) >= 24 ? 'Suscripción por dos años' : 'Suscripción anual';
                $verificationMonths = (int)($plan['months'] ?? 0);
              ?>
              <div class="plan-card <?php echo $isSelected ? 'selected' : ''; ?>">
                <?php if (!empty($plan['badge'])): ?>
                  <div class="plan-badge"><?php echo htmlspecialchars($plan['badge']); ?></div>
                <?php endif; ?>
                <div class="plan-name"><?php echo htmlspecialchars($plan['name']); ?></div>
                <div class="plan-price">
                  <?php echo formatCop($plan['monthly_cop']); ?>
                  <span class="plan-price-note">Mes/Usuario</span>
                </div>
                <div class="plan-meta">
                  <?php echo $subscriptionLabel; ?> <?php echo formatCop($plan['total_cop']); ?>
                  <?php if (!empty($plan['unit_cost_cop'])): ?>
                    <span class="plan-meta-muted">a <?php echo formatCop($plan['unit_cost_cop']); ?> cada firma</span>
                  <?php endif; ?>
                </div>
                <div class="plan-meta-label">Beneficios:</div>   
                <ul class="plan-features">
                  <li>Hasta <?php echo number_format($plan['signatures'], 0, ',', '.'); ?> firmas</li>
                  <li><?php echo $verificationMonths; ?> meses de verificación</li>
                </ul>
                <div class="plan-foot">
                  <form action="<?php echo htmlspecialchars($subscribePath); ?>" method="get" style="width:100%;">
                    <input type="hidden" name="plan" value="<?php echo htmlspecialchars($plan['code']); ?>">
                    <button class="btn btn-primary plan-btn" type="submit">Elegir <?php echo htmlspecialchars($plan['name']); ?></button>
                  </form>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
          <div class="info-note">
            Vencida la suscripción a $49,999 por cada año para verificar firmas firmadas.
          </div>
        <?php endif; ?>
      <?php endif; ?>
      <p style="margin-top:24px;"><a href="./">Volver</a></p>
    </div>
  </div>
</body>
</html>
