<?php
$base = (isset($analyticsBase) ? $analyticsBase : '');

function healthColor(int $score): string {
    return $score >= 70 ? 'success' : ($score >= 50 ? 'warning' : 'danger');
}
function deltaHtml(?array $d): string {
    if ($d === null) return '<span class="delta-neu">—</span>';
    $sign = $d['abs'] >= 0 ? '+' : '';
    $cls  = $d['abs'] >= 0 ? 'delta-pos' : 'delta-neg';
    $absF = number_format($d['abs']);
    return "<span class=\"{$cls}\" style=\"white-space:nowrap;\">{$sign}{$absF} ({$sign}{$d['pct']}%)</span>";
}
?>

<?php
// Dashboard KPI strip — aggregate across all projects' latest snapshots
$allSnaps    = array_filter(array_column($projects, 'snapshot'));
$totalLeads  = array_sum(array_column($allSnaps, 'total_leads'));
$totalSess   = array_sum(array_column($allSnaps, 'organic_sessions'));
$totalClicks = array_sum(array_column($allSnaps, 'gsc_clicks'));
$totalLlm    = array_sum(array_column($allSnaps, 'llm_total'));
$withData    = count($allSnaps);
$noData      = count($projects) - $withData;
$avgHealth   = $withData > 0 ? round(array_sum(array_map(fn($p) => $p['health_score'] ?? 0, $projects)) / count($projects)) : 0;
?>
<!-- KPI strip -->
<div class="row g-3 mb-4">
  <?php $kpis = [
    ['Sessions',   number_format($totalSess),   '#7c3aed', 'bi-graph-up-arrow'],
    ['GSC Clicks', number_format($totalClicks),  '#0284c7', 'bi-cursor-fill'],
    ['Total Leads',number_format($totalLeads),   '#d97706', 'bi-telephone-fill'],
    ['AI/LLM Traffic',number_format($totalLlm), '#8b5cf6', 'bi-robot'],
    ['Clients w/ Data',$withData . ' / ' . count($projects), '#16a34a', 'bi-check2-circle'],
    ['Avg Health', $avgHealth . '/100',          $avgHealth >= 70 ? '#22c55e' : ($avgHealth >= 50 ? '#f59e0b' : '#ef4444'), 'bi-heart-pulse'],
  ]; foreach ($kpis as $k): ?>
  <div class="col-6 col-md-2">
    <div class="card border-0 shadow-sm p-3 h-100" style="border-left:3px solid <?= $k[2] ?>!important;">
      <div class="d-flex align-items-center gap-2 mb-1">
        <i class="bi <?= $k[3] ?>" style="color:<?= $k[2] ?>;font-size:.9rem;"></i>
        <span style="font-size:.68rem;color:#64748b;text-transform:uppercase;letter-spacing:.04em;"><?= $k[0] ?></span>
      </div>
      <div style="font-size:1.3rem;font-weight:800;color:<?= $k[2] ?>;"><?= $k[1] ?></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Period selector + controls -->
<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="fw-bold mb-0">Manager Rollup &amp; Project Drilldown</h5>
    <p class="text-muted small mb-0">Select a period to update the rollup table. Click a manager row to expand projects.</p>
  </div>
  <div class="d-flex gap-2 align-items-center flex-wrap">
    <div class="btn-group btn-group-sm" id="period-preset">
      <button class="btn btn-outline-secondary" data-days="7">7d</button>
      <button class="btn btn-outline-secondary active" data-days="30">30d</button>
      <button class="btn btn-outline-secondary" data-days="90">90d</button>
      <button class="btn btn-outline-secondary" data-days="180">6mo</button>
      <button class="btn btn-outline-secondary" data-days="365">YoY</button>
    </div>
    <input type="date" id="date-start" class="form-control form-control-sm" style="width:140px;" value="<?= date('Y-m-d', strtotime('-30 days')) ?>">
    <span class="text-muted small">to</span>
    <input type="date" id="date-end" class="form-control form-control-sm" style="width:140px;" value="<?= date('Y-m-d') ?>">
    <button class="btn btn-sm btn-primary" id="run-all-btn" type="button">
      <i class="bi bi-play-fill me-1"></i>Run All
    </button>
    <a href="<?= htmlspecialchars($base) ?>/api/manager-rollup/export/excel?start=<?= date('Y-m-d', strtotime('-30 days')) ?>&end=<?= date('Y-m-d') ?>"
       class="btn btn-sm btn-outline-success" id="export-mgr-btn">
      <i class="bi bi-file-earmark-excel me-1"></i>Export Excel
    </a>
  </div>
