<?php
$title = 'Eventos';
$breadcrumbs = [['Eventos', null]];
$topActions = '<button onclick="openModal(\'create\')" class="btn btn-primary">+ Novo Evento</button>';
?>

<div class="card">
  <div class="card-header">
    <div>
      <div class="card-title">Todos os Eventos</div>
      <div class="card-sub"><?= count($events) ?> evento<?= count($events)!=1?'s':'' ?></div>
    </div>
  </div>
  <div class="tbl-wrap">
    <table class="tbl">
      <thead><tr>
        <th>Evento</th>
        <th>Data</th>
        <th style="text-align:center;">Fotos</th>
        <th style="text-align:center;">Encomendas</th>
        <th>Estado</th>
        <th>Ações</th>
      </tr></thead>
      <tbody>
      <?php if(empty($events)): ?>
      <tr><td colspan="6" class="tbl-empty">
        <div style="font-size:32px;margin-bottom:8px;">📷</div>
        <div style="font-weight:600;margin-bottom:4px;">Nenhum evento criado</div>
        <div style="font-size:12px;">Clica em "+ Novo Evento" para começar</div>
      </td></tr>
      <?php else: ?>
      <?php foreach($events as $ev):
        $encCount = (int)(\App\Core\Database::val("SELECT COUNT(*) FROM orders WHERE event_id=?",[$ev['id']])?:0);
      ?>
      <tr>
        <td>
          <div class="tbl-name"><?= h($ev['name']) ?></div>
          <div class="tbl-sub text-mono">/evento/<?= h($ev['slug']) ?></div>
        </td>
        <td class="text-muted"><?= $ev['date_event']?date('d/m/Y',strtotime($ev['date_event'])):'—' ?></td>
        <td style="text-align:center;"><strong><?= $ev['photo_count'] ?></strong></td>
        <td style="text-align:center;">
          <?php if($encCount > 0): ?>
          <a href="<?= base_url('admin/encomendas?event_id='.$ev['id']) ?>"
             style="color:#7C3AED;font-weight:600;"><?= $encCount ?></a>
          <?php else: ?>
          <span class="text-muted">0</span>
          <?php endif; ?>
        </td>
        <td>
          <form method="post" action="<?= base_url('admin/eventos/'.$ev['id'].'/toggle') ?>" style="display:inline;">
            <?= csrf_field() ?>
            <button type="submit" class="badge badge-<?= $ev['status']==='active'?'active':'hidden' ?>"
                    style="border:none;cursor:pointer;font-size:12px;">
              <?= $ev['status']==='active'?'● Ativo':'○ Oculto' ?>
            </button>
          </form>
        </td>
        <td>
          <div class="flex-center gap-8">
            <a href="<?= base_url('admin/eventos/'.$ev['id'].'/fotos') ?>" class="btn btn-secondary btn-sm">
              📷 Fotos
            </a>
            <a href="<?= base_url('admin/eventos/'.$ev['id'].'/relatorio') ?>" target="_blank"
               class="btn btn-secondary btn-sm" title="Todas as encomendas com dados dos clientes">
              📊 Relatório
            </a>
            <a href="<?= base_url('admin/eventos/'.$ev['id'].'/fotos-vendidas') ?>" target="_blank"
               class="btn btn-secondary btn-sm" title="Lista de fotos e quantidades vendidas">
              📋 Fotos Vendidas
            </a>
            <button onclick='openEdit(<?= json_encode(['id'=>$ev['id'],'name'=>$ev['name'],'date_event'=>$ev['date_event']??'','order_prefix'=>$ev['order_prefix']??'','description'=>$ev['description']??'','status'=>$ev['status']]) ?>)'
                    class="btn btn-ghost btn-icon btn-sm" title="Editar">✏️</button>
            <a href="<?= base_url('evento/'.$ev['slug']) ?>" target="_blank"
               class="btn btn-ghost btn-icon btn-sm" title="Ver no site">↗</a>
            <form method="post" action="<?= base_url('admin/eventos/'.$ev['id'].'/delete') ?>"
                  onsubmit="return confirm('Apagar «<?= h($ev['name']) ?>» e todas as suas fotografias? Esta ação é irreversível.')">
              <?= csrf_field() ?>
              <button type="submit" class="btn btn-danger btn-sm btn-icon" title="Apagar">🗑</button>
            </form>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal Criar Evento -->
