<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/layout.php';

$user = requireAuth();

$status = $_GET['status'] ?? '';
$params = [$user['id']];
$where  = '';
if ($status) { $where = "AND p.status = ?"; $params[] = $status; }

$projects = fetchAll(
    "SELECT p.*, c.name AS client_name, c.company AS client_company
     FROM projects p JOIN clients c ON c.id = p.client_id
     WHERE p.user_id = ? $where
     ORDER BY p.updated_at DESC",
    $params
);

$statuses = ['intake','brief','quote','contract','active','handover','completed'];

renderHead('Projects');
renderNav($user);
renderFlash();
?>

<?php renderPageHeader('Projects', count($projects) . ' total',
  '<a href="' . APP_URL . '/project-new.php" class="btn btn-primary">
    <svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    New Project
  </a>'); ?>

<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:20px;">
  <a href="projects.php" class="btn btn-sm <?= !$status ? 'btn-primary' : 'btn-ghost' ?>">All</a>
  <?php foreach ($statuses as $s): ?>
  <a href="projects.php?status=<?= $s ?>" class="btn btn-sm <?= $status === $s ? 'btn-primary' : 'btn-ghost' ?>"><?= ucfirst($s) ?></a>
  <?php endforeach; ?>
</div>

<div class="card">
  <?php if ($projects): ?>
  <div class="table-wrap">
    <table>
      <thead>
        <tr><th>Project</th><th>Client</th><th>Status</th><th>Updated</th><th></th></tr>
      </thead>
      <tbody>
        <?php foreach ($projects as $p): ?>
        <tr>
          <td><strong><?= e($p['title']) ?></strong></td>
          <td><?= e($p['client_name']) ?><?php if ($p['client_company']): ?> <small style="color:var(--text2)">/ <?= e($p['client_company']) ?></small><?php endif; ?></td>
          <td><?= statusBadge($p['status']) ?></td>
          <td style="color:var(--text2)"><?= formatDate($p['updated_at']) ?></td>
          <td><a href="<?= APP_URL ?>/project.php?id=<?= $p['id'] ?>" class="btn btn-ghost btn-sm">Open →</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php else: ?>
  <div class="empty-state">
    <div class="big-icon">📁</div>
    <h3>No projects<?= $status ? ' with status "' . e($status) . '"' : '' ?></h3>
    <p>Create a new project to get started.</p>
    <a href="project-new.php" class="btn btn-primary" style="margin-top:16px">New Project</a>
  </div>
  <?php endif; ?>
</div>

<?php renderFooter(); ?>
