<?php
$title = $order['order_number'];
$breadcrumbs = [
  ['Encomendas', base_url('admin/encomendas')],
  [$order['order_number'], null],
];
$badge = '<span class="badge badge-'.$order['status'].'" style="font-size:13px;">'.match($order['status']){'pending'=>'Pendente','paid'=>'Pago','sent'=>'Enviado',default=>'Cancelado'}.'</span>';
$topActions = '
  <a href="'.base_url('recibo/'.$order['order_number'].'?admin=1').'" target="_blank"
     class="btn btn-secondary">🖨 Ver Recibo PDF</a>
  '.$badge;
?>

<div style="display:grid;grid-template-columns:1fr 320px;gap:16px;align-items:start;">

  <!-- Coluna esquerda: formulário de edição -->
  <div style="display:flex;flex-direction:column;gap:14px;">

    <!-- Dados do cliente -->
    <div class="card">
      <div class="card-header">
        <div class="card-title">👤 Dados do Cliente</div>
      </div>
      <form method="post" action="<?= base_url('admin/encomendas/'.$order['id']) ?>" id="order-form">
        <?= csrf_field() ?>
        <div class="card-body">
          <div class="input-grid">
            <div class="form-group">
              <label class="form-label">Nome completo</label>
              <input type="text" name="customer_name" value="<?= h($order['customer_name']) ?>" required class="input">
            </div>
            <div class="form-group">
              <label class="form-label">Telemóvel <span style="font-weight:400;color:#AEAEB2;">(opcional)</span></label>
              <input type="tel" name="phone" value="<?= h($order['phone']) ?>" class="input" placeholder="+351 9XX XXX XXX">
            </div>
            <div class="form-group input-span2">
              <label class="form-label">Email <span style="font-weight:400;color:#AEAEB2;">(opcional)</span></label>
              <input type="email" name="email" value="<?= h($order['email']) ?>" class="input">
            </div>
            <div class="form-group">
              <label class="form-label">NIF <span style="font-weight:400;color:#AEAEB2;">(opcional)</span></label>
              <input type="text" name="nif" value="<?= h($order['nif'] ?? '') ?>" class="input" placeholder="Ex: 123456789">
            </div>
          </div>

          <hr class="divider">

          <!-- Envio -->
          <div class="section-title" style="margin-bottom:12px;">Método de Envio</div>
          <div style="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;" id="ship-options">
            <?php foreach([
              'noivos'        => ['💍','Entrega aos Noivos','Grátis'],
              'ctt'           => ['📦','Envio CTT','+'.money((float)config('app.preco_ctt'))],
              'internacional' => ['✈️','Envio Internacional','+'.money((float)config('app.preco_internacional'))],
            ] as $val=>[$icon,$label,$price]): ?>
            <label id="ship-lbl-<?= $val ?>"
                   onclick="selectShip('<?= $val ?>')"
                   style="display:flex;align-items:center;gap:10px;padding:10px 14px;border-radius:9px;
                          cursor:pointer;transition:border-color .15s,background .15s;
                          border:1.5px solid <?= $order['shipping_method']===$val?'#1C1C1E':'#E5E5EA' ?>;
                          background:<?= $order['shipping_method']===$val?'#F9F9FB':'#fff' ?>;">
              <input type="radio" name="shipping_method" value="<?= $val ?>"
                     <?= $order['shipping_method']===$val?'checked':'' ?>
                     style="accent-color:#1C1C1E;pointer-events:none;">
              <span><?= $icon ?></span>
              <span style="flex:1;font-weight:500;"><?= $label ?></span>
              <span style="color:#6E6E73;font-size:13px;"><?= $price ?></span>
            </label>
            <?php endforeach; ?>
          </div>

          <div class="form-group">
            <label class="form-label">Morada de entrega</label>
            <textarea name="address" rows="3" class="input"
                      placeholder="Deixa em branco se for entrega presencial"><?= h($order['address']??'') ?></textarea>
          </div>

          <hr class="divider">

          <!-- Estado e notas -->
          <div class="section-title" style="margin-bottom:12px;">Estado da Encomenda</div>
          <div class="input-grid">
            <div class="form-group">
              <label class="form-label">Método de Pagamento</label>
              <select name="payment_method" class="input">
                <option value="dinheiro" <?= ($order['payment_method']??'dinheiro')==='dinheiro'?'selected':'' ?>>💵 Dinheiro</option>
                <option value="mbway"    <?= ($order['payment_method']??'dinheiro')==='mbway'   ?'selected':'' ?>>📱 MBWay</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Estado</label>
              <select name="status" class="input">
                <?php foreach([
                  'pending'   => '⏳ Pendente — aguarda aprovação',
                  'paid'      => '✅ Pago — pagamento confirmado',
                  'sent'      => '📬 Enviado — fotos entregues',
                  'cancelled' => '❌ Cancelado',
                ] as $v=>$l): ?>
                <option value="<?= $v ?>" <?= $order['status']===$v?'selected':'' ?>><?= $l ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group" style="display:flex;align-items:flex-end;">
              <div style="background:#F9F9FB;border:1px solid #E5E5EA;border-radius:9px;padding:10px 14px;width:100%;font-size:13px;">
                <div style="color:#6E6E73;margin-bottom:2px;">Criado em</div>
                <div style="font-weight:600;"><?= date('d/m/Y H:i',strtotime($order['created_at'])) ?></div>
              </div>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">Notas internas <span style="font-weight:400;color:#AEAEB2;">(visível apenas no admin)</span></label>
            <textarea name="notes" rows="3" class="input" placeholder="Observações, acordos, informações relevantes..."><?= h($order['notes']??'') ?></textarea>
          </div>

          <button type="submit" class="btn btn-primary" style="width:100%;padding:12px;font-size:14px;">
            💾 Guardar Alterações
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- Coluna direita -->
  <div style="display:flex;flex-direction:column;gap:14px;">

    <!-- Resumo financeiro -->
    <div class="card">
      <div class="card-header">
        <div class="card-title">💶 Resumo</div>
      </div>
      <div class="card-body">
        <div class="detail-row">
          <span class="detail-key">Subtotal</span>
          <span class="detail-val" id="res-subtotal"><?= money($order['subtotal']) ?></span>
        </div>
        <?php if($order['photos_free']>0): ?>
        <div class="detail-row" style="color:#047857;">
          <span>🎁 Oferta</span>
          <span style="font-weight:600;" id="res-free">+<?= $order['photos_free'] ?> foto<?= $order['photos_free']!=1?'s':'' ?></span>
        </div>
        <?php endif; ?>
        <div class="detail-row" id="res-ship-row" style="<?= $order['shipping_cost']>0?'':'display:none' ?>">
          <span class="detail-key">Envio</span>
          <span class="detail-val" id="res-ship"><?= money($order['shipping_cost']) ?></span>
        </div>
        <div class="total-row">
          <span>Total</span>
          <span style="font-size:20px;" id="res-total"><?= money($order['total']) ?></span>
        </div>
        <div style="margin-top:12px;background:#EFF6FF;border-radius:8px;padding:10px 12px;font-size:13px;color:#1D4ED8;">
          💵 Pagamento presencial na entrega
        </div>
      </div>
    </div>

    <!-- Info evento -->
    <div class="card">
      <div class="card-header"><div class="card-title">📅 Evento</div></div>
      <div class="card-body">
        <div style="font-weight:600;margin-bottom:4px;"><?= h($order['event_name']?:'—') ?></div>
        <div style="font-size:13px;color:#6E6E73;">Nº <?= h($order['order_number']) ?></div>
        <?php if($order['event_id']): ?>
        <a href="<?= base_url('admin/encomendas?event_id='.$order['event_id']) ?>"
           style="font-size:12px;color:#7C3AED;margin-top:8px;display:block;">Ver todas as encomendas deste evento →</a>
        <?php endif; ?>
      </div>
    </div>

    <!-- Fotografias — com edição -->
    <div class="card">
      <div class="card-header">
        <div class="card-title">📷 Fotografias da Encomenda</div>
        <div class="card-sub"><?php $totalCopias=array_sum(array_column($items,'quantity')); ?><?= $totalCopias ?> fotografia<?= $totalCopias!=1?'s':'' ?></div>
      </div>

      <?php if(empty($items)): ?>
      <div style="padding:20px;text-align:center;color:#AEAEB2;font-size:13px;">Sem fotos registadas</div>
      <?php else: ?>
      <div>
        <?php foreach($items as $item): ?>
        <div style="display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid #F2F2F7;">
          <?php if($item['thumb_path']): ?>
          <img src="<?= base_url('imgs/'.$item['thumb_path']) ?>"
               style="width:42px;height:42px;object-fit:cover;border-radius:4px;flex-shrink:0;" loading="lazy">
          <?php endif; ?>
          <div style="flex:1;min-width:0;">
            <div style="font-size:12px;font-weight:600;color:#1D1D1F;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
              <?= h(fname($item['filename']??'')) ?>
            </div>
            <div style="font-size:11px;color:#6E6E73;">×<?= $item['quantity'] ?> = <?= money($item['subtotal']) ?></div>
          </div>
          <form method="post" action="<?= base_url('admin/encomendas/'.$order['id'].'/foto/remove') ?>"
                onsubmit="return confirm('Remover esta fotografia da encomenda?')">
            <?= csrf_field() ?>
            <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
            <button type="submit" class="btn btn-danger btn-sm" style="padding:4px 10px;font-size:11px;">× Remover</button>
          </form>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- Adicionar fotografia -->
      <?php if(!empty($eventPhotos)): ?>
      <div style="border-top:2px solid #F2F2F7;padding:14px 16px;">
        <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#AEAEB2;margin-bottom:10px;">
          + Adicionar fotografia do evento
        </div>
        <form method="post" action="<?= base_url('admin/encomendas/'.$order['id'].'/foto/add') ?>"
              style="display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap;">
          <?= csrf_field() ?>
          <div style="flex:1;min-width:180px;">
            <label style="font-size:11px;color:#6E6E73;display:block;margin-bottom:4px;">Fotografia</label>
            <select name="photo_id" class="input" style="font-size:13px;padding:8px 10px;">
              <option value="">— Escolher fotografia —</option>
              <?php
              $itemPhotoIds = array_column($items,'photo_id');
              foreach($eventPhotos as $ep):
                $alreadyIn = in_array($ep['id'], $itemPhotoIds);
              ?>
              <option value="<?= $ep['id'] ?>" <?= $alreadyIn?'style="color:#9ca3af;"':'' ?>>
                <?= h(fname($ep['filename'])) ?><?= $alreadyIn?' (já incluída)':'' ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div style="width:70px;">
            <label style="font-size:11px;color:#6E6E73;display:block;margin-bottom:4px;">Qtd</label>
            <input type="number" name="qty" value="1" min="1" max="99" class="input" style="font-size:13px;padding:8px 10px;">
          </div>
          <button type="submit" class="btn btn-primary" style="padding:8px 14px;white-space:nowrap;">Adicionar</button>
        </form>
      </div>
      <?php elseif(!empty($order['event_id'])): ?>
      <div style="padding:12px 16px;font-size:12px;color:#AEAEB2;border-top:1px solid #F2F2F7;">
        Sem fotografias disponíveis neste evento.
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
// Configurações de preço (vindas do servidor)
const PRECO     = <?= (float)config('app.preco_foto') ?>;
const PRECO_CTT = <?= (float)config('app.preco_ctt') ?>;
const PRECO_INT = <?= (float)config('app.preco_internacional') ?>;
const PC        = <?= (int)config('app.promo_compra') ?>;
const PO        = <?= (int)config('app.promo_oferta') ?>;
const CICLO     = PC + PO;

