<?php /* views/pages/followup.php */ ?>
<style>
  .card{background:#fff;border:1px solid #e5e7eb;border-radius:.75rem}
  .item{border:2px solid #dbeafe;border-radius:.75rem;background:#fff}
  .item .head{background:#eff6ff}
  .badge{background:#3b82f6;color:#fff;padding:.15rem .45rem;border-radius:9999px;font-size:.75rem}
</style>

<div class="p-6">
  <h1 class="text-2xl font-semibold mb-3">Follow up</h1>
  <p class="text-sm text-gray-600 mb-4">Envie 1 mensagem de follow por dia para quem <b>não respondeu</b> após o disparo inicial.</p>

  <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- Preferências -->
    <div class="card p-4 lg:col-span-1">
      <h2 class="text-lg font-medium mb-3">Preferências</h2>

      <div class="flex items-center justify-between mb-3">
        <span>Ativar Follow up</span>
        <label class="inline-flex items-center cursor-pointer">
          <input id="fEnabled" type="checkbox" class="sr-only">
          <span class="w-11 h-6 bg-gray-300 rounded-full relative transition">
            <span class="dot absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform"></span>
          </span>
        </label>
      </div>

      <div class="mb-3">
        <label class="block text-sm mb-1">Ignorar respostas nos primeiros (segundos)</label>
        <input id="fIgnore" type="number" min="0" class="w-full rounded border px-3 py-2" placeholder="Ex: 120">
        <p class="text-xs text-gray-500 mt-1">Protege dos “bots” do outro lado logo após o envio.</p>
      </div>

      <div class="mb-3">
        <label class="block text-sm mb-1">Fuso horário</label>
        <input id="fTz" type="text" class="w-full rounded border px-3 py-2" value="America/Sao_Paulo">
        <p class="text-xs text-gray-500 mt-1">IANA TZ (ex.: America/Sao_Paulo)</p>
      </div>

      <div class="flex items-center gap-2">
        <button id="btnPrefSave" class="rounded bg-gray-900 text-white px-4 py-2 text-sm">Salvar preferências</button>
        <span id="prefMsg" class="text-sm text-gray-500"></span>
      </div>
    </div>

    <!-- Editor de regras -->
    <div class="card p-4 lg:col-span-2">
      <div class="flex items-center justify-between mb-3">
        <h2 class="text-lg font-medium">Regras (dias)</h2>
        <div class="flex items-center gap-2">
          <input id="fpNome" class="rounded border px-3 py-2 text-sm" placeholder="Nome do pack de follow (ex: Padrão)">
          <button id="btnAddDay" class="rounded border px-3 py-2 text-sm">+ Adicionar dia</button>
        </div>
      </div>

      <div id="daysWrap" class="space-y-3"></div>

      <div class="mt-4 flex items-center gap-2">
        <button id="btnSave" class="rounded bg-indigo-600 text-white px-4 py-2">Salvar rascunho</button>
        <button id="btnPublish" class="rounded bg-emerald-600 text-white px-4 py-2">Publicar</button>
        <span id="mainMsg" class="text-sm text-gray-500"></span>
      </div>
    </div>
  </div>

  <!-- Lista -->
  <div class="card p-4 mt-6">
    <div class="flex items-center justify-between mb-3">
      <h2 class="text-lg font-medium">Meus packs de Follow up</h2>
      <button id="btnReload" class="rounded bg-gray-800 text-white px-3 py-1.5 text-sm">Atualizar</button>
    </div>
    <div class="overflow-x-auto">
      <table class="min-w-full text-sm">
        <thead><tr class="text-left border-b">
          <th class="py-2 pr-3">Nome</th><th class="py-2 pr-3">Status</th><th class="py-2 pr-3">Versão</th><th class="py-2">Ações</th>
        </tr></thead>
        <tbody id="tbodyList"></tbody>
      </table>
    </div>
  </div>
</div>

<script>
(function(){
  const API = 'api/followups.php', API_UPLOAD = 'api/upload.php';
  let editingId = null;

  const $ = (s,el=document)=>el.querySelector(s);
  const daysWrap = $('#daysWrap');
  const fpNome   = $('#fpNome');
  const mainMsg  = $('#mainMsg');
  const prefMsg  = $('#prefMsg');
  const fEnabled = $('#fEnabled');
  const fIgnore  = $('#fIgnore');
  const fTz      = $('#fTz');

  const esc = s => String(s||'').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('"','&quot;');
  async function fetchJSON(url,opts={}){ const r=await fetch(url,{credentials:'same-origin',...opts}); const t=await r.text(); let j; try{j=JSON.parse(t)}catch{}; return j&&r.ok?j:{ok:false,error:j?.error||t||'Falha'}; }

  // Toggle visual
  (function enhanceToggle(){
    const track = fEnabled.nextElementSibling, knob = track.querySelector('.dot');
    const paint = () => { track.style.background = fEnabled.checked ? '#16a34a' : '#d1d5db'; knob.style.transform = fEnabled.checked ? 'translateX(1.25rem)' : 'translateX(0)'; };
    fEnabled.addEventListener('change', paint); paint();
  })();

  // Preferências
  async function loadPrefs(){
    const j = await fetchJSON(`${API}?action=prefs&_=${Date.now()}`);
    if (!j.ok) return;
    const { enabled, ignore_seconds, timezone } = j.data || {};
    fEnabled.checked = !!enabled;
    fIgnore.value = (ignore_seconds ?? 0);
    fTz.value = timezone || 'America/Sao_Paulo';
    fEnabled.dispatchEvent(new Event('change')); // repinta o switch
  }
  async function savePrefs(){
    prefMsg.textContent = 'Salvando...';
    const body = new URLSearchParams({
      enabled: fEnabled.checked ? '1':'0',
      ignore_seconds: String(parseInt(fIgnore.value||'0',10)||0),
      timezone: fTz.value || ''
    });
    const j = await fetchJSON(`${API}?action=toggle_enabled`, {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body});
    prefMsg.textContent = j.ok ? 'Preferências salvas.' : ('Erro: '+(j.error||'Falha'));
    if (j.ok) loadPrefs();
  }
  $('#btnPrefSave').addEventListener('click', savePrefs);

  // UI de dias
  function renumber(){
    [...daysWrap.children].forEach((el,i)=>{
      $('[data-role="idx"]', el).textContent = i+1;
      $('[data-role="day"]', el).textContent = i+1;
    });
  }
  function readOne(el){
    const tipo = $('.fTipo', el).value;
    const hour = $('.fHour', el).value || '09:00';
    const out = {tipo, hour};
    if (tipo==='texto') out.conteudo = $('.fConteudo', el).value || '';
    else { out.url = $('.fUrl', el).value || ''; out.legenda = $('.fLegenda', el).value || ''; }
    return out;
  }
  function readAll(){
    const steps=[]; [...daysWrap.children].forEach(el=> steps.push(readOne(el)));
    return steps.map((s,i)=>({day:i+1, ...s}));
  }

  function addDay(data){
    const idx = daysWrap.children.length + 1;
    const d = document.createElement('div');
    d.className = 'item';
    d.innerHTML = `
      <div class="head flex items-center gap-2 px-3 py-2 rounded-t-lg">
        <span class="badge" data-role="idx">${idx}</span>
        <div class="font-medium">Dia <span data-role="day">${idx}</span></div>
        <div class="ml-auto flex items-center gap-2">
          <label class="text-xs text-gray-600">Hora
            <input class="fHour rounded border px-2 py-1 text-xs ml-1" type="time" value="${esc(data?.hour||'09:00')}">
          </label>
          <button class="btnUp rounded border px-2 py-1 text-xs" title="Subir">↑</button>
          <button class="btnDown rounded border px-2 py-1 text-xs" title="Descer">↓</button>
          <button class="btnDup rounded border px-2 py-1 text-xs" title="Duplicar">dup</button>
          <button class="btnDel rounded bg-rose-600 text-white px-2 py-1 text-xs" title="Remover">rem</button>
        </div>
      </div>
      <div class="px-3 py-3 grid grid-cols-1 md:grid-cols-3 gap-3">
        <label class="md:col-span-1 text-sm">Tipo
          <select class="fTipo w-full rounded border px-2 py-2">
            ${['texto','imagem','audio','pdf','video'].map(t=>`<option ${data?.tipo===t?'selected':''} value="${t}">${t}</option>`).join('')}
          </select>
        </label>
        <div class="fCfg md:col-span-2"></div>
      </div>
    `;
    const fTipo = $('.fTipo', d), fCfg = $('.fCfg', d);

    function renderCfg(){
      const t = fTipo.value;
      if (t==='texto'){
        fCfg.innerHTML = `
          <label class="block text-sm mb-1">Conteúdo</label>
          <textarea class="fConteudo w-full rounded border px-3 py-2" rows="3">${esc(data?.conteudo||'')}</textarea>`;
      } else {
        const accept = t==='imagem'?'image/*': t==='audio'?'audio/*': t==='pdf'?'application/pdf':'video/*';
        fCfg.innerHTML = `
          <div class="flex items-center gap-2 mb-2">
            <button type="button" class="btnUpload rounded border px-3 py-2 text-sm">Upload</button>
            <button type="button" class="btnPaste rounded border px-3 py-2 text-sm">Colar URL</button>
            <button type="button" class="btnOpen rounded border px-3 py-2 text-sm" ${data?.url?'':'disabled'}>Abrir</button>
            <button type="button" class="btnClear rounded border px-3 py-2 text-sm" ${data?.url?'':'disabled'}>Remover</button>
          </div>
          <input class="fUrl hidden" value="${esc(data?.url||'')}">
          <div class="prev text-xs text-gray-500 mb-1"></div>
          <label class="block text-sm mb-1">Legenda (opcional)</label>
          <input class="fLegenda w-full rounded border px-3 py-2" value="${esc(data?.legenda||'')}">
          <p class="text-xs text-gray-500 mt-1">Limite: 50MB. Tipos: ${accept.replace('*','')}</p>
        `;
        const btnUpload=$('.btnUpload',fCfg), btnPaste=$('.btnPaste',fCfg),
              btnOpen=$('.btnOpen',fCfg), btnClear=$('.btnClear',fCfg),
              fUrl=$('.fUrl',fCfg), prev=$('.prev',fCfg);

        const drawPrev=()=>{
          const url=fUrl.value.trim(); btnOpen.disabled=btnClear.disabled=!url;
          if (!url){ prev.textContent='Nenhum arquivo'; return; }
          if (t==='imagem') prev.innerHTML = `<img src="${esc(url)}" class="max-h-24 rounded border">`;
          else if (t==='audio') prev.innerHTML = `<audio controls src="${esc(url)}" class="w-full"></audio>`;
          else if (t==='pdf')   prev.innerHTML = `<a class="underline" target="_blank" href="${esc(url)}">Abrir PDF</a>`;
          else if (t==='video') prev.innerHTML = `<a class="underline" target="_blank" href="${esc(url)}">Abrir vídeo</a>`;
        };
        drawPrev();

        btnUpload.addEventListener('click', async ()=>{
          const fi=document.createElement('input'); fi.type='file'; fi.accept=accept;
          fi.onchange = async () => {
            if (!fi.files || !fi.files[0]) return;
            btnUpload.disabled = true; const old=btnUpload.textContent; btnUpload.textContent='Enviando...';
            const fd=new FormData(); fd.append('file', fi.files[0]); fd.append('kind', t==='pdf'?'pdf':(t==='imagem'?'imagem':(t==='audio'?'audio':'video')));
            try{
              const r=await fetch(API_UPLOAD,{method:'POST',body:fd,credentials:'same-origin'});
              const j=await r.json();
              if (j.ok){ fUrl.value=j.public_url||j.signed_url||''; drawPrev(); } else alert(j.error||'Falha no upload');
            }catch(e){ alert('Erro de rede'); }
            btnUpload.disabled=false; btnUpload.textContent=old;
          };
          fi.click();
        });
        btnPaste.addEventListener('click', ()=>{ const u=prompt('Cole a URL pública:'); if(!u) return; fUrl.value=u.trim(); drawPrev(); });
        btnOpen.addEventListener('click', ()=>{ const u=fUrl.value.trim(); if(u) window.open(u,'_blank'); });
        btnClear.addEventListener('click', ()=>{ fUrl.value=''; drawPrev(); });
      }
    }
    fTipo.addEventListener('change', renderCfg);
    renderCfg();

    $('.btnDel', d).addEventListener('click', ()=>{ d.remove(); renumber(); });
    $('.btnDup', d).addEventListener('click', ()=>{ const clone=readOne(d); addDay(clone); renumber(); });
    $('.btnUp', d).addEventListener('click', ()=>{ const p=d.previousElementSibling; if(p) daysWrap.insertBefore(d,p); renumber(); });
    $('.btnDown', d).addEventListener('click', ()=>{ const n=d.nextElementSibling; if(n) daysWrap.insertBefore(n,d); renumber(); });

    daysWrap.appendChild(d);
    renumber();
  }
  $('#btnAddDay').addEventListener('click', ()=> addDay({tipo:'texto', hour:'09:00'}));

  // Persistência do pack
  async function saveDraft(){
    const payload = {
      id: editingId,
      nome: fpNome.value || '',
      initial_ignore_seconds: parseInt(fIgnore.value||'0',10)||0,
      timezone: fTz.value || 'America/Sao_Paulo',
      steps: readAll()
    };
    mainMsg.textContent = 'Salvando...';
    const j = await fetchJSON(`${API}?action=save`, {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload)});
    mainMsg.textContent = j.ok ? 'Rascunho salvo.' : ('Erro: '+(j.error||'Falha'));
    if (j.ok && j.id && !editingId) editingId = j.id;
    await loadList();
  }
  async function publishPack(){
    if (!editingId){ mainMsg.textContent='Salve primeiro o rascunho.'; return; }
    mainMsg.textContent = 'Publicando...';
    const body = new URLSearchParams({id: editingId});
    const j = await fetchJSON(`${API}?action=publish`, {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body});
    mainMsg.textContent = j.ok ? `Publicado v${j.versao}.` : ('Erro: '+(j.error||'Falha'));
    await loadList();
  }
  $('#btnSave').addEventListener('click', saveDraft);
  $('#btnPublish').addEventListener('click', publishPack);

  // Lista
  async function loadList(){
    const tb = $('#tbodyList');
    const j = await fetchJSON(`${API}?action=list&_=${Date.now()}`);
    if (!j.ok){ tb.innerHTML = `<tr><td class="py-3" colspan="4">${j.error}</td></tr>`; return; }
    tb.innerHTML = (j.data||[]).map(f=>`
      <tr class="border-b">
        <td class="py-2 pr-3">${f.nome}</td>
        <td class="py-2 pr-3">${f.status}</td>
        <td class="py-2 pr-3">${f.versao}</td>
        <td class="py-2">
          <button class="actEdit px-2 py-1 rounded border" data-id="${f.id}">Editar</button>
          <button class="actDel px-2 py-1 rounded bg-rose-600 text-white ml-1" data-id="${f.id}">Excluir</button>
        </td>
      </tr>`).join('') || '<tr><td class="py-3" colspan="4">Nenhum pack</td></tr>';

    tb.querySelectorAll('.actEdit').forEach(b=> b.addEventListener('click', async ()=>{
      const id = b.getAttribute('data-id');
      const g = await fetchJSON(`${API}?action=get&id=${encodeURIComponent(id)}`);
      if (!g.ok){ mainMsg.textContent='Erro: '+(g.error||'Falha'); return; }
      editingId = g.data.id; fpNome.value = g.data.nome || '';
      fIgnore.value = g.data.initial_ignore_seconds ?? 0;
      fTz.value = g.data.timezone || 'America/Sao_Paulo';
      daysWrap.innerHTML = '';
      (g.data.steps||[]).forEach(s=> addDay(s));
      mainMsg.textContent = 'Rascunho carregado.';
    }));

    tb.querySelectorAll('.actDel').forEach(b=> b.addEventListener('click', async ()=>{
      if (!confirm('Excluir este pack?')) return;
      const id = b.getAttribute('data-id');
      const body = new URLSearchParams({id});
      const r = await fetchJSON(`${API}?action=delete`, {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body});
      if (!r.ok) alert(r.error||'Falha');
      if (editingId == id){ editingId=null; fpNome.value=''; daysWrap.innerHTML=''; }
      await loadList();
    }));
  }
  $('#btnReload').addEventListener('click', loadList);

  // Boot assíncrono
  (async function boot(){
    addDay({tipo:'texto', hour:'09:00'});
    await loadPrefs();
    loadList();
  })();

})();
</script>
