<?php
$title = 'Fotos';
$breadcrumbs = [
  ['Eventos', base_url('admin/eventos')],
  [h($event['name']), null],
];
$topActions = '
  <span class="badge badge-'.($event['status']==='active'?'active':'hidden').'" style="font-size:13px;">'.($event['status']==='active'?'● Ativo':'○ Oculto').'</span>
  <a href="'.base_url('admin/eventos/'.$event['id'].'/relatorio').'" target="_blank" class="btn btn-secondary btn-sm">📊 Relatório Completo</a>
  <a href="'.base_url('admin/eventos/'.$event['id'].'/fotos-vendidas').'" target="_blank" class="btn btn-secondary btn-sm">📋 Fotos Vendidas</a>
  <a href="'.base_url('evento/'.h($event['slug'])).'" target="_blank" class="btn btn-ghost btn-sm">↗ Ver Galeria</a>
  <form method="post" action="'.base_url('admin/eventos/'.$event['id'].'/reset-vendas').'" style="display:inline;" onsubmit="return confirm(atob(\'RWxpbWluYXIgVE9EQVMgYXMgdmVuZGFzIGRlc3RlIGV2ZW50bz8=\'))">
    '.csrf_field().'
    <button type="submit" class="btn btn-danger btn-sm">🗑 Resetar Vendas</button>
  </form>';
?>

