<?php
require_once __DIR__ . '/functions.php';

$settings = getSettings();
$baseUrl  = rtrim($settings['base_url'] ?: BASE_URL, '/');

$sessionId     = $_GET['session_id'] ?? null;
$purchaseToken = $_GET['pt']         ?? null;

$giftcards   = [];
$errorMsg    = null;
$total       = 0;
$senderName  = '';
$senderEmail = '';
$emailSent   = false;
$pointsAdded = false;

if ($purchaseToken) {
  global $pdo;
  $stmt = $pdo->prepare("SELECT * FROM giftcards WHERE purchase_token = ?");
  $stmt->execute([$purchaseToken]);
  $giftcards = $stmt->fetchAll();

  if ($giftcards) {
    foreach ($giftcards as $g) $total += (float)$g['amount'];

    $senderName  = $giftcards[0]['sender_name'];
    $senderEmail = $giftcards[0]['sender_email'];

    // Envío de email
    $emailSent = sendGiftcardsEmailToSender($senderEmail, $senderName, $giftcards);

    // Puntos
    addLoyaltyPoints($senderEmail, $senderName, $total, $purchaseToken);
    $pointsAdded = true;

    if ($sessionId) {
      $pdo->prepare("UPDATE giftcards SET stripe_session_id=? WHERE purchase_token=?")
         ->execute([$sessionId, $purchaseToken]);
    }
  } else {
    $errorMsg = "No se encontraron tarjetas para esta compra.";
  }
} else {
  $errorMsg = "No se recibió información de la compra.";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="styles.css"> <!-- Usa tu styles.css del flujo -->
<style>
/* Ajustes ligeros adicionales */
.success-preview-wrap {
  border-radius:20px;
  overflow:hidden;
  width:100%;
  margin-bottom:16px;
  box-shadow:0 18px 40px rgba(15,23,42,0.18);
}
.success-preview-wrap img {
  width:100%;
  display:block;
}

.success-info-card {
  background:#fff;
  border-radius:24px;
  padding:20px 18px 22px;
  box-shadow:0 18px 35px rgba(15,23,42,0.08);
  margin-top:16px;
}

.success-btn-row {
  display:flex;
  justify-content:center;
  gap:10px;
  width:100%;
  margin-top:14px;
}

.btn-main, .btn-soft {
  max-width:200px;
}
</style>
</head>

<body class="app-body">

<div class="app-root">

  <!-- ================= HEADER iOS ================= -->
  <header class="app-header">
    <div class="app-header-inner centered-layout">

      <!--div class="app-header-logo-wrap">
        <img src="logo/logo.png" class="app-logo">
      </div-->

      <div class="app-header-title centered">
        <h1></h1>
      </div>

      <span class="app-header-sub">Compra confirmada</span>
    </div>
  </header>

  <!-- ================= CONTENIDO ================= -->
  <div class="app-shell">
    <div id="successWrapper" class="step-active">

      <?php if ($errorMsg): ?>
        <div class="success-info-card text-center">
          <h2 class="page-title">Error</h2>
          <p class="page-sub"><?php echo htmlspecialchars($errorMsg); ?></p>
          <button class="btn-soft" onclick="window.location.href='index.php'">Volver al inicio</button>
        </div>
      <?php else: ?>

        <h2 class="page-title">¡Gracias por tu compra!</h2>
        <p class="page-sub">
          Hemos generado tus tarjetas de regalo.
        </p>

        <?php foreach ($giftcards as $g): ?>
          <?php
            $img = $baseUrl . "/giftcards/" . $g['image_filename'];
            $recipient = htmlspecialchars($g['recipient_name']);
          ?>

          <!-- PREVIEW FULL iOS STYLE -->
          <div class="success-preview-wrap">
            <img src="<?php echo $img ?>">
          </div>

          <div class="success-info-card text-center">
            <p class="step-desc">Tu tarjeta está lista para descargar o compartir.</p>

            <div class="success-btn-row">
              <a href="<?php echo $img ?>" download class="btn-main">Descargar</a>
              <button class="btn-soft" onclick="shareWA('<?php echo $recipient ?>','<?php echo $img ?>')">Whatsapp</button>
            </div>
          </div>

        <?php endforeach; ?>

        <div class="success-btn-row" style="margin-top:26px;">
          <button class="btn-soft" onclick="window.location.href='index.php'">Crear nuevas tarjetas</button>
        </div>

      <?php endif; ?>

    </div>
  </div>
</div>

<script>
function shareWA(name, imgUrl) {
  const msg =
    "🎁 *Aquí tienes tu Giftcard Digital*\n" +
    `👤 *Para:* ${name}\n\n` +
    "Puedes descargarla aquí:\n" +
    imgUrl;

  window.open(`https://wa.me/?text=${encodeURIComponent(msg)}`, "_blank");
}
</script>

</body>
</html>
