<?php
$pageTitle = 'Projects';
// Pull latest analytics snapshot per project for inline stats
$analyticsSnaps = [];
try {
    $db = \CAE\Lib\Database::getInstance();
    $rows = $db->fetchAll("
        SELECT s.project_id, s.organic_sessions, s.gsc_clicks, s.total_leads,
               s.gsc_position, s.period_start, s.period_end
        FROM analytics_snapshots s
        INNER JOIN (SELECT project_id, MAX(id) AS mx FROM analytics_snapshots GROUP BY project_id) l
            ON l.project_id = s.project_id AND l.mx = s.id
    ");
    foreach ($rows as $r) $analyticsSnaps[(int)$r['project_id']] = $r;
} catch (\Throwable) {}
// Pull audit health per project
$auditHealth = [];
try {
    $hRows = $db->fetchAll("
        SELECT p.id,
               cr.total_pages,
               COALESCE(SUM(CASE WHEN cp.status_code>=400 THEN 1 ELSE 0 END),0) AS errs,
               COALESCE(SUM(CASE WHEN (cp.title IS NULL OR cp.title='') AND cp.status_code=200 THEN 1 ELSE 0 END),0) AS no_title
        FROM projects p
        LEFT JOIN crawl_runs cr ON cr.id=(SELECT id FROM crawl_runs WHERE project_id=p.id ORDER BY id DESC LIMIT 1)
        LEFT JOIN crawl_pages cp ON cp.crawl_run_id=cr.id
        GROUP BY p.id, cr.total_pages
    ");
    foreach ($hRows as $h) {
        $total = (int)($h['total_pages'] ?? 0);
        if ($total > 0) {
            $score = max(0, 100 - min(30, ($h['errs']/$total)*60) - min(20, ($h['no_title']/$total)*40));
            $auditHealth[(int)$h['id']] = (int)round($score);
        }
    }
} catch (\Throwable) {}
require __DIR__ . '/../layout/header.php';
?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h4 class="fw-bold mb-0">Projects</h4>
    <p class="text-muted mb-0 small">Brand rules, SEO config, and analytics — all in one place.</p>
  </div>
  <a href="<?= BASE_URL ?>/projects/create" class="btn btn-primary btn-sm">
    <i class="bi bi-plus-lg me-1"></i>New Project
  </a>
</div>

<?php if (empty($projects)): ?>
<div class="card border-2 text-center py-5">
  <div class="card-body">
    <i class="bi bi-briefcase fs-1 text-muted mb-3 d-block"></i>
    <h5 class="fw-semibold">No projects yet</h5>
    <p class="text-muted">Create your first project to set up brand rules, analytics, and audit config.</p>
    <a href="<?= BASE_URL ?>/projects/create" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Create First Project</a>
  </div>
</div>
<?php else: ?>
<div class="row g-3">
  <?php foreach ($projects as $proj):
    $snap   = $analyticsSnaps[(int)$proj['id']] ?? null;
    $hScore = $auditHealth[(int)$proj['id']] ?? null;
    $hColor = $hScore !== null ? ($hScore >= 80 ? '#22c55e' : ($hScore >= 60 ? '#f59e0b' : '#ef4444')) : null;
    $topicCount   = (new \CAE\Models\Project())->countTopics($proj['id']);
    $contentCount = (new \CAE\Models\Project())->countGeneratedContent($proj['id']);
  ?>
  <div class="col-md-6 col-xl-4">
    <div class="card border-0 shadow-sm h-100" style="<?= $hColor ? 'border-left:3px solid ' . $hColor . '!important;' : '' ?>">
      <div class="card-body pb-2">
        <!-- Header -->
        <div class="d-flex align-items-start justify-content-between mb-1">
          <div>
            <div class="fw-bold" style="font-size:.95rem;"><?= htmlspecialchars($proj['business_name']) ?></div>
            <?php if ($proj['website_url']): ?>
            <a href="<?= htmlspecialchars($proj['website_url']) ?>" target="_blank" class="text-muted" style="font-size:.72rem;text-decoration:none;">
              <i class="bi bi-link-45deg"></i><?= htmlspecialchars(parse_url($proj['website_url'], PHP_URL_HOST) ?: $proj['website_url']) ?>
            </a>
            <?php endif; ?>
          </div>
          <div class="d-flex gap-1 align-items-center">
            <?php if ($hScore !== null): ?>
            <span style="font-size:.7rem;font-weight:700;color:<?= $hColor ?>;white-space:nowrap;">
              <span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:<?= $hColor ?>;margin-right:2px;"></span><?= $hScore ?>
            </span>
            <?php endif; ?>
            <span class="badge <?= $proj['is_active'] ? 'bg-success-subtle text-success' : 'bg-secondary-subtle text-secondary' ?>" style="font-size:.65rem;">
              <?= $proj['is_active'] ? 'Active' : 'Inactive' ?>
            </span>
          </div>
        </div>

        <!-- Voice tags -->
        <div class="mb-2">
          <?php if ($proj['tone_voice']): ?>
          <span class="badge bg-primary-subtle text-primary me-1" style="font-size:.65rem;"><i class="bi bi-mic me-1"></i><?= htmlspecialchars($proj['tone_voice']) ?></span>
          <?php endif; ?>
          <?php if ($proj['content_intent']): ?>
          <span class="badge bg-warning-subtle text-warning" style="font-size:.65rem;"><?= htmlspecialchars($proj['content_intent']) ?></span>
          <?php endif; ?>
          <?php if ($proj['manager_name'] ?? ''): ?>
          <span class="badge bg-light text-muted" style="font-size:.65rem;"><i class="bi bi-person me-1"></i><?= htmlspecialchars($proj['manager_name']) ?></span>
          <?php endif; ?>
        </div>

        <!-- Analytics KPI strip -->
        <?php if ($snap): ?>
        <div class="d-flex gap-2 mb-2 px-1 py-1 rounded" style="background:#f8fafc;font-size:.72rem;">
          <div class="text-center flex-fill">
            <div class="text-muted">Sessions</div>
            <div class="fw-bold" style="color:#7c3aed;"><?= number_format($snap['organic_sessions'] ?? 0) ?></div>
          </div>
          <div class="text-center flex-fill border-start">
            <div class="text-muted">Clicks</div>
            <div class="fw-bold" style="color:#0284c7;"><?= number_format($snap['gsc_clicks'] ?? 0) ?></div>
          </div>
          <div class="text-center flex-fill border-start">
            <div class="text-muted">Leads</div>
            <div class="fw-bold" style="color:#d97706;"><?= number_format($snap['total_leads'] ?? 0) ?></div>
          </div>
          <div class="text-center flex-fill border-start">
            <div class="text-muted">Pos.</div>
            <div class="fw-bold"><?= number_format($snap['gsc_position'] ?? 0, 1) ?></div>
          </div>
        </div>
        <div style="font-size:.62rem;color:#94a3b8;" class="mb-1">
          Analytics: <?= date('d M', strtotime($snap['period_start'])) ?> – <?= date('d M Y', strtotime($snap['period_end'])) ?>
        </div>
        <?php else: ?>
        <div class="text-muted mb-2" style="font-size:.72rem;">
          <i class="bi bi-bar-chart me-1"></i>No analytics data — <a href="/Savit/Analytics/public/projects/<?= $proj['id'] ?>" style="font-size:.72rem;">run tracker →</a>
        </div>
        <?php endif; ?>
      </div>

      <!-- Footer actions -->
      <div class="card-footer bg-transparent border-top pt-2 pb-2 d-flex align-items-center justify-content-between">
        <div class="d-flex gap-3 text-muted" style="font-size:.72rem;">
          <span><i class="bi bi-tags me-1"></i><?= number_format($topicCount) ?> topics</span>
          <span><i class="bi bi-collection me-1"></i><?= number_format($contentCount) ?> content</span>
        </div>
        <div class="d-flex gap-1">
          <a href="<?= BASE_URL ?>/topics?project_id=<?= $proj['id'] ?>" class="btn btn-sm btn-outline-secondary py-0 px-2" title="Topics"><i class="bi bi-tags"></i></a>
          <a href="<?= BASE_URL ?>/projects/<?= $proj['id'] ?>/edit" class="btn btn-sm btn-outline-primary py-0 px-2" title="Settings"><i class="bi bi-gear"></i></a>
          <a href="/Savit/Audit/public/?p=<?= $proj['id'] ?>" class="btn btn-sm btn-outline-secondary py-0 px-2" title="Audit"><i class="bi bi-search"></i></a>
          <form method="POST" action="<?= BASE_URL ?>/projects/<?= $proj['id'] ?>/delete" class="d-inline confirm-delete">
            <button type="submit" class="btn btn-sm btn-outline-danger py-0 px-2" title="Delete"><i class="bi bi-trash"></i></button>
          </form>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<script>
// Set savit_project when user clicks edit on a project card
document.querySelectorAll('a[href*="/projects/"][href*="/edit"]').forEach(function (a) {
  a.addEventListener('click', function () {
    try {
      var card = a.closest('.card');
      if (!card) return;
      var nameEl = card.querySelector('.fw-bold');
      var linkEl = card.querySelector('a[href^="http"]');
      var idMatch = (a.href || '').match(/\/projects\/(\d+)\/edit/);
      if (!idMatch) return;
      localStorage.setItem('savit_project', JSON.stringify({
        id:     parseInt(idMatch[1]),
        name:   nameEl ? nameEl.textContent.trim() : '',
        domain: linkEl ? linkEl.href : '',
      }));
    } catch (_) {}
  });
});
</script>
<?php require __DIR__ . '/../layout/footer.php'; ?>
