<?php
declare(strict_types=1);

require_once __DIR__ . '/common.php';

$config = kapvoe_load_config();
$sessionId = trim((string)($_GET['session_id'] ?? ''));
$order = null;
$product = null;
$error = '';
$catalogProductMissing = false;
$mailRetryResult = null;

if ($sessionId === '') {
    $error = 'Falta el codi de sessió de Stripe.';
} else {
    $order = kapvoe_get_order_by_session_id($config, $sessionId);

    if (!$order) {
        $error = 'No s\'ha trobat la comanda associada a aquesta sessió.';
    } else {
        try {
            $product = kapvoe_get_catalog_product_by_code(
                $config,
                (string)($order['product_code'] ?? '')
            );
        } catch (Throwable $e) {
            $product = null;
            $catalogProductMissing = true;
        }

        if ((string)($order['payment_status'] ?? '') === 'paid') {
            try {
                $mailRetryResult = kapvoe_send_order_notifications($config, $order, $sessionId);
                $order = kapvoe_get_order_by_session_id($config, $sessionId) ?? $order;
            } catch (Throwable $e) {
                $mailRetryResult = [
                    'error' => $e->getMessage(),
                ];
            }
        }
    }
}

function kapvoe_find_local_product_image_url(string $productCode): string {
    $productCode = trim($productCode);
    if ($productCode === '') {
        return '';
    }

    foreach (['png', 'jpg', 'jpeg', 'webp'] as $ext) {
        $absolutePath = dirname(__DIR__) . "/assets/products/{$productCode}.{$ext}";
        if (is_file($absolutePath)) {
            return "/assets/products/{$productCode}.{$ext}";
        }
    }

    return '';
}