</div>

<!-- View toggle -->
<div class="d-flex gap-2 mb-3">
  <button class="btn btn-sm btn-primary" id="view-rollup" type="button">Manager Rollup</button>
  <button class="btn btn-sm btn-outline-secondary" id="view-projects" type="button">All Projects</button>
</div>

<!-- Manager Rollup Table -->
<div id="section-rollup">
  <div class="card border-0 shadow-sm mb-4">
    <div class="card-header fw-semibold d-flex align-items-center justify-content-between">
      <span>Manager Rollup</span>
      <span class="text-muted small" id="rollup-period"></span>
    </div>
    <div class="table-responsive table-scroll-wrap" id="rollup-scroll">
      <table class="table table-hover align-middle mb-0 no-datatable table-sticky-col" id="rollup-table" style="min-width:900px;white-space:nowrap;">
        <thead class="table-light">
          <tr>
            <th>Manager</th>
            <th class="text-center" data-sort="clients">Clients</th>
            <th class="text-center" title="Clients with declining leads">▼</th>
            <th class="text-end" data-sort="sessions">Sessions</th><th class="text-end">Δ</th>
            <th class="text-end" data-sort="clicks">Clicks</th><th class="text-end">Δ</th>
            <th class="text-end" data-sort="impressions">Impressions</th><th class="text-end">Δ</th>
            <th class="text-end" data-sort="leads">Leads</th><th class="text-end">Δ</th>
            <th class="text-end" data-sort="llm">AI/LLM</th><th class="text-end">Δ</th>
            <th class="text-end" data-sort="roas">ROAS</th>
            <th class="text-center">Health</th>
          </tr>
        </thead>
        <tbody id="rollup-tbody">
          <?php foreach ($rollup as $row): ?>
          <tr class="rollup-row"
              data-manager="<?= htmlspecialchars($row['manager']) ?>"
              data-clients="<?= $row['clients'] ?>"
              data-sessions="<?= $row['sessions'] ?>"
              data-clicks="<?= $row['clicks'] ?>"
              data-impressions="<?= $row['impressions'] ?>"
              data-leads="<?= $row['leads'] ?>"
              data-llm="<?= $row['llm'] ?>"
              data-roas="<?= $row['roas'] ?>">
            <td class="fw-semibold"><?= htmlspecialchars($row['manager']) ?></td>
            <td class="text-center"><?= $row['clients'] ?></td>
            <td class="text-center text-danger"><?= $row['declining'] > 0 ? $row['declining'] : '—' ?></td>
            <td class="text-end"><?= number_format($row['sessions']) ?></td>
            <td class="text-end"><?= deltaHtml($row['delta_sessions']) ?></td>
            <td class="text-end"><?= number_format($row['clicks']) ?></td>
            <td class="text-end"><?= deltaHtml($row['delta_clicks']) ?></td>
            <td class="text-end"><?= number_format($row['impressions']) ?></td>
            <td class="text-end"><?= deltaHtml($row['delta_impressions']) ?></td>
            <td class="text-end fw-semibold"><?= number_format($row['leads']) ?></td>
            <td class="text-end"><?= deltaHtml($row['delta_leads']) ?></td>
            <td class="text-end"><?= number_format($row['llm']) ?></td>
            <td class="text-end"><?= deltaHtml($row['delta_llm']) ?></td>
            <td class="text-end fw-semibold"><?= $row['roas'] ?>x</td>
            <td class="text-center">
              <span class="health-dot bg-<?= $row['health_color'] === 'green' ? 'success' : ($row['health_color'] === 'yellow' ? 'warning' : 'danger') ?>"></span>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- All Projects Table -->