<style>
.log-line { display:flex; align-items:center; gap:8px; padding:5px 0; border-bottom:1px solid #f0f0f0; font-size:12px; }
.log-line:last-child { border:none; }
.log-ok   { color:#166534; }
.log-err  { color:#dc2626; }
.log-name { flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:#374151; }
.log-err .log-name { color:#dc2626; }
.log-msg  { font-size:11px; color:#dc2626; max-width:280px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.btn-retry-one {
  background:#fef2f2; color:#dc2626; border:1px solid #fecaca;
  padding:3px 10px; border-radius:5px; font-size:11px; font-weight:600;
  cursor:pointer; white-space:nowrap; flex-shrink:0; font-family:inherit;
}
.btn-retry-one:hover { background:#fee2e2; }
</style>

<!-- Zona de upload -->
<div class="card" style="margin-bottom:16px;">
  <div class="card-body">
    <div class="upload-zone" id="drop-zone"
         onclick="document.getElementById('file-input').click()"
         ondragover="event.preventDefault();this.classList.add('drag')"
         ondragleave="this.classList.remove('drag')"
         ondrop="event.preventDefault();this.classList.remove('drag');addFiles(event.dataTransfer.files)">
      <div class="upload-zone-icon">📤</div>
      <div class="upload-zone-title">Arrasta as fotografias aqui</div>
      <div class="upload-zone-sub">ou clica para selecionar · JPEG, PNG, WebP · máx. 10MB por foto</div>
      <input type="file" id="file-input" multiple accept="image/jpeg,image/png,image/webp"
             style="display:none;" onchange="addFiles(this.files)">
    </div>

    <!-- Painel de progresso -->
    <div id="prog-wrap" style="display:none; margin-top:16px;">

      <!-- Barra e contadores -->
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
        <span style="font-size:13px;font-weight:600;color:#374151;" id="prog-label">A processar...</span>
        <div style="display:flex;align-items:center;gap:10px;">
          <span id="prog-counts" style="font-size:12px;color:#6b7280;"></span>
          <button id="btn-retry-all" onclick="retryAll()" style="display:none;"
                  class="btn btn-danger btn-sm">↺ Retentar falhados (<span id="fail-count">0</span>)</button>
          <button id="btn-cancel" onclick="cancelUpload()"
                  style="background:#f5f5f5;border:1px solid #e5e5e5;color:#374151;padding:5px 12px;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit;">
            ✕ Cancelar
          </button>
        </div>
      </div>
      <div class="progress-bar-bg">
        <div id="prog-bar" class="progress-bar-fill" style="width:0%;transition:width .3s;"></div>
      </div>

      <!-- Resumo rápido -->
      <div style="display:flex;gap:16px;margin-top:8px;margin-bottom:12px;font-size:12px;">
        <span style="color:#166534;">✓ <span id="count-ok">0</span> carregadas</span>
        <span style="color:#dc2626;">✗ <span id="count-err">0</span> falhadas</span>
        <span style="color:#6b7280;">⏳ <span id="count-pend">0</span> em fila</span>
      </div>

      <!-- Log linha a linha -->
      <div id="prog-log" class="progress-log" style="max-height:280px;overflow-y:auto;border:1px solid #f0f0f0;border-radius:8px;padding:8px 12px;background:#fafafa;"></div>
    </div>
  </div>
</div>

<!-- Grid de fotos -->
<div class="card">
  <div class="card-header">
    <div>
      <div class="card-title">Fotografias do Evento</div>
      <div class="card-sub" id="photo-count-label"><?= count($photos) ?> fotografia<?= count($photos)!=1?'s':'' ?></div>
    </div>
    <?php if(count($photos)>0): ?>
    <div style="font-size:12px;color:#AEAEB2;">Passa o rato para ver ações · ★ define capa · × apaga</div>
    <?php endif; ?>
  </div>
  <div class="photo-admin-grid" id="photos-grid" <?= empty($photos)?'style="display:none"':'' ?>>
    <?php foreach($photos as $p): ?>
    <div class="photo-admin-cell" id="ph-<?= $p['id'] ?>">
      <img src="<?= imgurl('thumbnails', $p['event_id'], $p['filename']) ?>" loading="lazy">
      <div class="photo-admin-overlay">
        <form method="post" action="<?= base_url('admin/eventos/'.$event['id'].'/capa/'.$p['id']) ?>">
          <?= csrf_field() ?>
          <button type="submit" class="photo-admin-btn" style="background:rgba(255,193,7,.9);" title="Definir capa">★</button>
        </form>
        <button onclick="delPhoto(<?= $p['id'] ?>,<?= $event['id'] ?>)" class="photo-admin-btn"
                style="background:rgba(239,68,68,.9);color:#fff;" title="Apagar">×</button>
      </div>
      <?php if($event['cover_photo']===$p['thumb_path']): ?>
      <div class="photo-admin-cover">CAPA</div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>
  <?php if(empty($photos)): ?>
  <div id="empty-msg" style="padding:48px;text-align:center;color:#AEAEB2;">
    <div style="font-size:36px;margin-bottom:8px;">📷</div>
    <div style="font-weight:600;margin-bottom:4px;">Sem fotografias</div>
    <div style="font-size:12px;">Carrega as fotos usando a zona de upload acima</div>
  </div>
  <?php endif; ?>
</div>

<script>
const EID   = <?= $event['id'] ?>;
const BASE  = '<?= base_url() ?>';
const CSRF  = '<?= csrf_token() ?>';

// Fila de upload
let queue      = [];   // [{file, id}] — ficheiros a carregar
let failed     = [];   // [{file, name}] — ficheiros que falharam (para retry)
let processing = false;
let cancelled  = false;
let totalFiles = 0;
let doneOk     = 0;
let doneErr    = 0;

// ── Adicionar ficheiros à fila ─────────────────────────
function addFiles(fileList) {
  const files = Array.from(fileList);
  if (!files.length) return;

  // Validar tamanho máximo
  const toAdd = files.filter(f => {
    if (f.size > 10 * 1024 * 1024) {
      logLine(f.name, false, 'Ficheiro demasiado grande (máx. 10MB)', f);
      doneErr++;
      return false;
    }
    return true;
  });

  if (!toAdd.length) return;

  // Adicionar à fila com ID único
  toAdd.forEach((f, i) => queue.push({ file: f, id: Date.now() + i }));
  totalFiles += toAdd.length;
  cancelled   = false;

  document.getElementById('prog-wrap').style.display = 'block';
  updateCounts();

  if (!processing) processQueue();
}

// ── Processar fila sequencialmente ────────────────────
async function processQueue() {
  processing = true;
  while (queue.length > 0 && !cancelled) {
    const item = queue.shift();
    updateCounts();
    await uploadFile(item.file);
  }
  processing = false;
  onQueueFinished();
}

async function uploadFile(file) {
  const fd = new FormData();
  fd.append('photo', file);
  fd.append('_csrf', CSRF);

  try {
    const r   = await fetch(`${BASE}admin/eventos/${EID}/upload`, { method:'POST', body:fd });
    const raw = await r.text();
    let d;
    try { d = JSON.parse(raw); }
    catch(e) {
      const msg = raw.replace(/<[^>]+>/g,' ').replace(/\s+/g,' ').trim().slice(0,100);
      logLine(file.name, false, msg, file);
      doneErr++;
      return;
    }
    if (d.ok) {
      logLine(file.name, true, '', null);
      appendThumb(d.thumb, d.id);
      doneOk++;
    } else {
      logLine(file.name, false, d.error || 'Erro desconhecido', file);
      doneErr++;
    }
  } catch(e) {
    logLine(file.name, false, 'Erro de rede — sem resposta do servidor', file);
    doneErr++;
  }
  updateCounts();
}

// ── Log linha a linha com botão retry ──────────────────
function logLine(name, ok, msg, file) {
  const log = document.getElementById('prog-log');
  const div = document.createElement('div');
  div.className = 'log-line ' + (ok ? 'log-ok' : 'log-err');

  if (ok) {
    div.innerHTML = `<span>✓</span><span class="log-name">${esc(name)}</span>`;
  } else {
    // Guardar ficheiro falhado para retry
    if (file) failed.push({ file, name });
    const retryId = 'retry-' + Date.now() + Math.floor(Math.random()*10000);
    div.innerHTML = `
      <span>✗</span>
      <span class="log-name">${esc(name)}</span>
      <span class="log-msg" title="${esc(msg)}">${esc(msg)}</span>
      ${file ? `<button class="btn-retry-one" id="${retryId}" onclick="retryOne(this,'${retryId}')">↺ Retentar</button>` : ''}
    `;
    if (file) {
      // Associar o ficheiro ao botão via closure
      const btn = div.querySelector(`#${retryId}`);
      if (btn) btn._file = file;
    }
  }

  log.appendChild(div);
  log.scrollTop = log.scrollHeight;
  updateFailCount();
}

// ── Retry individual ───────────────────────────────────
async function retryOne(btn, id) {
  const file = btn._file;
  if (!file) return;

  btn.textContent = '⏳';
  btn.disabled = true;

  // Remover dos falhados
  failed = failed.filter(f => f.file !== file);

  const fd = new FormData();
  fd.append('photo', file);
  fd.append('_csrf', CSRF);

  try {
    const r   = await fetch(`${BASE}admin/eventos/${EID}/upload`, { method:'POST', body:fd });
    const raw = await r.text();
    let d;
    try { d = JSON.parse(raw); } catch(e) { d = { ok:false, error: raw.replace(/<[^>]+>/g,' ').trim().slice(0,80) }; }

    const line = btn.closest('.log-line');
    if (d.ok) {
      line.className = 'log-line log-ok';
      line.innerHTML = `<span>✓</span><span class="log-name">${esc(file.name)}</span><span style="font-size:11px;color:#166534;">retentado com sucesso</span>`;
      appendThumb(d.thumb, d.id);
      doneOk++;
      doneErr = Math.max(0, doneErr - 1);
    } else {
      failed.push({ file, name: file.name });
      btn.textContent = '↺ Retentar';
      btn.disabled = false;
      // Actualizar mensagem de erro
      const msgEl = line.querySelector('.log-msg');
      if (msgEl) msgEl.textContent = d.error || 'Erro';
    }
  } catch(e) {
    failed.push({ file, name: file.name });
    btn.textContent = '↺ Retentar';
    btn.disabled = false;
  }
  updateCounts();
  updateFailCount();
}

// ── Retry todos os falhados ───────────────────────────
async function retryAll() {
  if (!failed.length) return;
  const toRetry = [...failed];
  failed = [];

  document.getElementById('btn-retry-all').style.display = 'none';
  document.getElementById('prog-label').textContent = 'A retentar falhados...';
  cancelled = false;

  // Adicionar à fila e processar
  toRetry.forEach((item, i) => queue.push({ file: item.file, id: Date.now() + i }));
  totalFiles += toRetry.length;
  updateCounts();

  if (!processing) processQueue();
}

// ── Cancelar ──────────────────────────────────────────
function cancelUpload() {
  cancelled = true;
  queue = [];
  document.getElementById('prog-label').textContent = 'Cancelado.';
  document.getElementById('btn-cancel').style.display = 'none';
  updateCounts();
}

// ── UI helpers ────────────────────────────────────────
function updateCounts() {
  const pend = queue.length;
  document.getElementById('count-ok').textContent   = doneOk;
  document.getElementById('count-err').textContent  = doneErr;
  document.getElementById('count-pend').textContent = pend;

  const done = doneOk + doneErr;
  const pct  = totalFiles > 0 ? Math.round(done / totalFiles * 100) : 0;
  document.getElementById('prog-bar').style.width = pct + '%';
  document.getElementById('prog-counts').textContent = `${done} / ${totalFiles}`;

  if (pend > 0) {
    document.getElementById('prog-label').textContent = 'A processar...';
  }
}

function updateFailCount() {
  const n   = failed.length;
  const btn = document.getElementById('btn-retry-all');
  document.getElementById('fail-count').textContent = n;
  btn.style.display = n > 0 ? 'inline-flex' : 'none';
}

function onQueueFinished() {
  if (cancelled) return;
  const label = document.getElementById('prog-label');
  if (doneErr === 0) {
    label.textContent = `✓ Concluído — ${doneOk} fotografia${doneOk!==1?'s':''} carregada${doneOk!==1?'s':''}`;
    label.style.color = '#166534';
  } else {
    label.textContent = `Concluído — ${doneOk} ok, ${doneErr} falhada${doneErr!==1?'s':''}`;
    label.style.color = '#dc2626';
  }
  document.getElementById('btn-cancel').style.display = 'none';
  updateFailCount();
}

function esc(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// ── Grid helpers ──────────────────────────────────────
function appendThumb(src, pid) {
  const grid = document.getElementById('photos-grid');
  if (!grid) return;
  // Mostrar grid e esconder mensagem vazia
  grid.style.display = '';
  const emptyMsg = document.getElementById('empty-msg');
  if (emptyMsg) emptyMsg.style.display = 'none';
  const div = document.createElement('div');
  div.className = 'photo-admin-cell'; div.id = 'ph-'+pid;
  div.innerHTML = `<img src="${src}" loading="lazy">
    <div class="photo-admin-overlay">
      <button onclick="delPhoto(${pid},${EID})" class="photo-admin-btn"
              style="background:rgba(239,68,68,.9);color:#fff;" title="Apagar">×</button>
    </div>`;
  grid.appendChild(div);
  // Actualizar contador
  const lbl = document.getElementById('photo-count-label');
  if (lbl) {
    const n = grid.querySelectorAll('.photo-admin-cell').length;
    lbl.textContent = `${n} fotografia${n!==1?'s':''}`;
  }
}

async function delPhoto(pid, eid) {
  if (!confirm('Apagar esta fotografia?')) return;
  const fd = new FormData(); fd.append('_csrf', CSRF);
  try {
    const r = await fetch(`${BASE}admin/eventos/${eid}/foto/${pid}/delete`, { method:'POST', body:fd });
    const d = await r.json();
    if (d.ok) {
      document.getElementById('ph-'+pid)?.remove();
      const grid = document.getElementById('photos-grid');
      const lbl  = document.getElementById('photo-count-label');
      if (grid && lbl) {
        const n = grid.querySelectorAll('.photo-admin-cell').length;
        lbl.textContent = `${n} fotografia${n!==1?'s':''}`;
      }
    }
  } catch(e) { alert('Erro ao apagar: '+e.message); }
}
</script>