<div id="modal-create" style="display:none;" class="modal-backdrop" onclick="closeModal('create')">
  <div class="modal-box" onclick="event.stopPropagation()">
    <div class="modal-title">✨ Novo Evento</div>
    <form method="post" action="<?= base_url('admin/eventos') ?>">
      <?= csrf_field() ?>
      <div class="form-group">
        <label class="form-label">Nome do evento *</label>
        <input type="text" name="name" required class="input" id="create-name"
               oninput="genPrefix(this.value,'create')" placeholder="Ex: Casamento Ana & João">
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
        <div class="form-group">
          <label class="form-label">Data do evento</label>
          <input type="date" name="date_event" class="input">
        </div>
        <div class="form-group">
          <label class="form-label">Prefixo encomendas</label>
          <input type="text" name="order_prefix" id="create-prefix" class="input"
                 style="text-transform:uppercase;" maxlength="10" placeholder="ANAJOAO">
          <div class="form-hint">Ex: <span id="create-prefix-eg">ANAJOAO</span>-F001</div>
        </div>
      </div>
      <div class="form-group">
        <label class="form-label">Descrição <span style="font-weight:400;color:#AEAEB2;">(opcional)</span></label>
        <textarea name="description" class="input" rows="2" placeholder="Notas sobre o evento"></textarea>
      </div>
      <div class="form-group">
        <label class="form-label">Password de acesso <span style="font-weight:400;color:#AEAEB2;">(opcional — protege o evento)</span></label>
        <input type="text" name="password" class="input" placeholder="Ex: casamento2025" autocomplete="off">
        <div style="font-size:11px;color:#AEAEB2;margin-top:4px;">Se definida, os clientes terão de introduzir esta password para ver as fotos.</div>
      </div>
      <div style="display:flex;gap:10px;margin-top:8px;">
        <button type="button" onclick="closeModal('create')" class="btn btn-secondary" style="flex:1;">Cancelar</button>
        <button type="submit" class="btn btn-primary" style="flex:1;">Criar Evento</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Editar Evento -->
<div id="modal-edit" style="display:none;" class="modal-backdrop" onclick="closeModal('edit')">
  <div class="modal-box" onclick="event.stopPropagation()">
    <div class="modal-title">✏️ Editar Evento</div>
    <form id="edit-form" method="post">
      <?= csrf_field() ?>
      <div class="form-group">
        <label class="form-label">Nome *</label>
        <input type="text" name="name" id="edit-name" required class="input">
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
        <div class="form-group">
          <label class="form-label">Data</label>
          <input type="date" name="date_event" id="edit-date" class="input">
        </div>
        <div class="form-group">
          <label class="form-label">Prefixo</label>
          <input type="text" name="order_prefix" id="edit-prefix" class="input" style="text-transform:uppercase;" maxlength="10">
        </div>
      </div>
      <div class="form-group">
        <label class="form-label">Descrição</label>
        <textarea name="description" id="edit-desc" class="input" rows="2"></textarea>
      </div>
      <div class="form-group">
        <label class="form-label">Estado</label>
        <select name="status" id="edit-status" class="input">
          <option value="hidden">○ Oculto — não visível para clientes</option>
          <option value="active">● Ativo — visível na galeria pública</option>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Nova password <span style="font-weight:400;color:#AEAEB2;">(deixa em branco para não alterar)</span></label>
        <input type="text" name="password" id="edit-pass" class="input" placeholder="Nova password ou vazio para manter" autocomplete="off">
        <div id="edit-pass-status" style="font-size:11px;color:#AEAEB2;margin-top:4px;"></div>
      </div>
      <div style="display:flex;gap:10px;margin-top:8px;">
        <button type="button" onclick="closeModal('edit')" class="btn btn-secondary" style="flex:1;">Cancelar</button>
        <button type="submit" class="btn btn-primary" style="flex:1;">Guardar</button>
      </div>
    </form>
  </div>
</div>

<script>
function openModal(id) { document.getElementById('modal-'+id).style.display='flex'; }
function closeModal(id) { document.getElementById('modal-'+id).style.display='none'; }

function genPrefix(v, prefix) {
  const p = v.toUpperCase().replace(/[^A-Z0-9]/g,'').substring(0,10) || 'ENC';
  const el = document.getElementById(prefix+'-prefix');
  const eg = document.getElementById(prefix+'-prefix-eg');
  if(el && !el.dataset.edited) el.value = p;
  if(eg) eg.textContent = (el?.value || p);
}

function openEdit(ev) {
  document.getElementById('edit-name').value   = ev.name   || '';
  document.getElementById('edit-date').value   = ev.date_event || '';
  document.getElementById('edit-prefix').value = ev.order_prefix || '';
  document.getElementById('edit-desc').value   = ev.description || '';
  document.getElementById('edit-status').value = ev.status || 'hidden';
  document.getElementById('edit-form').action  = '<?= base_url("admin/eventos/") ?>' + ev.id + '/update';
  const passStatus = document.getElementById('edit-pass-status');
  if (passStatus) passStatus.textContent = ev.password ? '🔒 Este evento tem password definida.' : '🔓 Sem password — acesso livre.';
  openModal('edit');
}
</script>
