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

$user = requireAuth();
$id   = (int)($_GET['id'] ?? 0);
$proj = getProject($id, $user['id']);
if (!$proj) { flash('error', 'Project not found.'); redirect(APP_URL . '/projects.php'); }

$tab = $_GET['tab'] ?? 'intake';

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

    if ($action === 'save_intake') {
        $fields = ['business_name','industry','website_url','project_type','goals',
                   'target_audience','competitors','design_style','color_preferences',
                   'features_needed','budget_range','timeline','additional_notes'];
        $data = ['project_id' => $id];
        foreach ($fields as $f) $data[$f] = trim($_POST[$f] ?? '');

        $existing = fetchOne("SELECT id FROM intake_forms WHERE project_id = ?", [$id]);
        if ($existing) {
            unset($data['project_id']);
            update('intake_forms', $data, 'project_id = ?', [$id]);
        } else {
            insert('intake_forms', $data);
        }
        // Only advance to 'brief' if still at intake stage — don't regress active/completed projects
        if ($proj['status'] === 'intake') {
            update('projects', ['status' => 'brief', 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        } else {
            update('projects', ['updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        }
        flash('success', 'Intake saved! You can now generate a brief.');
        redirect(APP_URL . "/project.php?id=$id&tab=intake");
    }

    if ($action === 'generate_brief') {
        $intake = fetchOne("SELECT * FROM intake_forms WHERE project_id = ?", [$id]);
        if (!$intake) { flash('error', 'Fill in the intake form first.'); redirect(APP_URL . "/project.php?id=$id&tab=brief"); }
        $content = generateBriefWithAI($intake, $user);
        $existing = fetchOne("SELECT id FROM briefs WHERE project_id = ?", [$id]);
        if ($existing) {
            update('briefs', ['content' => $content, 'edited_at' => date('Y-m-d H:i:s')], 'project_id = ?', [$id]);
        } else {
            insert('briefs', ['project_id' => $id, 'content' => $content]);
        }
        flash('success', 'Brief generated by AI!');
        redirect(APP_URL . "/project.php?id=$id&tab=brief");
    }

    if ($action === 'save_brief') {
        $content  = $_POST['brief_content'] ?? '';
        $existing = fetchOne("SELECT id FROM briefs WHERE project_id = ?", [$id]);
        if ($existing) {
            update('briefs', ['content' => $content, 'edited_at' => date('Y-m-d H:i:s')], 'project_id = ?', [$id]);
        } else {
            insert('briefs', ['project_id' => $id, 'content' => $content]);
        }
        flash('success', 'Brief saved.');
        redirect(APP_URL . "/project.php?id=$id&tab=brief");
    }

    if ($action === 'save_quote') {
        $existing = fetchOne("SELECT id FROM quotes WHERE project_id = ?", [$id]);
        $qData = [
            'project_id'  => $id,
            'quote_number'=> trim($_POST['quote_number'] ?? ''),
            'valid_until' => $_POST['valid_until'] ?? null,
            'notes'       => trim($_POST['notes'] ?? ''),
            'discount'    => (float)($_POST['discount'] ?? 0),
            'tax_percent' => (float)($_POST['tax_percent'] ?? 0),
        ];
        if ($existing) {
            $qid = $existing['id'];
            unset($qData['project_id']);
            update('quotes', $qData, 'id = ?', [$qid]);
            query("DELETE FROM quote_items WHERE quote_id = ?", [$qid]);
        } else {
            $qid = insert('quotes', $qData);
        }
        // Save line items — $_POST['items'] is array of [ idx => ['description'=>..,'quantity'=>..,'unit_price'=>..] ]
        $itemRows = $_POST['items'] ?? [];
        foreach ($itemRows as $row) {
            $desc = trim($row['description'] ?? '');
            if ($desc !== '') {
                insert('quote_items', [
                    'quote_id'    => $qid,
                    'description' => $desc,
                    'quantity'    => (float)($row['quantity']   ?? 1),
                    'unit_price'  => (float)($row['unit_price'] ?? 0),
                ]);
            }
        }
        // Only advance to 'quote' if still at quote stage or earlier
        $quoteStatuses = ['intake', 'brief', 'quote'];
        if (in_array($proj['status'], $quoteStatuses)) {
            update('projects', ['status' => 'quote', 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        } else {
            update('projects', ['updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        }
        flash('success', 'Quote saved.');
        redirect(APP_URL . "/project.php?id=$id&tab=quote");
    }

    if ($action === 'send_quote') {
        $qid = (int)$_POST['quote_id'];
        update('quotes', ['status' => 'sent'], 'id = ? AND project_id = ?', [$qid, $id]);
        flash('success', 'Quote marked as sent.');
        redirect(APP_URL . "/project.php?id=$id&tab=quote");
    }

    if ($action === 'save_contract') {
        $existing = fetchOne("SELECT id FROM contracts WHERE project_id = ?", [$id]);
        $cData = [
            'project_id' => $id,
            'title'      => trim($_POST['contract_title'] ?? 'Project Contract'),
            'content'    => $_POST['contract_content'] ?? '',
        ];
        if ($existing) {
            $cid = $existing['id'];
            unset($cData['project_id']);
            update('contracts', $cData, 'id = ?', [$cid]);
        } else {
            insert('contracts', $cData);
        }
        // Only advance to 'contract' if not already active/handover/completed
        $preContractStatuses = ['intake', 'brief', 'quote', 'contract'];
        if (in_array($proj['status'], $preContractStatuses)) {
            update('projects', ['status' => 'contract', 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        } else {
            update('projects', ['updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        }
        flash('success', 'Contract saved.');
        redirect(APP_URL . "/project.php?id=$id&tab=contract");
    }

    if ($action === 'sign_contract') {
        $cid = (int)$_POST['contract_id'];
        $sig = $_POST['sig_data'] ?? '';
        update('contracts',
            ['designer_signature' => $sig, 'status' => 'signed', 'signed_at' => date('Y-m-d H:i:s')],
            'id = ? AND project_id = ?', [$cid, $id]
        );
        update('projects', ['status' => 'active', 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        flash('success', 'Contract signed! Project is now active.');
        redirect(APP_URL . "/project.php?id=$id&tab=contract");
    }

    if ($action === 'add_handover') {
        insert('handover_items', [
            'project_id'   => $id,
            'category'     => $_POST['category'] ?? 'notes',
            'title'        => trim($_POST['h_title'] ?? ''),
            'content'      => trim($_POST['h_content'] ?? ''),
            'is_sensitive' => isset($_POST['is_sensitive']) ? 1 : 0,
        ]);
        // Only advance to 'handover' if not already completed
        if ($proj['status'] !== 'completed') {
            update('projects', ['status' => 'handover', 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        } else {
            update('projects', ['updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        }
        flash('success', 'Handover item added.');
        redirect(APP_URL . "/project.php?id=$id&tab=handover");
    }

    if ($action === 'delete_handover') {
        $hid = (int)$_POST['item_id'];
        query("DELETE FROM handover_items WHERE id = ? AND project_id = ?", [$hid, $id]);
        redirect(APP_URL . "/project.php?id=$id&tab=handover");
    }

    if ($action === 'save_invoice') {
        $studio   = getStudioSettings($user['id']);
        $existing = fetchOne("SELECT id FROM invoices WHERE project_id = ? AND user_id = ?", [$id, $user['id']]);
        $quote    = fetchOne("SELECT id FROM quotes WHERE project_id = ?", [$id]);
        $client   = fetchOne("SELECT currency FROM clients WHERE id = ?", [$proj['client_id']]);

        $currency = $_POST['currency'] ?? $client['currency'] ?? $studio['default_currency'] ?? 'USD';
        $invData  = [
            'invoice_number' => trim($_POST['invoice_number'] ?? nextInvoiceNumber($user['id'])),
            'currency'       => in_array($currency, ['USD','EUR','GBP']) ? $currency : 'USD',
            'issued_at'      => $_POST['issued_at'] ?? date('Y-m-d'),
            'due_date'       => $_POST['due_date'] ?: null,
            'notes'          => trim($_POST['notes'] ?? ''),
        ];

        if ($existing) {
            update('invoices', $invData, 'id = ?', [$existing['id']]);
            flash('success', 'Invoice updated.');
        } else {
            $invData['user_id']    = $user['id'];
            $invData['project_id'] = $id;
            $invData['quote_id']   = $quote['id'] ?? null;
            $invData['status']     = 'draft';
            insert('invoices', $invData);
            incrementInvoiceNumber($user['id']);
            flash('success', 'Invoice created.');
        }
        redirect(APP_URL . "/project.php?id=$id&tab=invoice");
    }

    if ($action === 'mark_invoice_paid') {
        $iid = (int)$_POST['invoice_id'];
        update('invoices', ['status' => 'paid'], 'id = ? AND user_id = ?', [$iid, $user['id']]);
        flash('success', 'Invoice marked as paid! 💰');
        redirect(APP_URL . "/project.php?id=$id&tab=invoice");
    }

    if ($action === 'complete_project') {
        update('projects', ['status' => 'completed', 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        flash('success', 'Project marked as completed! 🎉');
        redirect(APP_URL . "/project.php?id=$id&tab=handover");
    }
}

// ── Load tab data ───────────────────────────────────────────────────────────
$intake   = fetchOne("SELECT * FROM intake_forms WHERE project_id = ?", [$id]);
$brief    = fetchOne("SELECT * FROM briefs WHERE project_id = ?", [$id]);
$quote    = fetchOne("SELECT * FROM quotes WHERE project_id = ?", [$id]);
$qItems   = $quote ? fetchAll("SELECT * FROM quote_items WHERE quote_id = ?", [$quote['id']]) : [];
$contract = fetchOne("SELECT * FROM contracts WHERE project_id = ?", [$id]);
$handover = fetchAll("SELECT * FROM handover_items WHERE project_id = ? ORDER BY category, created_at", [$id]);
$invoice  = fetchOne("SELECT * FROM invoices WHERE project_id = ? AND user_id = ?", [$id, $user['id']]);
$studio   = getStudioSettings($user['id']);

$pipeline = ['intake','brief','quote','contract','active','handover','completed'];
$curIdx   = array_search($proj['status'], $pipeline);

renderHead($proj['title']);
renderNav($user);
renderFlash();
// project.php content starts here
?>

<!-- Project header -->
<div class="page-header">
  <div>
    <h1><?= e($proj['title']) ?></h1>
    <p class="subtitle"><?= e($proj['client_name']) ?><?= $proj['client_company'] ? ' · ' . e($proj['client_company']) : '' ?></p>
  </div>
  <div style="display:flex;gap:8px;align-items:center">
    <?= statusBadge($proj['status']) ?>
    <a href="<?= APP_URL ?>/website-spec.php?id=<?= $id ?>" class="btn btn-ghost btn-sm">📋 Website Spec</a>
    <a href="<?= APP_URL ?>/projects.php" class="btn btn-ghost btn-sm">← Projects</a>
  </div>
</div>

<!-- Pipeline -->
<div class="pipeline">
  <?php foreach ($pipeline as $i => $step): 
    $cls = '';
    if ($i < $curIdx) $cls = 'done';
    elseif ($i === $curIdx) $cls = 'current';
  ?>
  <div class="pipeline-step <?= $cls ?>"><?= ucfirst($step) ?><?= $cls === 'done' ? ' ✓' : '' ?></div>
  <?php endforeach; ?>
</div>

<!-- Tabs -->
<div class="tabs">
  <?php $tabs = ['intake' => 'Intake Form','brief' => 'AI Brief','quote' => 'Quote','contract' => 'Contract','handover' => 'Handover','invoice' => '🧾 Invoice']; ?>
  <?php foreach ($tabs as $key => $label): ?>
  <a href="?id=<?= $id ?>&tab=<?= $key ?>" class="tab <?= $tab === $key ? 'active' : '' ?>"><?= $label ?></a>
  <?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB: INTAKE FORM
═══════════════════════════════════════════════════════════════════════════ -->
<?php if ($tab === 'intake'): ?>
<div class="card">
  <h2 class="card-title">Client Intake Form</h2>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_intake">

    <div class="form-row">
      <div class="form-group">
        <label>Business Name</label>
        <input type="text" name="business_name" value="<?= e($intake['business_name'] ?? '') ?>">
      </div>
      <div class="form-group">
        <label>Industry</label>
        <input type="text" name="industry" value="<?= e($intake['industry'] ?? '') ?>" placeholder="e.g. E-commerce, Healthcare">
      </div>
    </div>
    <div class="form-row">
      <div class="form-group">
        <label>Current Website URL</label>
        <input type="url" name="website_url" value="<?= e($intake['website_url'] ?? '') ?>" placeholder="https://...">
      </div>
      <div class="form-group">
        <label>Project Type</label>
        <select name="project_type">
          <?php foreach (['New Website','Redesign','Landing Page','E-commerce','Web App','Branding','Other'] as $opt): ?>
          <option <?= ($intake['project_type'] ?? '') === $opt ? 'selected' : '' ?>><?= $opt ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="form-group">
      <label>Project Goals</label>
      <textarea name="goals" placeholder="What do you want to achieve with this project?"><?= e($intake['goals'] ?? '') ?></textarea>
    </div>
    <div class="form-group">
      <label>Target Audience</label>
      <textarea name="target_audience" placeholder="Who are your ideal customers?"><?= e($intake['target_audience'] ?? '') ?></textarea>
    </div>
    <div class="form-group">
      <label>Competitors / Inspiration Sites</label>
      <textarea name="competitors" placeholder="URLs or names of sites you admire or compete with"><?= e($intake['competitors'] ?? '') ?></textarea>
    </div>
    <div class="form-row">
      <div class="form-group">
        <label>Design Style</label>
        <select name="design_style">
          <?php foreach (['Modern / Minimal','Bold / Colorful','Corporate / Professional','Luxury / Premium','Playful / Friendly','Dark / Dramatic','Other'] as $opt): ?>
          <option <?= ($intake['design_style'] ?? '') === $opt ? 'selected' : '' ?>><?= $opt ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Color Preferences</label>
        <input type="text" name="color_preferences" value="<?= e($intake['color_preferences'] ?? '') ?>" placeholder="e.g. Blues and greens, avoid red">
      </div>
    </div>
    <div class="form-group">
      <label>Features Needed</label>
      <textarea name="features_needed" placeholder="Contact form, e-commerce, blog, booking system, etc."><?= e($intake['features_needed'] ?? '') ?></textarea>
    </div>
    <div class="form-row">
      <div class="form-group">
        <label>Budget Range</label>
        <select name="budget_range">
          <?php foreach (['Under $1,000','$1,000–$3,000','$3,000–$7,500','$7,500–$15,000','$15,000–$30,000','$30,000+','To be discussed'] as $opt): ?>
          <option <?= ($intake['budget_range'] ?? '') === $opt ? 'selected' : '' ?>><?= $opt ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Desired Timeline</label>
        <input type="text" name="timeline" value="<?= e($intake['timeline'] ?? '') ?>" placeholder="e.g. 6 weeks, ASAP, by Dec 1">
      </div>
    </div>
    <div class="form-group">
      <label>Additional Notes</label>
      <textarea name="additional_notes" placeholder="Anything else we should know?"><?= e($intake['additional_notes'] ?? '') ?></textarea>
    </div>

    <button class="btn btn-primary" type="submit">Save Intake & Continue →</button>
  </form>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB: AI BRIEF
═══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'brief'): ?>

<div style="display:flex;gap:12px;margin-bottom:20px;flex-wrap:wrap">
  <form method="POST" style="display:inline">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="generate_brief">
    <button class="btn btn-ai" type="submit" id="gen-btn" onclick="showSpinner()">
      <svg viewBox="0 0 24 24"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>
      <?= $brief ? 'Regenerate with AI' : 'Generate Brief with AI' ?>
    </button>
  </form>
  <?php if (!$intake): ?>
  <div class="flash flash-info" style="margin:0">Fill in the intake form first to enable AI generation.</div>
  <?php endif; ?>
</div>

<div class="ai-spinner" id="ai-spinner">
  <div class="spinner"></div> Generating brief with AI — this takes ~15 seconds…
</div>

<?php if ($brief): ?>
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
  <span style="font-size:13px;color:var(--text2)">Generated <?= formatDate($brief['generated_at']) ?><?= $brief['edited_at'] ? ' · Edited ' . formatDate($brief['edited_at']) : '' ?></span>
  <button class="btn btn-ghost btn-sm" onclick="document.getElementById('brief-editor').style.display='block';this.style.display='none'">Edit</button>
</div>
<div class="brief-content"><?= markdownToHtml($brief['content']) ?></div>

<!-- Editor -->
<div id="brief-editor" style="display:none;margin-top:20px">
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_brief">
    <div class="form-group">
      <label>Edit Brief (Markdown supported)</label>
      <textarea name="brief_content" style="min-height:500px;font-family:monospace;font-size:13px"><?= e($brief['content']) ?></textarea>
    </div>
    <button class="btn btn-primary" type="submit">Save Brief</button>
  </form>
</div>
<?php else: ?>
<div class="empty-state">
  <div class="big-icon">✨</div>
  <h3>No brief yet</h3>
  <p>Click "Generate Brief with AI" to create one from your intake data.</p>
</div>
<?php endif; ?>

<script>
function showSpinner() {
  document.getElementById('ai-spinner').classList.add('visible');
  document.getElementById('gen-btn').disabled = true;
}
</script>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB: QUOTE
═══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'quote'): ?>

<?php if ($quote): ?>
<div style="display:flex;gap:8px;margin-bottom:16px;align-items:center">
  <?= statusBadge($quote['status']) ?>
  <?php if ($quote['status'] === 'draft'): ?>
  <form method="POST" style="display:inline">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="send_quote">
    <input type="hidden" name="quote_id" value="<?= $quote['id'] ?>">
    <button class="btn btn-primary btn-sm" type="submit">Mark as Sent</button>
  </form>
  <?php endif; ?>
</div>
<?php endif; ?>

<div class="card">
  <h2 class="card-title">Quote Builder</h2>
  <form method="POST" id="quote-form">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_quote">

    <div class="form-row">
      <div class="form-group">
        <label>Quote Number</label>
        <input type="text" name="quote_number" value="<?= e($quote['quote_number'] ?? 'Q-' . date('Y') . '-001') ?>">
      </div>
      <div class="form-group">
        <label>Valid Until</label>
        <input type="date" name="valid_until" value="<?= e($quote['valid_until'] ?? date('Y-m-d', strtotime('+30 days'))) ?>">
      </div>
    </div>

    <div class="form-group">
      <label>Line Items</label>
      <div id="line-items-container">
        <?php if ($qItems): ?>
          <?php foreach ($qItems as $i => $item): ?>
          <div class="line-item-row">
            <input class="line-item-desc" type="text" name="items[<?= $i ?>][description]" value="<?= e($item['description']) ?>" required>
            <input class="line-item-qty" type="number" name="items[<?= $i ?>][quantity]" value="<?= $item['quantity'] ?>" min="0.01" step="0.01" oninput="calcRow(this.closest('.line-item-row'))">
            <input class="line-item-price" type="number" name="items[<?= $i ?>][unit_price]" value="<?= $item['unit_price'] ?>" min="0" step="0.01" oninput="calcRow(this.closest('.line-item-row'))">
            <span class="line-item-total"><?= formatMoney($item['quantity'] * $item['unit_price']) ?></span>
            <button type="button" class="btn btn-sm btn-danger line-item-del" onclick="this.closest('.line-item-row').remove();calcTotals()">✕</button>
          </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
      <button type="button" class="btn btn-ghost btn-sm" style="margin-top:8px" onclick="addLineItem()">+ Add Line Item</button>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Discount ($)</label>
        <input type="number" id="discount" name="discount" value="<?= e($quote['discount'] ?? 0) ?>" min="0" step="0.01" oninput="calcTotals()">
      </div>
      <div class="form-group">
        <label>Tax (%)</label>
        <input type="number" id="tax_percent" name="tax_percent" value="<?= e($quote['tax_percent'] ?? 0) ?>" min="0" step="0.01" oninput="calcTotals()">
      </div>
    </div>

    <div class="form-group">
      <label>Notes / Payment Terms</label>
      <textarea name="notes" placeholder="Payment due within 30 days…"><?= e($quote['notes'] ?? '') ?></textarea>
    </div>

    <?php
    $quoteCurrencyRow = fetchOne("SELECT currency FROM clients WHERE id = ?", [$proj['client_id']]);
    $quoteSym = currencySymbol($quoteCurrencyRow['currency'] ?? $studio['default_currency'] ?? 'USD');
    ?>
    <div class="quote-summary">
      <div class="row"><span>Subtotal</span><span id="subtotal-display"><?= $quoteSym ?>0.00</span></div>
      <div class="row"><span>Tax</span><span id="tax-display"><?= $quoteSym ?>0.00</span></div>
      <div class="row total"><span>Total</span><span id="total-display"><?= $quoteSym ?>0.00</span></div>
    </div>
    <script>var QUOTE_SYM = <?= json_encode($quoteSym) ?>;</script>

    <div style="margin-top:20px">
      <button class="btn btn-primary" type="submit">Save Quote</button>
    </div>
  </form>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB: CONTRACT
═══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'contract'): ?>

<div class="card contract-body">
  <h2 class="card-title">Contract</h2>
  <?php if ($contract && $contract['status'] === 'signed'): ?>
    <div class="flash flash-success">✓ Contract signed on <?= formatDate($contract['signed_at']) ?></div>
    <div class="brief-content" style="margin-top:16px"><?= markdownToHtml($contract['content']) ?></div>
    <?php if ($contract['designer_signature']): ?>
    <div style="margin-top:20px">
      <p style="font-size:13px;color:var(--text2);margin-bottom:8px">Designer Signature:</p>
      <img src="<?= e($contract['designer_signature']) ?>" style="background:#fff;border-radius:8px;padding:8px;max-width:300px">
    </div>
    <?php endif; ?>
  <?php else: ?>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_contract">
    <div class="form-group">
      <label>Contract Title</label>
      <input type="text" name="contract_title" value="<?= e($contract['title'] ?? 'Web Design Services Agreement') ?>">
    </div>
    <div class="form-group">
      <label>Contract Body (Markdown)</label>
      <textarea name="contract_content" style="min-height:400px;font-family:monospace;font-size:13px"><?= e($contract['content'] ?? defaultContract($proj)) ?></textarea>
    </div>
    <div style="display:flex;gap:8px">
      <button class="btn btn-primary" type="submit">Save Contract</button>
    </div>
  </form>

  <?php if ($contract): ?>
  <hr style="border-color:var(--border);margin:28px 0">
  <h3 style="font-family:'Syne',sans-serif;font-size:16px;margin-bottom:16px">Sign Contract (Designer)</h3>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="sign_contract">
    <input type="hidden" name="contract_id" value="<?= $contract['id'] ?>">
    <input type="hidden" name="sig_data" id="sig-data">
    <p style="font-size:13px;color:var(--text2);margin-bottom:12px">Draw your signature below:</p>
    <div class="sig-wrap"><canvas id="sig-canvas" width="500" height="140"></canvas></div>
    <div style="display:flex;gap:8px;margin-top:12px">
      <button type="button" id="sig-clear" class="btn btn-ghost btn-sm">Clear</button>
      <button type="submit" class="btn btn-primary">Sign & Activate Project</button>
    </div>
  </form>
  <?php endif; ?>
  <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB: HANDOVER
═══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'handover'): ?>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
  <div></div>
  <div style="display:flex;gap:8px">
    <?php if ($proj['status'] !== 'completed'): ?>
    <form method="POST" style="display:inline">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <input type="hidden" name="action" value="complete_project">
      <button class="btn btn-primary" type="submit" data-confirm="Mark this project as completed?">✓ Complete Project</button>
    </form>
    <?php else: ?>
    <span class="badge badge-green" style="font-size:14px;padding:6px 14px">🎉 Project Completed</span>
    <?php endif; ?>
  </div>
</div>

<!-- Add handover item -->
<div class="card" style="margin-bottom:24px">
  <h2 class="card-title">Add Handover Item</h2>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="add_handover">
    <div class="form-row">
      <div class="form-group">
        <label>Category</label>
        <select name="category">
          <option value="credentials">Credentials / Logins</option>
          <option value="files">Files / Assets</option>
          <option value="links">Links / URLs</option>
          <option value="instructions">Instructions</option>
          <option value="notes">Notes</option>
        </select>
      </div>
      <div class="form-group">
        <label>Title</label>
        <input type="text" name="h_title" required placeholder="e.g. WordPress Admin, Hosting cPanel">
      </div>
    </div>
    <div class="form-group">
      <label>Content</label>
      <textarea name="h_content" placeholder="Username, password, URL, instructions…"></textarea>
    </div>
    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-bottom:16px">
      <input type="checkbox" name="is_sensitive"> Mark as sensitive (blurred by default)
    </label>
    <button class="btn btn-primary" type="submit">Add Item</button>
  </form>
</div>

<!-- Handover items grid -->
<?php
$categories = ['credentials' => '🔑 Credentials', 'files' => '📁 Files', 'links' => '🔗 Links', 'instructions' => '📋 Instructions', 'notes' => '📝 Notes'];
$grouped    = [];
foreach ($handover as $item) $grouped[$item['category']][] = $item;
?>

<?php if ($grouped): ?>
<?php foreach ($categories as $cat => $label): ?>
  <?php if (!empty($grouped[$cat])): ?>
  <div class="portal-section">
    <h2><?= $label ?></h2>
    <div class="handover-grid">
      <?php foreach ($grouped[$cat] as $item): ?>
      <div class="handover-item">
        <div class="handover-item-header">
          <span class="handover-item-title"><?= e($item['title']) ?></span>
          <form method="POST" style="display:inline">
            <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
            <input type="hidden" name="action" value="delete_handover">
            <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
            <button class="btn btn-sm btn-danger" style="padding:3px 8px" data-confirm="Delete this item?" type="submit">✕</button>
          </form>
        </div>
        <div class="handover-item-content <?= $item['is_sensitive'] ? 'sensitive-mask' : '' ?>"><?= e($item['content']) ?></div>
        <?php if ($item['is_sensitive']): ?><small style="font-size:11px;color:var(--text2)">Click to reveal</small><?php endif; ?>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>
<?php endforeach; ?>
<?php else: ?>
<div class="empty-state">
  <div class="big-icon">📦</div>
  <h3>No handover items yet</h3>
  <p>Add credentials, files, and instructions to hand off the project.</p>
</div>
<?php endif; // end handover ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB: INVOICE
═══════════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'invoice'):
  $clientRow = fetchOne("SELECT * FROM clients WHERE id = ?", [$proj['client_id']]);
  $sub  = array_sum(array_map(fn($i) => $i['quantity'] * $i['unit_price'], $qItems));
  $disc = (float)($quote['discount']    ?? 0);
  $taxP = (float)($quote['tax_percent'] ?? 0);
  $tax  = ($sub - $disc) * ($taxP / 100);
  $tot  = $sub - $disc + $tax;

  // Currency: invoice overrides client default
  $invCurrency = $invoice['currency']
      ?? $clientRow['currency']
      ?? $studio['default_currency']
      ?? 'USD';
  $sym = currencySymbol($invCurrency);

  // Suggested due date
  $dueDays      = (int)($studio['payment_due_days'] ?? 30);
  $defaultDue   = date('Y-m-d', strtotime("+{$dueDays} days"));
  $nextInvNum   = $invoice ? $invoice['invoice_number'] : nextInvoiceNumber($user['id']);
?>

<!-- Status + actions bar -->
<?php if ($invoice): ?>
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:20px;">
  <?= statusBadge($invoice['status']) ?>
  <span style="font-size:13px;color:var(--text2)"><?= e($invoice['invoice_number']) ?></span>

  <?php if ($invoice['status'] !== 'paid'): ?>
  <form method="POST" style="display:inline">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="mark_invoice_paid">
    <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
    <button class="btn btn-ghost btn-sm" data-confirm="Mark this invoice as paid?" type="submit">💰 Mark Paid</button>
  </form>
  <?php endif; ?>

  <a href="<?= APP_URL ?>/invoice-pdf.php?invoice_id=<?= $invoice['id'] ?>&action=download"
     class="btn btn-ghost btn-sm" target="_blank">⬇ Download PDF</a>

  <?php if ($clientRow['email']): ?>
  <a href="<?= APP_URL ?>/invoice-pdf.php?invoice_id=<?= $invoice['id'] ?>&action=email"
     class="btn btn-ghost btn-sm"
     onclick="return confirm('Email invoice to <?= e(addslashes($clientRow['email'])) ?>?')">📧 Email to Client</a>
  <?php else: ?>
  <span style="font-size:12px;color:var(--text2)" title="Add client email in Clients page">📧 Email unavailable — no client email</span>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- Invoice form -->
<div class="card" style="max-width:680px;margin-bottom:24px;">
  <h2 class="card-title"><?= $invoice ? 'Edit Invoice' : 'Create Invoice' ?></h2>
  <?php if (!$quote && !$qItems): ?>
  <div class="flash flash-info" style="margin-bottom:18px;">ℹ Build a quote first — line items are pulled from the Quote tab.</div>
  <?php endif; ?>

  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_invoice">

    <div class="form-row">
      <div class="form-group">
        <label>Invoice Number</label>
        <input type="text" name="invoice_number" value="<?= e($nextInvNum) ?>" required>
      </div>
      <div class="form-group">
        <label>Currency</label>
        <select name="currency">
          <?php foreach (['USD' => '$ USD', 'EUR' => '€ EUR', 'GBP' => '£ GBP'] as $code => $label): ?>
          <option value="<?= $code ?>" <?= $invCurrency === $code ? 'selected' : '' ?>><?= $label ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Issue Date</label>
        <input type="date" name="issued_at" value="<?= e($invoice['issued_at'] ?? date('Y-m-d')) ?>" required>
      </div>
      <div class="form-group">
        <label>Due Date <small style="font-weight:400;color:var(--text2)">(default +<?= $dueDays ?> days)</small></label>
        <input type="date" name="due_date" value="<?= e($invoice['due_date'] ?? $defaultDue) ?>">
      </div>
    </div>

    <div class="form-group">
      <label>Notes / Payment Terms</label>
      <textarea name="notes" rows="3" placeholder="Payment within <?= $dueDays ?> days. Bank transfer preferred."><?= e($invoice['notes'] ?? ($quote['notes'] ?? '')) ?></textarea>
    </div>

    <button class="btn btn-primary" type="submit"><?= $invoice ? 'Update Invoice' : 'Save Invoice' ?></button>
    <?php if (!$studio['studio_name'] || !$studio['bank_details']): ?>
    <a href="<?= APP_URL ?>/admin.php?tab=studio" class="btn btn-ghost" style="margin-left:8px">⚙ Setup Studio Branding</a>
    <?php endif; ?>
  </form>
</div>

<!-- Preview -->
<?php if ($invoice && $qItems): ?>
<div class="card" style="max-width:680px;">
  <h2 class="card-title" style="margin-bottom:18px;">Preview</h2>

  <!-- Header row -->
  <div style="display:flex;justify-content:space-between;align-items:flex-start;padding-bottom:16px;border-bottom:2px solid var(--accent);margin-bottom:20px;">
    <div>
      <?php if ($studio['logo_url']): ?>
      <img src="<?= e($studio['logo_url']) ?>" style="height:44px;max-width:150px;object-fit:contain;margin-bottom:8px;display:block;"
           onerror="this.style.display='none'">
      <?php endif; ?>
      <div style="font-size:14px;font-weight:700"><?= e($studio['studio_name'] ?: $user['name']) ?></div>
      <?php if ($studio['email']): ?><div style="font-size:11px;color:var(--text2)"><?= e($studio['email']) ?></div><?php endif; ?>
    </div>
    <div style="text-align:right;">
      <div style="font-size:22px;font-weight:800;color:var(--accent);letter-spacing:-1px">INVOICE</div>
      <div style="font-size:13px;font-weight:700">#<?= e($invoice['invoice_number']) ?></div>
      <div style="font-size:11px;color:var(--text2);margin-top:2px">Issued: <?= date('d M Y', strtotime($invoice['issued_at'])) ?></div>
      <?php if ($invoice['due_date']): ?>
      <div style="font-size:11px;color:var(--text2)">Due: <?= date('d M Y', strtotime($invoice['due_date'])) ?></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Bill to -->
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:24px;">
    <div>
      <div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:1.5px;color:var(--accent2);margin-bottom:6px;">Bill To</div>
      <div style="font-size:13px;font-weight:700"><?= e($clientRow['name']) ?></div>
      <?php if ($clientRow['company']): ?><div style="font-size:11px;color:var(--text2)"><?= e($clientRow['company']) ?></div><?php endif; ?>
      <?php if ($clientRow['email']): ?><div style="font-size:11px;color:var(--text2)"><?= e($clientRow['email']) ?></div><?php endif; ?>
    </div>
    <div>
      <div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:1.5px;color:var(--accent2);margin-bottom:6px;">For</div>
      <div style="font-size:13px;font-weight:700"><?= e($proj['title']) ?></div>
      <?php if ($invCurrency !== ($studio['default_currency'] ?? 'USD')): ?>
      <div style="font-size:11px;color:var(--text2);margin-top:4px">Currency: <strong><?= e($invCurrency) ?></strong></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Line items -->
  <div class="table-wrap" style="margin-bottom:16px;">
    <table>
      <thead>
        <tr>
          <th style="background:var(--accent);color:#fff;font-size:10px;text-transform:uppercase;letter-spacing:.5px;">Description</th>
          <th style="background:var(--accent);color:#fff;font-size:10px;text-transform:uppercase;letter-spacing:.5px;text-align:center;width:60px;">Qty</th>
          <th style="background:var(--accent);color:#fff;font-size:10px;text-transform:uppercase;letter-spacing:.5px;text-align:right;width:120px;">Unit Price</th>
          <th style="background:var(--accent);color:#fff;font-size:10px;text-transform:uppercase;letter-spacing:.5px;text-align:right;width:120px;">Total</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($qItems as $idx => $item): ?>
        <tr style="background:<?= $idx % 2 === 0 ? 'var(--bg3)' : 'var(--bg2)' ?>">
          <td style="font-size:12px;"><?= e($item['description']) ?></td>
          <td style="text-align:center;font-size:12px;color:var(--text2)"><?= rtrim(rtrim(number_format($item['quantity'],2),'0'),'.') ?></td>
          <td style="text-align:right;font-size:12px;color:var(--text2)"><?= $sym . number_format($item['unit_price'],2) ?></td>
          <td style="text-align:right;font-size:12px;font-weight:600"><?= $sym . number_format($item['quantity']*$item['unit_price'],2) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Totals -->
  <div style="display:flex;justify-content:flex-end;margin-bottom:20px;">
    <div style="min-width:240px;">
      <div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px;color:var(--text2)">
        <span>Subtotal</span><span><?= $sym . number_format($sub,2) ?></span>
      </div>
      <?php if ($disc > 0): ?>
      <div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px;color:var(--red)">
        <span>Discount</span><span>−<?= $sym . number_format($disc,2) ?></span>
      </div>
      <?php endif; ?>
      <?php if ($taxP > 0): ?>
      <div style="display:flex;justify-content:space-between;padding:4px 0;font-size:12px;color:var(--text2)">
        <span>Tax (<?= $taxP ?>%)</span><span><?= $sym . number_format($tax,2) ?></span>
      </div>
      <?php endif; ?>
      <div style="display:flex;justify-content:space-between;padding:10px 12px;margin-top:6px;background:var(--accent);border-radius:var(--radius);font-weight:700;font-size:14px;color:#fff;">
        <span>Total (<?= e($invCurrency) ?>)</span><span><?= $sym . number_format($tot,2) ?></span>
      </div>
    </div>
  </div>

  <?php if ($studio['bank_details']): ?>
  <div style="background:var(--bg3);border-left:3px solid var(--accent);padding:12px 16px;border-radius:0 var(--radius) var(--radius) 0;margin-bottom:16px;">
    <div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--accent2);margin-bottom:8px;">Payment Details</div>
    <?php foreach (array_filter(array_map('trim', explode("\n", $studio['bank_details']))) as $line): ?>
    <div style="font-size:11px;color:var(--text2);margin-bottom:2px;"><?= e($line) ?></div>
    <?php endforeach; ?>
  </div>
  <?php else: ?>
  <div class="flash flash-info" style="font-size:12px;">⚠ No bank details — <a href="<?= APP_URL ?>/admin.php?tab=bank" style="color:var(--accent2)">add them in Studio Admin</a></div>
  <?php endif; ?>

  <div style="text-align:center;padding-top:14px;border-top:1px solid var(--border);font-size:12px;color:var(--accent2);font-weight:600;">
    <?= e($studio['invoice_footer'] ?: 'Thank you for your business!') ?>
  </div>
</div>

<?php elseif ($invoice && !$qItems): ?>
<div class="flash flash-info">Invoice saved — add line items on the <a href="?id=<?= $id ?>&tab=quote" style="color:var(--accent2)">Quote tab</a> to see a preview.</div>
<?php endif; ?>

<?php endif; // end all tabs ?>

<?php renderFooter(); ?>
<?php

function defaultContract(array $proj): string {
    $date = date('F j, Y');
    return <<<CONTRACT
# Web Design Services Agreement

**Date:** $date
**Designer:** {{Your Name / Studio}}
**Client:** {$proj['client_name']}
**Project:** {$proj['title']}

## Scope of Work

The Designer agrees to provide web design and development services as outlined in the approved project brief.

## Payment Terms

- 50% deposit due before project commencement
- Remaining 50% due upon project completion
- Invoices are due within 14 days of issue

## Revisions

The project includes up to 3 rounds of revisions. Additional revisions will be billed at the Designer's hourly rate.

## Intellectual Property

Upon receipt of full payment, the Client will own all custom design elements created for this project. The Designer retains the right to display the work in their portfolio.

## Confidentiality

Both parties agree to keep all proprietary information shared during this project confidential.

## Limitation of Liability

The Designer's liability is limited to the total amount paid under this agreement.

## Termination

Either party may terminate this agreement with 14 days written notice. The Client will pay for all work completed to date.

---

By signing below, both parties agree to the terms of this agreement.
CONTRACT;
}
?>
