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

$user    = requireAuth();
$clients = fetchAll("SELECT id, name, company FROM clients WHERE user_id = ? ORDER BY name", [$user['id']]);
$error   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $title     = trim($_POST['title']            ?? '');
    $clientId  = (int)($_POST['client_id']        ?? 0);
    $newName   = trim($_POST['new_client_name']   ?? '');
    $newEmail  = trim($_POST['new_client_email']  ?? '');

    do {
        if (!$title) { $error = 'Project title is required.'; break; }

        // Create inline client if no existing client selected
        if (!$clientId) {
            if (!$newName || !$newEmail) { $error = 'Please select an existing client or provide a new client name and email.'; break; }
            $clientId = insert('clients', [
                'user_id'      => $user['id'],
                'name'         => $newName,
                'email'        => $newEmail,
                'portal_token' => slug(16),
            ]);
        }

        $pid = insert('projects', [
            'user_id'   => $user['id'],
            'client_id' => $clientId,
            'title'     => $title,
            'status'    => 'intake',
            'slug'      => slug(),
        ]);

        flash('success', 'Project created! Fill in the intake form to get started.');
        redirect(APP_URL . '/project.php?id=' . $pid . '&tab=intake');
    } while (false);
}

renderHead('New Project');
renderNav($user);
renderFlash();
?>

<?php renderPageHeader('New Project', 'Set up a new client project'); ?>

<?php if ($error): ?><div class="flash flash-error"><?= e($error) ?></div><?php endif; ?>

<div class="card" style="max-width:620px">
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">

    <div class="form-group">
      <label>Project Title *</label>
      <input type="text" name="title" required placeholder="e.g. Acme Corp Website Redesign" value="<?= e($_POST['title'] ?? '') ?>">
    </div>

    <div class="form-group">
      <label>Select Existing Client</label>
      <select name="client_id" id="client-select" onchange="toggleNewClient(this.value)">
        <option value="">— or create new client below —</option>
        <?php foreach ($clients as $c): ?>
        <option value="<?= $c['id'] ?>" <?= (int)($_POST['client_id'] ?? 0) === $c['id'] ? 'selected' : '' ?>>
          <?= e($c['name']) ?><?= $c['company'] ? ' (' . e($c['company']) . ')' : '' ?>
        </option>
        <?php endforeach; ?>
      </select>
    </div>

    <div id="new-client-fields">
      <p style="font-size:13px;color:var(--text2);margin-bottom:12px;margin-top:-6px">— New client —</p>
      <div class="form-row">
        <div class="form-group">
          <label>Client Name</label>
          <input type="text" name="new_client_name" placeholder="John Smith" value="<?= e($_POST['new_client_name'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label>Client Email</label>
          <input type="email" name="new_client_email" placeholder="john@example.com" value="<?= e($_POST['new_client_email'] ?? '') ?>">
        </div>
      </div>
    </div>

    <div style="display:flex;gap:10px;margin-top:8px;flex-wrap:wrap">
      <a href="projects.php" class="btn btn-ghost">Cancel</a>
      <button class="btn btn-primary" type="submit">Create Project →</button>
    </div>
  </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  toggleNewClient(document.getElementById('client-select').value);
});
</script>

<?php renderFooter(); ?>