<div id="section-projects" class="d-none">
  <div class="card border-0 shadow-sm mb-4">
    <div class="card-header fw-semibold d-flex align-items-center justify-content-between">
      <span>All Projects</span>
      <input type="text" class="form-control form-control-sm ms-auto" style="max-width:220px;" id="project-search" placeholder="🔍 Search…">
    </div>
    <div class="table-responsive table-scroll-wrap" id="projects-scroll-analytics">
      <table class="table table-hover align-middle mb-0 no-datatable table-sticky-col" style="min-width:800px;white-space:nowrap;">
        <thead class="table-light">
          <tr>
            <th>Project</th>
            <th>Manager</th>
            <th class="text-end">Sessions</th>
            <th class="text-end">Clicks</th>
            <th class="text-end">Leads</th>
            <th class="text-end">ROAS</th>
            <th class="text-center">Health</th>
            <th class="text-center">Last Fetched</th>
            <th></th>
          </tr>
        </thead>
        <tbody id="projects-tbody">
          <?php foreach ($projects as $p):
            $snap   = $p['snapshot'] ?? null;
            $health = (int)($p['health_score'] ?? 0);
            $hcls   = healthColor($health);
            $fetched= $snap ? date('d M', strtotime($snap['fetched_at'] ?? $snap['created_at'])) : '—';
            $stale  = !$snap || (time() - strtotime($snap['fetched_at'] ?? '2000-01-01')) > 604800;
          ?>
          <tr class="project-row" data-id="<?= (int)$p['id'] ?>">
            <td>
              <div class="fw-medium"><?= htmlspecialchars($p['business_name']) ?></div>
              <div class="text-muted small"><?= htmlspecialchars($p['business_category'] ?? '') ?></div>
            </td>
            <td class="small text-muted"><?= htmlspecialchars($p['manager_name'] ?? '—') ?></td>
            <td class="text-end small"><?= $snap ? number_format($snap['organic_sessions'] ?? 0) : '—' ?></td>
            <td class="text-end small"><?= $snap ? number_format($snap['gsc_clicks']       ?? 0) : '—' ?></td>
            <td class="text-end small fw-semibold"><?= $snap ? number_format($snap['total_leads'] ?? 0) : '—' ?></td>
            <td class="text-end small"><?= $p['roas'] > 0 ? $p['roas'] . 'x' : '—' ?></td>
            <td class="text-center">
              <?php if ($health > 0): ?>
              <span class="badge bg-<?= $hcls ?>-subtle text-<?= $hcls ?>"><?= $health ?></span>
              <?php else: ?>
              <span class="text-muted small">—</span>
              <?php endif; ?>
            </td>
            <td class="text-center small <?= $stale ? 'text-warning' : 'text-muted' ?>"><?= $fetched ?></td>
            <td class="text-end">
              <div class="d-flex gap-1 justify-content-end">
                <button class="btn btn-xs btn-outline-primary py-0 px-2 fetch-btn" data-id="<?= (int)$p['id'] ?>"
                        title="Run tracker for this project" style="font-size:.75rem;">
                  <i class="bi bi-play-fill"></i>
                </button>
                <a href="<?= htmlspecialchars($base) ?>/projects/<?= (int)$p['id'] ?>"
                   class="btn btn-xs btn-outline-secondary py-0 px-2 project-detail-link"
                   data-id="<?= (int)$p['id'] ?>"
                   data-name="<?= htmlspecialchars($p['business_name']) ?>"
                   data-domain="<?= htmlspecialchars($p['website_url'] ?? '') ?>"
                   style="font-size:.75rem;">
                  <i class="bi bi-graph-up"></i>
                </a>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Progress modal -->
