<?php
$title       = 'Checkout';
$preco       = config('app.preco_foto');
$fieldErrors = flash('field_errors') ?? [];
?>
<style>
.co-input {
  width:100%;
  background:#1f2937;
  border:1px solid rgba(255,255,255,.12);
  border-radius:8px;
  padding:12px 14px;
  font-size:15px;
  color:#f9fafb;
  outline:none;
  font-family:inherit;
  transition:border-color .15s;
}
.co-input:focus { border-color:rgba(255,255,255,.4); }
.co-input::placeholder { color:#6b7280; }
.co-label {
  display:block;
  font-size:11px;
  font-weight:600;
  letter-spacing:.07em;
  text-transform:uppercase;
  color:#9ca3af;
  margin-bottom:7px;
}
.co-field { margin-bottom:14px; }
.co-section {
  background:#111827;
  border:1px solid rgba(255,255,255,.07);
  border-radius:14px;
  padding:22px;
  margin-bottom:14px;
}
.co-section-title {
  font-size:11px;
  font-weight:600;
  letter-spacing:.08em;
  text-transform:uppercase;
  color:#6b7280;
  margin-bottom:18px;
}
.co-radio-label {
  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:12px 14px;
  border:1.5px solid rgba(255,255,255,.1);
  border-radius:9px;
  cursor:pointer;
  transition:border-color .15s;
  margin-bottom:8px;
}
.co-radio-label:hover { border-color:rgba(255,255,255,.25); }
.co-radio-label.active { border-color:rgba(255,255,255,.5); background:rgba(255,255,255,.04); }
.co-btn {
  display:block;
  width:100%;
  background:#fff;
  color:#111827;
  border:none;
  border-radius:10px;
  padding:14px;
  font-size:15px;
  font-weight:700;
  cursor:pointer;
  font-family:inherit;
  transition:background .15s;
  text-align:center;
}
.co-btn:hover { background:#f3f4f6; }
.co-btn-secondary {
  display:block;
  width:100%;
  background:transparent;
  color:#6b7280;
  border:1px solid rgba(255,255,255,.1);
  border-radius:10px;
  padding:12px;
  font-size:14px;
  font-weight:500;
  cursor:pointer;
  font-family:inherit;
  transition:all .15s;
  text-align:center;
  text-decoration:none;
  margin-bottom:10px;
}
.co-btn-secondary:hover { color:#fff; border-color:rgba(255,255,255,.25); }
.err-msg { font-size:12px; color:#f87171; margin-top:5px; display:none; }
.err-msg.show { display:block; }
.co-input.err { border-color:#ef4444; }
</style>

<div style="max-width:520px;margin:0 auto;padding:36px 16px 80px;">

  <a href="<?= base_url('carrinho') ?>" class="co-btn-secondary" style="margin-bottom:20px;">← Voltar ao carrinho</a>

  <h1 style="font-size:26px;font-weight:700;color:#fff;margin-bottom:24px;">Finalizar compra</h1>

  <?php if($m=flash('error')): ?>
  <div style="background:rgba(239,68,68,.15);border:1px solid rgba(239,68,68,.3);color:#f87171;padding:12px 16px;border-radius:10px;margin-bottom:16px;font-size:13px;"><?= h($m) ?></div>
  <?php endif; ?>

  <form id="co-form" method="post" action="<?= base_url('checkout') ?>" novalidate>
    <?= csrf_field() ?>

    <!-- Dados pessoais -->
    <div class="co-section">
      <div class="co-section-title">Dados pessoais</div>

      <div class="co-field">
        <label class="co-label" for="f-name">Nome completo *</label>
        <input type="text" name="name" id="f-name" value="<?= old('name') ?>"
               class="co-input <?= in_array('name',$fieldErrors)?'err':'' ?>" placeholder="O teu nome">
        <div class="err-msg <?= in_array('name',$fieldErrors)?'show':'' ?>" id="err-name">Campo obrigatório</div>
      </div>

      <div class="co-field">
        <label class="co-label" for="f-phone">Telemóvel <span style="font-weight:400;text-transform:none;letter-spacing:0;color:#6b7280;">(opcional)</span></label>
        <input type="tel" name="phone" id="f-phone" value="<?= old('phone') ?>"
               class="co-input" placeholder="+351 9XX XXX XXX">
        
      </div>

      <div class="co-field">
        <label class="co-label" for="f-email">Email <span style="font-weight:400;text-transform:none;letter-spacing:0;color:#6b7280;">(opcional)</span></label>
        <input type="email" name="email" id="f-email" value="<?= old('email') ?>"
               class="co-input <?= in_array('email',$fieldErrors)?'err':'' ?>" placeholder="email@exemplo.pt">
        <div class="err-msg <?= in_array('email',$fieldErrors)?'show':'' ?>" id="err-email">Email inválido</div>
      </div>

      <div class="co-field" style="margin-bottom:0;">
        <label class="co-label" for="f-nif">NIF <span style="font-weight:400;text-transform:none;letter-spacing:0;color:#6b7280;">(opcional)</span></label>
        <input type="text" name="nif" id="f-nif" value="<?= old('nif') ?>" class="co-input" placeholder="Ex: 123456789">
      </div>
    </div>

    <!-- Método de envio -->
    <div class="co-section">
      <div class="co-section-title">Método de envio</div>
      <?php foreach([
        ['noivos','💍','Entrega aos Noivos','Grátis','#4ade80'],
        ['ctt','📦','Envio CTT','+'.money(config('app.preco_ctt')),'#9ca3af'],
        ['internacional','✈️','Envio Internacional','+'.money(config('app.preco_internacional')),'#9ca3af'],
      ] as [$v,$icon,$l,$p,$pc]): ?>
      <label class="co-radio-label <?= old('shipping_method','noivos')===$v?'active':'' ?>" id="ship-lbl-<?= $v ?>"
             data-ship="<?= $v ?>">
        <div style="display:flex;align-items:center;gap:10px;">
          <input type="radio" name="shipping_method" value="<?= $v ?>"
                 <?= old('shipping_method','noivos')===$v?'checked':'' ?>
                 style="accent-color:#fff;" id="ship-<?= $v ?>">
          <span style="font-size:15px;"><?= $icon ?></span>
          <span style="font-size:14px;color:#e5e7eb;"><?= $l ?></span>
        </div>
        <span style="font-size:13px;font-weight:600;color:<?= $pc ?>;"><?= $p ?></span>
      </label>
      <?php endforeach; ?>

      <!-- Morada -->
      <div id="addr-block" style="margin-top:14px;<?= !in_array(old('shipping_method'),['ctt','internacional'])?'display:none;':'' ?>">
        <div style="display:grid;grid-template-columns:1fr 90px;gap:10px;margin-bottom:10px;">
          <div class="co-field" style="margin-bottom:0;">
            <label class="co-label">Rua / Avenida</label>
            <input type="text" name="addr_rua" id="f-addr_rua" value="<?= old('addr_rua') ?>"
                     class="co-input <?= in_array('addr_rua',$fieldErrors)?'err':'' ?>" placeholder="Rua das Flores">
            <div class="err-msg <?= in_array('addr_rua',$fieldErrors)?'show':'' ?>" id="err-addr_rua">Obrigatório</div>
          </div>
          <div class="co-field" style="margin-bottom:0;">
            <label class="co-label">Número</label>
            <input type="text" name="addr_num" value="<?= old('addr_num') ?>" class="co-input" placeholder="12">
          </div>
        </div>
        <div style="display:grid;grid-template-columns:130px 1fr;gap:10px;">
          <div class="co-field" style="margin-bottom:0;">
            <label class="co-label">Cód. Postal</label>
            <input type="text" name="addr_cp" id="f-addr_cp" value="<?= old('addr_cp') ?>"
                     class="co-input <?= in_array('addr_cp',$fieldErrors)?'err':'' ?>" placeholder="1234-567">
            <div class="err-msg <?= in_array('addr_cp',$fieldErrors)?'show':'' ?>" id="err-addr_cp">Obrigatório</div>
          </div>
          <div class="co-field" style="margin-bottom:0;">
            <label class="co-label">Localidade</label>
            <input type="text" name="addr_loc" id="f-addr_loc" value="<?= old('addr_loc') ?>" class="co-input" placeholder="Lisboa">
            <div class="err-msg" id="err-addr_loc">Obrigatório</div>
          </div>
        </div>
      </div>
    </div>
    <!-- Resumo -->
    <div class="co-section" style="margin-bottom:20px;">
      <div class="co-section-title">Resumo</div>
      <div style="display:flex;justify-content:space-between;font-size:13px;color:#9ca3af;margin-bottom:6px;">
        <span><?= $totals['items'] ?> foto<?= $totals['items']!=1?'s':'' ?> (<?= $totals['pay'] ?> pagas)</span>
        <span><?= money($totals['subtotal']) ?></span>
      </div>
      <?php if($totals['free']>0): ?>
      <div style="display:flex;justify-content:space-between;font-size:13px;color:#4ade80;margin-bottom:6px;">
        <span>+<?= $totals['free'] ?> de oferta</span><span>Incluídas</span>
      </div>
      <?php endif; ?>
      <div style="display:flex;justify-content:space-between;font-size:13px;color:#9ca3af;margin-bottom:14px;">
        <span>Envio</span><span id="ship-price" style="color:#4ade80;">Grátis</span>
      </div>
      <div style="display:flex;justify-content:space-between;align-items:baseline;border-top:1px solid rgba(255,255,255,.08);padding-top:12px;">
        <span style="font-size:14px;font-weight:600;color:#fff;">Total</span>
        <span id="total-display" style="font-size:22px;font-weight:700;color:#fff;"><?= money($totals['subtotal']) ?></span>
      </div>
    </div>

    <button type="submit" class="co-btn">Confirmar encomenda →</button>
  </form>
</div>

<!-- Notif validação -->
<div id="val-notif" style="display:none;position:fixed;top:70px;left:50%;transform:translateX(-50%);z-index:300;
     background:#450a0a;border:1px solid #7f1d1d;color:#fca5a5;padding:11px 20px;border-radius:10px;
     font-size:13px;font-weight:600;box-shadow:0 4px 24px rgba(0,0,0,.4);white-space:nowrap;">
  ⚠️ Preenche os campos obrigatórios assinalados
</div>

<script nonce="<?= nonce() ?>">
const SUB=<?= $totals['subtotal'] ?>,CTT=<?= config('app.preco_ctt') ?>,INTL=<?= config('app.preco_internacional') ?>;
let shipMethod='<?= old('shipping_method','noivos') ?>';

function onShip(v) {
  shipMethod = v;
  document.getElementById('ship-'+v).checked = true;
  ['noivos','ctt','internacional'].forEach(m => {
    const l = document.getElementById('ship-lbl-'+m);
    if (l) l.className = 'co-radio-label' + (m===v?' active':'');
  });
  document.getElementById('addr-block').style.display = (v==='ctt'||v==='internacional') ? 'block' : 'none';
  const s = v==='ctt'?CTT:v==='internacional'?INTL:0;
  const sp = document.getElementById('ship-price');
  const tp = document.getElementById('total-display');
  if (sp) { sp.textContent = s>0 ? '+'+s.toFixed(2).replace('.',',')+'€' : 'Grátis'; sp.style.color = s>0?'#9ca3af':'#4ade80'; }
  if (tp) tp.textContent = (SUB+s).toFixed(2).replace('.',',')+'€';
}

// Event listeners nos labels de envio (substitui onclick inline — compatível com CSP)
document.querySelectorAll('[data-ship]').forEach(function(lbl) {
  // Click no label inteiro
  lbl.addEventListener('click', function() { onShip(this.dataset.ship); });
  // Change no radio (acessibilidade — teclado/leitor de ecrã)
  const radio = lbl.querySelector('input[type=radio]');
  if (radio) radio.addEventListener('change', function() { if (this.checked) onShip(this.value); });
});


document.getElementById('co-form').addEventListener('submit', function(e) {
  let ok = true;
  document.querySelectorAll('.err-msg.show').forEach(el => el.classList.remove('show'));
  document.querySelectorAll('.co-input.err').forEach(el => el.classList.remove('err'));
  const req = ['name'];
  if (shipMethod==='ctt'||shipMethod==='internacional') req.push('addr_rua','addr_cp','addr_loc');
  let first = null;
  req.forEach(f => {
    const el = document.getElementById('f-'+f);
    const err = document.getElementById('err-'+f);
    if (el && !el.value.trim()) {
      el.classList.add('err'); if(err) err.classList.add('show'); ok=false; if(!first) first=el;
    }
  });
  if (!ok) {
    e.preventDefault();
    const n = document.getElementById('val-notif');
    n.style.display = 'block';
    setTimeout(() => n.style.display='none', 3500);
    if (first) first.scrollIntoView({behavior:'smooth',block:'center'});
  }
});
</script>
