<?php /* Painel de Integração Google Agenda */ ?>
<div class="page-header">
  <h1>Integração Google Agenda</h1>
  <p class="muted">Configure sua conexão e sincronize lembretes financeiros.</p>
  <div id="gcStatus" class="muted"></div>
  <small class="muted">Os dados são armazenados criptografados por tenant.</small>
</div>

<section class="card">
  <h2 class="card-title">Credenciais</h2>
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
    <div>
      <label>Calendar ID</label>
      <input id="calendarId" class="input" placeholder="primary" />
    </div>
    <div>
      <label>Client ID</label>
      <input id="clientId" class="input" placeholder="Google OAuth Client ID" />
    </div>
    <div>
      <label>Client Secret</label>
      <input id="clientSecret" class="input" type="password" placeholder="Google OAuth Client Secret" />
    </div>
    <div>
      <label>Refresh Token</label>
      <input id="refreshToken" class="input" type="password" placeholder="Token de atualização (offline)" />
    </div>
  </div>
  <div style="margin-top:1rem;display:flex;gap:0.5rem;">
    <button class="btn btn-primary" id="btnGcSave">Salvar Configuração</button>
    <span id="gcSaveMsg" class="muted" aria-live="polite"></span>
  </div>
</section>

<section class="card">
  <h2 class="card-title">Sincronização</h2>
  <div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
    <label>Antecedência (minutos)</label>
    <input id="remMin" class="input" type="number" value="60" min="5" style="width:100px;" />
    <button class="btn" id="btnSyncPayables">Sincronizar Contas a Pagar (próx. 30 dias)</button>
  </div>
  <div id="gcSyncMsg" style="margin-top:0.5rem;" class="muted"></div>
</section>

<script>
async function gcReq(path, opts={}) {
  const headers = Object.assign({ 'Content-Type': 'application/json' }, opts.headers || {});
  const res = await fetch(path, Object.assign({}, opts, { headers }));
  return res;
}

async function gcLoad() {
  const res = await gcReq('/api/integrations/google-calendar/config');
  if (!res.ok) { document.getElementById('gcStatus').textContent = 'Falha ao carregar config.'; return; }
  const j = await res.json();
  const cfg = j.config || {};
  document.getElementById('calendarId').value = cfg.calendar_id || 'primary';
  document.getElementById('gcStatus').textContent = (cfg.has_client && cfg.has_refresh_token) ? 'Configuração presente.' : 'Configuração incompleta.';
}

async function gcSave() {
  const calendarId = document.getElementById('calendarId').value.trim() || 'primary';
  const clientId = document.getElementById('clientId').value.trim();
  const clientSecret = document.getElementById('clientSecret').value.trim();
  const refreshToken = document.getElementById('refreshToken').value.trim();
  document.getElementById('gcSaveMsg').textContent = 'Salvando...';
  const res = await gcReq('/api/integrations/google-calendar/config', { method: 'POST', body: JSON.stringify({ calendar_id: calendarId, client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken }) });
  if (res.ok) { document.getElementById('gcSaveMsg').textContent = 'Salvo.'; gcLoad(); }
  else { const j = await res.json().catch(()=>({})); document.getElementById('gcSaveMsg').textContent = 'Erro: ' + (j.error || res.status); }
}

async function gcSyncPayables() {
  const reminderMinutes = parseInt(document.getElementById('remMin').value, 10) || 60;
  document.getElementById('gcSyncMsg').textContent = 'Sincronizando...';
  const res = await gcReq('/api/integrations/google-calendar/sync/payables', { method: 'POST', body: JSON.stringify({ reminder_minutes: reminderMinutes }) });
  const msgEl = document.getElementById('gcSyncMsg');
  if (!res.ok) { const j = await res.json().catch(()=>({})); msgEl.textContent = 'Erro: ' + (j.error || res.status); return; }
  const j = await res.json();
  msgEl.textContent = 'Eventos criados: ' + (j.created || 0);
}

document.getElementById('btnGcSave').addEventListener('click', gcSave);
document.getElementById('btnSyncPayables').addEventListener('click', gcSyncPayables);
gcLoad();
</script>