function e(?string $value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function fmt_eur($value): string {
    $n = (float)$value;
    return number_format($n, 2, ',', '.') . ' €';
}

$productCode = (string)($order['product_code'] ?? '');
$imageUrl = trim((string)($order['product_image_url'] ?? ''));
if ($imageUrl === '') {
    $imageUrl = (string)($product['image_url'] ?? '');
}
if ($imageUrl === '') {
    $imageUrl = kapvoe_find_local_product_image_url($productCode);
}
$shippingMethod = (string)($order['shipping_method'] ?? 'pickup');
$subtotal = (string)($order['subtotal'] ?? $order['unit_price'] ?? '0.00');
$shippingCost = (string)($order['shipping_cost'] ?? '0.00');
$totalAmount = (string)($order['total_amount'] ?? $order['unit_price'] ?? '0.00');
?>
<!DOCTYPE html>
<html lang="ca">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Compra confirmada · Blood Bros Sports</title>
  <link rel="icon" type="image/png" href="/assets/logo/bloodbros-sports-logo.png">
  <style>
    :root{
      --bg-1:#040b16;
      --bg-2:#071425;
      --bg-3:#091a30;
      --card:#0d1729;
      --line:rgba(255,255,255,.10);
      --text:#f4f7fb;
      --muted:#9fb0ca;
      --accent:#64c4ff;
      --green:#28d267;
      --shadow:0 16px 44px rgba(0,0,0,.34);
      --radius-xl:30px;
      --radius-lg:24px;
      --radius-md:18px;
    }

    *{box-sizing:border-box}
    html,body{margin:0;padding:0}
    body{
      font-family: Inter, ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
      color:var(--text);
      background:
        radial-gradient(circle at 12% 10%, rgba(52,122,255,.18), transparent 24%),
        radial-gradient(circle at 82% 12%, rgba(100,196,255,.12), transparent 24%),
        linear-gradient(180deg, var(--bg-1) 0%, var(--bg-2) 38%, var(--bg-3) 100%);
      min-height:100vh;
    }

    .wrap{
      max-width:980px;
      margin:0 auto;
      padding:38px 18px 42px;
    }

    .card{
      border-radius:32px;
      border:1px solid rgba(255,255,255,.10);
      background:
        radial-gradient(circle at 75% 15%, rgba(104,133,255,.18), transparent 28%),
        linear-gradient(180deg, rgba(17,29,52,.95), rgba(12,20,36,.98));
      box-shadow:var(--shadow);
      overflow:hidden;
    }

    .head{
      display:flex;
      align-items:center;
      gap:18px;
      padding:28px 28px 10px;
    }

    .logo-wrap{
      width:84px;
      height:84px;
      border-radius:24px;
      background:linear-gradient(135deg, rgba(255,255,255,.08), rgba(255,255,255,.03));
      border:1px solid rgba(255,255,255,.10);
      display:flex;
      align-items:center;
      justify-content:center;
      overflow:hidden;
      flex:0 0 auto;
    }

    .logo-wrap img{
      max-width:82%;
      max-height:82%;
      object-fit:contain;
      display:block;
    }

    .head-copy h1{
      margin:0 0 6px;
      font-size:24px;
      font-weight:1000;
    }

    .head-copy p{
      margin:0;
      color:var(--muted);
      font-size:16px;
      line-height:1.45;
    }

    .ok-badge{
      margin:0 28px 22px;
      display:inline-flex;
      align-items:center;
      gap:10px;
      min-height:40px;
      padding:0 16px;
      border-radius:999px;
      background:rgba(40,210,103,.14);
      border:1px solid rgba(40,210,103,.28);
      color:#c8ffd9;
      font-weight:900;
    }

    .content{
      padding:0 28px 30px;
      display:grid;
      gap:18px;
    }

    .summary-card{
      display:grid;
      grid-template-columns:120px 1fr;
      gap:18px;
      align-items:center;
      border:1px solid rgba(255,255,255,.08);
      background:rgba(255,255,255,.04);
      border-radius:24px;
      padding:18px;
    }

    .summary-media{
      width:120px;
      height:120px;
      border-radius:18px;
      background:rgba(255,255,255,.92);
      display:flex;
      align-items:center;
      justify-content:center;
      overflow:hidden;
    }

    .summary-media img{
      width:100%;
      height:100%;
      object-fit:contain;
      display:block;
    }

    .summary-placeholder{
      color:#0b1630;
      font-size:12px;
      font-weight:900;
      text-align:center;
      padding:8px;
    }

    .summary-info h2{
      margin:0 0 6px;
      font-size:38px;
      line-height:1;
      font-weight:1000;
      letter-spacing:-.04em;
    }

    .summary-info .meta{
      color:var(--muted);
      font-size:15px;
      line-height:1.5;
    }

    .grid{
      display:grid;
      grid-template-columns:1fr 1fr;
      gap:18px;
    }

    .box{
      border:1px solid rgba(255,255,255,.08);
      background:rgba(255,255,255,.04);
      border-radius:24px;
      padding:18px;
    }

    .box-title{
      margin:0 0 14px;
      color:var(--muted);
      font-size:12px;
      text-transform:uppercase;
      letter-spacing:.16em;
      font-weight:900;
    }

    .line{
      display:flex;
      justify-content:space-between;
      gap:14px;
      padding:8px 0;
      color:#eef4ff;
      font-size:15px;
      border-bottom:1px solid rgba(255,255,255,.06);
    }

    .line:last-child{
      border-bottom:none;
    }

    .line.total{
      font-size:18px;
      font-weight:1000;
      padding-top:12px;
    }

    .contact-item{
      display:grid;
      gap:4px;
      padding:10px 0;
      border-bottom:1px solid rgba(255,255,255,.06);
    }

    .contact-item:last-child{
      border-bottom:none;
    }

    .contact-item strong{
      font-size:12px;
      color:var(--muted);
      text-transform:uppercase;
      letter-spacing:.12em;
    }

    .contact-item span{
      color:#eef4ff;
      font-size:15px;
      line-height:1.45;
      word-break:break-word;
    }

    .actions{
      display:flex;
      gap:12px;
      flex-wrap:wrap;
      margin-top:6px;
    }

    .btn{
      min-height:52px;
      padding:0 20px;
      border-radius:999px;
      border:1px solid rgba(255,255,255,.10);
      text-decoration:none;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      font-weight:900;
      color:#fff;
      background:rgba(255,255,255,.05);
    }

    .btn-primary{
      background:linear-gradient(180deg, rgba(93,154,255,.34), rgba(52,115,214,.28));
      border-color:rgba(100,196,255,.24);
    }

    .error-box{
      margin:28px;
      padding:20px;
      border-radius:22px;
      border:1px solid rgba(255,90,98,.20);
      background:rgba(255,90,98,.08);
      color:#ffd9dc;
    }

    @media (max-width:780px){
      .summary-card{
        grid-template-columns:1fr;
      }
      .summary-media{
        width:100%;
        height:220px;
      }
      .grid{
        grid-template-columns:1fr;
      }
      .head{
        align-items:flex-start;
      }
    }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="card">
      <div class="head">
        <div class="logo-wrap">
          <img src="/assets/logo/bloodbros-sports-logo.png" alt="Blood Bros Sports">
        </div>
        <div class="head-copy">
          <h1>Pagament correcte</h1>
          <p>Hem rebut la teva compra. Aquí tens un resum de la comanda confirmada.</p>
        </div>
      </div>

      <?php if ($error !== ''): ?>
        <div class="error-box">
          <strong>No hem pogut carregar el resum de la comanda.</strong><br><br>
          <?= e($error) ?>
        </div>
      <?php else: ?>
        <div class="ok-badge">✅ Compra confirmada</div>

        <div class="content">
          <div class="summary-card">
            <div class="summary-media">
              <?php if ($imageUrl !== ''): ?>
                <img src="<?= e($imageUrl) ?>" alt="<?= e($productCode) ?>">
              <?php else: ?>
                <div class="summary-placeholder">Sense imatge</div>
              <?php endif; ?>
            </div>

            <div class="summary-info">
              <h2><?= e($productCode) ?></h2>
              <div class="meta">
                Sessió Stripe: <strong><?= e($sessionId) ?></strong><br>
                Mètode: <strong><?= e($shippingMethod === 'shipping' ? 'Enviament' : 'Entrega en persona') ?></strong>
              </div>
            </div>
          </div>

          <div class="grid">
            <div class="box">
              <div class="box-title">Resum econòmic</div>

              <div class="line">
                <span>Subtotal producte</span>
                <strong><?= fmt_eur($subtotal) ?></strong>
              </div>

              <div class="line">
                <span>Enviament</span>
                <strong><?= fmt_eur($shippingCost) ?></strong>
              </div>

              <div class="line total">
                <span>Total</span>
                <strong><?= fmt_eur($totalAmount) ?></strong>
              </div>
            </div>

            <div class="box">
              <div class="box-title">Dades de contacte</div>

              <div class="contact-item">
                <strong>Nom</strong>
                <span><?= e((string)($order['customer_name'] ?? '')) ?></span>
              </div>

              <div class="contact-item">
                <strong>Telèfon</strong>
                <span><?= e((string)($order['phone'] ?? '')) ?></span>
              </div>

              <div class="contact-item">
                <strong>Correu electrònic</strong>
                <span><?= e((string)($order['email'] ?? '')) ?></span>
              </div>

              <?php if ($shippingMethod === 'shipping'): ?>
                <div class="contact-item">
                  <strong>Adreça d'enviament</strong>
                  <span>
                    <?= e((string)($order['address'] ?? '')) ?><br>
                    <?= e((string)($order['postal_code'] ?? '')) ?> <?= e((string)($order['city'] ?? '')) ?><br>
                    <?= e((string)($order['province'] ?? '')) ?>
                  </span>
                </div>
              <?php else: ?>
                <div class="contact-item">
                  <strong>Entrega</strong>
                  <span>Quedarem amb tu per WhatsApp per entregar-te les ulleres en persona a Lleida o Mollerussa.</span>
                </div>
              <?php endif; ?>
            </div>
          </div>

          <div class="actions">
            <a class="btn btn-primary" href="/">Torna al catàleg</a>
          </div>
        </div>
      <?php endif; ?>
    </div>
  </div>
</body>
</html>
