<?php $title='Carrinho'; $preco=config('app.preco_foto'); ?>
<style>
.btn-outline-white {
  display:inline-flex;align-items:center;gap:6px;
  background:transparent;color:var(--text);
  border:1.5px solid var(--border);
  padding:11px 20px;border-radius:10px;
  font-size:14px;font-weight:600;cursor:pointer;
  font-family:inherit;transition:all .15s;text-decoration:none;
}
.btn-outline-white:hover { border-color:var(--text);background:rgba(0,0,0,.04); }
.btn-purple {
  display:inline-flex;align-items:center;gap:6px;
  background:#7c3aed;color:#fff;border:none;
  padding:11px 24px;border-radius:10px;
  font-size:14px;font-weight:700;cursor:pointer;
  font-family:inherit;transition:background .15s;text-decoration:none;
}
.btn-purple:hover { background:#6d28d9; }
</style>

<div style="max-width:640px;margin:0 auto;padding:40px 32px 80px;">

  <!-- Cabeçalho -->
  <div style="display:flex;align-items:baseline;justify-content:space-between;margin-bottom:28px;">
    <h1 class="serif" style="font-size:2rem;font-weight:300;letter-spacing:-.01em;">Carrinho</h1>
    <?php if(!empty($cart)): ?>
    <form method="post" action="<?= base_url('carrinho/clear') ?>"
          onsubmit="return confirm('Remover todas as fotografias do carrinho?')">
      <?= csrf_field() ?>
      <button type="submit" class="btn-outline-white" style="padding:7px 14px;font-size:12px;">
        🗑 Limpar carrinho
      </button>
    </form>
    <?php endif; ?>
  </div>

  <?php if(empty($cart)): ?>
  <div style="text-align:center;padding:60px 0;border-top:1px solid var(--border);">
    <p style="font-size:13px;color:var(--text-3);letter-spacing:.05em;text-transform:uppercase;margin-bottom:20px;">Carrinho vazio</p>
    <a href="<?= base_url() ?>" class="btn-purple">Escolher fotografias</a>
  </div>
  <?php else: ?>

  <!-- Lista -->
  <div style="border-top:1px solid var(--border);" id="cart-list">
    <?php foreach($cart as $pid => $qty):
      $p = $photos[$pid] ?? null; if(!$p) continue; ?>
    <div style="display:flex;align-items:center;gap:14px;padding:16px 0;border-bottom:1px solid var(--border-light);"
         id="cart-item-<?= $pid ?>">
      <div style="width:64px;height:64px;flex-shrink:0;background:var(--border-light);border-radius:var(--radius);overflow:hidden;">
        <img src="<?= imgurl('thumbnails',$p['event_id'],$p['filename']) ?>"
             style="width:100%;height:100%;object-fit:cover;" loading="lazy">
      </div>
      <div style="flex:1;min-width:0;">
        <div style="font-size:13px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
          <?= h(fname($p['filename'])) ?>
        </div>
        <div style="font-size:12px;color:var(--text-3);margin-top:2px;"><?= money($preco) ?> / unidade</div>
      </div>
      <!-- Quantidade -->
      <div style="display:flex;align-items:center;gap:0;border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;">
        <button data-cart-action="qty" data-delta="<?= $pid ?>,-1)"
                style="width:32px;height:32px;background:none;border:none;cursor:pointer;font-size:15px;color:var(--text-2);">−</button>
        <span id="cqty-<?= $pid ?>" style="min-width:28px;text-align:center;font-size:13px;font-weight:600;"><?= $qty ?></span>
        <button data-cart-action="qty" data-delta="<?= $pid ?>,+1)"
                style="width:32px;height:32px;background:none;border:none;cursor:pointer;font-size:15px;color:var(--text-2);">+</button>
      </div>
      <!-- Subtotal -->
      <div id="csub-<?= $pid ?>" style="width:64px;text-align:right;font-size:13px;font-weight:600;flex-shrink:0;">
        <?= money($qty * $preco) ?>
      </div>
      <!-- Remover -->
      <button data-cart="remove" data-pid="<?= $pid ?>"
              style="background:none;border:none;cursor:pointer;color:var(--text-3);font-size:20px;padding:4px;line-height:1;flex-shrink:0;"
              title="Remover">×</button>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- Totais -->
  <div id="totals-block" style="padding-top:20px;">
    <div style="display:flex;justify-content:space-between;font-size:13px;color:var(--text-2);margin-bottom:8px;">
      <span id="tot-desc"><?= $totals['items'] ?> foto<?= $totals['items']!=1?'s':'' ?> (<?= $totals['pay'] ?> pagas)</span>
      <span id="tot-sub"><?= money($totals['subtotal']) ?></span>
    </div>
    <?php if($totals['free']>0): ?>
    <div id="tot-free-row" style="display:flex;justify-content:space-between;font-size:13px;color:#2D8A4E;margin-bottom:8px;">
      <span>🎁 <?= $totals['free'] ?> fotografia<?= $totals['free']!=1?'s':'' ?> grátis</span><span>Incluída<?= $totals['free']!=1?'s':'' ?></span>
    </div>
    <?php else: ?>
    <div id="tot-free-row" style="display:none;justify-content:space-between;font-size:13px;color:#2D8A4E;margin-bottom:8px;">
      <span id="tot-free-lbl">🎁 1 fotografia grátis</span><span>Incluída</span>
    </div>
    <?php endif; ?>
    <div style="display:flex;justify-content:space-between;font-size:13px;color:var(--text-2);margin-bottom:16px;">
      <span>Envio</span><span>Calculado no checkout</span>
    </div>
    <div style="display:flex;justify-content:space-between;align-items:baseline;border-top:1px solid var(--border);padding-top:16px;margin-bottom:24px;">
      <span style="font-size:13px;font-weight:600;">Subtotal</span>
      <span id="tot-total" style="font-size:20px;font-weight:600;"><?= money($totals['subtotal']) ?></span>
    </div>
  </div>

  <!-- Botões -->
  <div style="display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap;">
    <a href="<?= base_url() ?>" class="btn-outline-white">← Continuar a escolher</a>
    <a href="<?= base_url('checkout') ?>" class="btn-purple">Finalizar encomenda →</a>
  </div>
  <?php endif; ?>
</div>

<script nonce="<?= nonce() ?>">
const CSRF  = '<?= csrf_token() ?>';
const BASE  = '<?= base_url() ?>';
const PRECO = <?= $preco ?>;
const PROMO_C = <?= config('app.promo_compra') ?>;
const PROMO_O = <?= config('app.promo_oferta') ?>;
let cart = <?= json_encode(array_map('intval', $cart)) ?>;

async function changeQty(pid, delta) {
  const cur = cart[pid] || 0;
  const qty = Math.max(0, cur + delta);
  if (qty === cur) return;
  if (qty <= 0) { removeItem(pid); return; }
  cart[pid] = qty;
  const fd = new URLSearchParams({_csrf:CSRF, photo_id:pid, qty});
  try {
    const r = await fetch(BASE+'carrinho/update', {method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'}});
    const d = await r.json();
    updateCartBadge(d.count);
  } catch(e){}
  document.getElementById('cqty-'+pid).textContent = qty;
  const sub = document.getElementById('csub-'+pid);
  if (sub) sub.textContent = (qty*PRECO).toFixed(2).replace('.',',')+'€';
  recalc();
}

// Event delegation para carrinho
document.getElementById('cart-list')?.addEventListener('click', function(e) {
  const btn = e.target.closest('[data-cart]');
  if (!btn) return;
  const pid   = parseInt(btn.dataset.pid, 10);
  const action = btn.dataset.cart;
  if (action === 'qty')    changeQty(pid, parseInt(btn.dataset.delta, 10));
  if (action === 'remove') removeItem(pid);
});

async function removeItem(pid) {
  delete cart[pid];
  const fd = new URLSearchParams({_csrf:CSRF, photo_id:pid, qty:0});
  try {
    const r = await fetch(BASE+'carrinho/remove', {method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'}});
    const d = await r.json();
    updateCartBadge(d.count);
  } catch(e){}
  document.getElementById('cart-item-'+pid)?.remove();
  recalc();
  // Se carrinho vazio, recarregar para mostrar estado vazio
  if (Object.keys(cart).length === 0) location.reload();
}

function recalc() {
  const total = Object.values(cart).reduce((a,b)=>a+b, 0);
  const free  = PROMO_C>0 ? Math.floor(total/PROMO_C)*PROMO_O : 0;
  const pay   = total - free;
  const sub   = pay * PRECO;
  const desc  = document.getElementById('tot-desc');
  const subEl = document.getElementById('tot-sub');
  const totEl = document.getElementById('tot-total');
  const freeRow = document.getElementById('tot-free-row');
  const freeLbl = document.getElementById('tot-free-lbl');
  if (desc) desc.textContent = `${total} foto${total!==1?'s':''} (${pay} paga${pay!==1?'s':''})`;
  if (subEl) subEl.textContent = sub.toFixed(2).replace('.',',')+'€';
  if (totEl) totEl.textContent = sub.toFixed(2).replace('.',',')+'€';
  if (freeRow) {
    freeRow.style.display = free>0 ? 'flex' : 'none';
    if (freeLbl) freeLbl.textContent = `🎁 ${free} fotografia${free!==1?'s':''} grátis`;
  }
  updateCartBadge(total);
}
</script>