// Total de fotografias na encomenda (fixo enquanto não adicionar/remover)
let totalFotos  = <?= (int)array_sum(array_column($items,'quantity')) ?>;

function fmt(v) {
  return v.toFixed(2).replace('.', ',') + '€';
}

function recalcResumo(ship) {
  const free     = (CICLO > 0 && totalFotos > 0) ? Math.floor(totalFotos / CICLO) * PO : 0;
  const pay      = totalFotos - free;
  const subtotal = pay * PRECO;
  const shipCost = ship === 'ctt' ? PRECO_CTT : ship === 'internacional' ? PRECO_INT : 0;
  const total    = subtotal + shipCost;

  // Subtotal
  const elSub = document.getElementById('res-subtotal');
  if (elSub) elSub.textContent = fmt(subtotal);

  // Oferta
  const elFree = document.getElementById('res-free');
  if (elFree) elFree.textContent = '+' + free + ' foto' + (free !== 1 ? 's' : '');

  // Envio
  const elShipRow = document.getElementById('res-ship-row');
  const elShip    = document.getElementById('res-ship');
  if (elShipRow) elShipRow.style.display = shipCost > 0 ? '' : 'none';
  if (elShip)    elShip.textContent = fmt(shipCost);

  // Total
  const elTotal = document.getElementById('res-total');
  if (elTotal) elTotal.textContent = fmt(total);
}

function selectShip(val) {
  // Marcar o radio
  const radio = document.querySelector('input[name="shipping_method"][value="' + val + '"]');
  if (radio) radio.checked = true;

  // Feedback visual em todos os labels
  ['noivos','ctt','internacional'].forEach(function(v) {
    const lbl = document.getElementById('ship-lbl-' + v);
    if (!lbl) return;
    if (v === val) {
      lbl.style.borderColor = '#1C1C1E';
      lbl.style.background  = '#F9F9FB';
    } else {
      lbl.style.borderColor = '#E5E5EA';
      lbl.style.background  = '#fff';
    }
  });

  // Recalcular resumo
  recalcResumo(val);
}

// Calcular ao carregar com o método actual
const checkedShip = document.querySelector('input[name="shipping_method"]:checked');
if (checkedShip) recalcResumo(checkedShip.value);
</script>