<div class="modal fade" id="run-modal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Running Tracker — All Projects</h5></div>
      <div class="modal-body">
        <div class="d-flex align-items-center justify-content-between mb-2">
          <div id="run-progress-text" class="small text-muted">Initialising…</div>
        </div>
        <div class="progress mb-3"><div class="progress-bar progress-bar-striped progress-bar-animated" id="run-bar" style="width:0%"></div></div>
        <div id="run-project-list" style="max-height:320px;overflow-y:auto;"></div>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  const base = (document.querySelector('meta[name="base-url"]') || {}).content || '';
  let startDate = document.getElementById('date-start').value;
  let endDate   = document.getElementById('date-end').value;

  // ── Period presets ───────────────────────────────────────────────────────
  document.getElementById('period-preset').addEventListener('click', e => {
    const btn = e.target.closest('[data-days]');
    if (!btn) return;
    document.querySelectorAll('#period-preset .btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    const days = +btn.dataset.days;
    endDate   = new Date().toISOString().split('T')[0];
    startDate = new Date(Date.now() - days * 864e5).toISOString().split('T')[0];
    document.getElementById('date-start').value = startDate;
    document.getElementById('date-end').value   = endDate;
  });
  document.getElementById('date-start').addEventListener('change', e => startDate = e.target.value);
  document.getElementById('date-end').addEventListener('change',   e => endDate   = e.target.value);

  // ── View toggle ──────────────────────────────────────────────────────────
  document.getElementById('view-rollup').addEventListener('click', () => {
    document.getElementById('section-rollup').classList.remove('d-none');
    document.getElementById('section-projects').classList.add('d-none');
    document.getElementById('view-rollup').classList.replace('btn-outline-secondary','btn-primary');
    document.getElementById('view-projects').classList.replace('btn-primary','btn-outline-secondary');
  });
  document.getElementById('view-projects').addEventListener('click', () => {
    document.getElementById('section-projects').classList.remove('d-none');
    document.getElementById('section-rollup').classList.add('d-none');
    document.getElementById('view-projects').classList.replace('btn-outline-secondary','btn-primary');
    document.getElementById('view-rollup').classList.replace('btn-primary','btn-outline-secondary');
  });

  // ── Project search ────────────────────────────────────────────────────────
  document.getElementById('project-search')?.addEventListener('input', e => {
    const q = e.target.value.toLowerCase();
    document.querySelectorAll('#projects-tbody .project-row').forEach(row => {
      row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
  });

  // ── Project row → persist to localStorage before navigation ─────────────
  document.querySelectorAll('.project-row').forEach(row => {
    row.addEventListener('click', e => {
      if (e.target.closest('.fetch-btn') || e.target.closest('a')) return;
      const id   = row.dataset.id;
      const name = row.querySelector('.fw-medium')?.textContent?.trim() || '';
      try { localStorage.setItem('savit_project', JSON.stringify({ id: +id, name, domain: '' })); } catch(_){}
      window.location.href = base + '/projects/' + id;
    });
    row.style.cursor = 'pointer';
  });

  // ── Single project fetch ──────────────────────────────────────────────────
  document.addEventListener('click', async e => {
    const btn = e.target.closest('.fetch-btn');
    if (!btn) return;
    const id = btn.dataset.id;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
    try {
      const r = await fetch(base + '/api/projects/' + id + '/fetch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ start: startDate, end: endDate, period_type: 'custom' }),
      });
      const j = await r.json();
      btn.innerHTML = j.data?.success ? '<i class="bi bi-check-lg text-success"></i>' : '<i class="bi bi-x text-danger"></i>';
      if (j.data?.success) setTimeout(() => location.reload(), 800);
    } catch { btn.innerHTML = '<i class="bi bi-x text-danger"></i>'; }
  });

  // ── Run All (per-project progress list) ─────────────────────────────────
  document.getElementById('run-all-btn').addEventListener('click', async () => {
    const modal = new bootstrap.Modal(document.getElementById('run-modal'));
    modal.show();
    const prog = document.getElementById('run-progress-text');
    const bar  = document.getElementById('run-bar');
    const list = document.getElementById('run-project-list');
    prog.textContent = 'Starting…';
    bar.style.width  = '5%';
    list.innerHTML   = '';
    try {
      const r = await fetch(base + '/api/projects/fetch-all', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ start: startDate, end: endDate, period_type: 'custom' }),
      });
      const j = await r.json();
      const results = j.data?.results || [];
      const ok = results.filter(x => x.success).length;
      bar.style.width = '100%';
      prog.textContent = `Done — ${ok}/${results.length} succeeded`;
      list.innerHTML = results.map(x => `
        <div class="d-flex justify-content-between align-items-center py-1 border-bottom">
          <span class="small text-truncate" style="max-width:240px;">${x.business_name || 'Project ' + x.project_id}</span>
          <span class="badge ${x.success ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'}" style="font-size:.65rem;">
            ${x.success ? '✓ OK' : '✗ ' + (x.message || 'failed')}
          </span>
        </div>`).join('');
      setTimeout(() => { modal.hide(); location.reload(); }, 2500);
    } catch (e) {
      prog.textContent = 'Error: ' + e.message;
    }
  });

  // ── Project detail links → persist before navigating ───────────────────
  document.querySelectorAll('.project-detail-link').forEach(link => {
    link.addEventListener('click', function() {
      try { localStorage.setItem('savit_project', JSON.stringify({
        id: +this.dataset.id, name: this.dataset.name, domain: this.dataset.domain || ''
      })); } catch(_){}
    });
  });

  // ── Export URL: keep in sync with date pickers ───────────────────────────
  function updateExportUrl() {
    const el = document.getElementById('export-mgr-btn');
    if (el) el.href = base + '/api/manager-rollup/export/excel?start=' + startDate + '&end=' + endDate;
    document.getElementById('rollup-period').textContent = startDate + ' → ' + endDate;
  }
  document.getElementById('date-start').addEventListener('change', e => { startDate = e.target.value; updateExportUrl(); });
  document.getElementById('date-end').addEventListener('change',   e => { endDate   = e.target.value; updateExportUrl(); });
  // Also update when period preset is clicked
  document.getElementById('period-preset').addEventListener('click', () => setTimeout(updateExportUrl, 50));
  updateExportUrl();

  // ── Rollup table sortable columns ─────────────────────────────────────────
  document.querySelectorAll('#rollup-table th[data-sort]').forEach(th => {
    th.style.cursor = 'pointer';
    th.title = 'Click to sort';
  });
  let sortCol = null, sortAsc = true;
  document.getElementById('rollup-table')?.addEventListener('click', e => {
    const th = e.target.closest('th[data-sort]');
    if (!th) return;
    const col = th.dataset.sort;
    if (sortCol === col) sortAsc = !sortAsc; else { sortCol = col; sortAsc = false; }
    document.querySelectorAll('#rollup-table th').forEach(t => t.querySelector('.sort-icon')?.remove());
    const icon = document.createElement('span');
    icon.className = 'sort-icon ms-1';
    icon.textContent = sortAsc ? '▲' : '▼';
    th.appendChild(icon);
    const tbody = document.getElementById('rollup-tbody');
    const rows  = Array.from(tbody.querySelectorAll('tr'));
    rows.sort((a, b) => {
      const av = parseFloat(a.dataset[col] || 0);
      const bv = parseFloat(b.dataset[col] || 0);
      return sortAsc ? av - bv : bv - av;
    });
    rows.forEach(r => tbody.appendChild(r));
  });
  // Overflow fade hints
  function initOverflowHint(id) {
    const el = document.getElementById(id);
    if (!el) return;
    const check = () => el.classList.toggle('has-overflow', el.scrollLeft + el.clientWidth < el.scrollWidth - 4);
    check();
    el.addEventListener('scroll', check);
    window.addEventListener('resize', check);
  }
  initOverflowHint('rollup-scroll');
  initOverflowHint('projects-scroll-analytics');
})();
</script>
