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

$user = requireAuth();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $id = insert('clients', [
            'user_id'      => $user['id'],
            'name'         => trim($_POST['name']),
            'email'        => trim($_POST['email']),
            'company'      => trim($_POST['company'] ?? ''),
            'phone'        => trim($_POST['phone']   ?? ''),
            'address'      => trim($_POST['address'] ?? ''),
            'currency'     => in_array($_POST['currency'] ?? '', ['USD','EUR','GBP']) ? $_POST['currency'] : 'USD',
            'portal_token' => slug(16),
        ]);
        flash('success', 'Client created.');
    } elseif ($action === 'delete') {
        $id = (int)$_POST['client_id'];
        $c  = fetchOne("SELECT id FROM clients WHERE id = ? AND user_id = ?", [$id, $user['id']]);
        if ($c) { query("DELETE FROM clients WHERE id = ?", [$id]); flash('success', 'Client deleted.'); }
    }
    redirect(APP_URL . '/clients.php');
}

$clients = fetchAll(
    "SELECT c.*, (SELECT COUNT(*) FROM projects p WHERE p.client_id = c.id) AS project_count
     FROM clients c WHERE c.user_id = ? ORDER BY c.created_at DESC",
    [$user['id']]
);

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

<?php renderPageHeader('Clients', count($clients) . ' total', '
  <button class="btn btn-primary" onclick="document.getElementById(\'new-modal\').style.display=\'flex\'">
    <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>
    Add Client
  </button>'); ?>

<div class="card">
  <?php if ($clients): ?>
  <div class="table-wrap">
    <table>
      <thead>
        <tr><th>Name</th><th>Company</th><th>Email</th><th>Projects</th><th>Portal</th><th></th></tr>
      </thead>
      <tbody>
        <?php foreach ($clients as $c): ?>
        <tr>
          <td><strong><?= e($c['name']) ?></strong></td>
          <td><?= e($c['company']) ?></td>
          <td><?= e($c['email']) ?></td>
          <td><?= $c['project_count'] ?></td>
          <td>
            <a href="<?= APP_URL ?>/portal.php?token=<?= e($c['portal_token']) ?>" target="_blank"
               class="btn btn-ghost btn-sm">View portal</a>
          </td>
          <td>
            <form method="POST" style="display:inline">
              <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="client_id" value="<?= $c['id'] ?>">
              <button class="btn btn-ghost btn-sm" data-confirm="Delete this client and all their data?" type="submit">Delete</button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php else: ?>
  <div class="empty-state">
    <div class="big-icon">👥</div>
    <h3>No clients yet</h3>
    <p>Add your first client to start a project.</p>
  </div>
  <?php endif; ?>
</div>

<!-- New client modal -->
<div id="new-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:200;align-items:center;justify-content:center;">
  <div class="card" style="width:100%;max-width:480px;position:relative">
    <h2 class="card-title">Add Client</h2>
    <form method="POST">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <input type="hidden" name="action" value="create">
      <div class="form-group"><label>Full Name *</label><input type="text" name="name" required></div>
      <div class="form-group"><label>Email *</label><input type="email" name="email" required></div>
      <div class="form-row">
        <div class="form-group"><label>Company</label><input type="text" name="company"></div>
        <div class="form-group"><label>Phone</label><input type="text" name="phone"></div>
      </div>
      <div class="form-group"><label>Address</label><textarea name="address" rows="3" placeholder="Street, City, State ZIP, Country"></textarea></div>
      <div class="form-group">
        <label>Currency</label>
        <select name="currency">
          <option value="USD">$ USD — US Dollar</option>
          <option value="EUR">€ EUR — Euro</option>
          <option value="GBP">£ GBP — British Pound</option>
        </select>
      </div>
      <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:8px;">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('new-modal').style.display='none'">Cancel</button>
        <button type="submit" class="btn btn-primary">Save Client</button>
      </div>
    </form>
  </div>
</div>

<?php renderFooter(); ?>
