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

$token  = $_GET['token'] ?? '';
$client = fetchOne("SELECT * FROM clients WHERE portal_token = ?", [$token]);

if (!$client) {
    http_response_code(404);
    die('<h2 style="font-family:sans-serif;color:#fff;background:#0d0e11;min-height:100vh;display:flex;align-items:center;justify-content:center">Portal not found.</h2>');
}

// Portal password check
$sessionKey = 'portal_auth_' . $client['id'];
if ($client['portal_password'] && empty($_SESSION[$sessionKey])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['portal_pass'])) {
        if (password_verify($_POST['portal_pass'], $client['portal_password'])) {
            $_SESSION[$sessionKey] = true;
        } else {
            $pwError = 'Incorrect password.';
        }
    }
    if (empty($_SESSION[$sessionKey])) {
        // Show password form
        ?><!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Client Portal</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=DM+Sans:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= APP_URL ?>/assets/css/app.css">
</head><body>
<div class="auth-wrap">
  <div class="auth-card">
    <div class="auth-logo"><span class="brand-mark">D</span><span class="brand-name">debrieft</span></div>
    <h2>Client Portal</h2><p>Enter your access password to view your project.</p>
    <?php if (!empty($pwError)): ?><div class="flash flash-error"><?= e($pwError) ?></div><?php endif; ?>
    <form method="POST">
      <div class="form-group"><label>Password</label><input type="password" name="portal_pass" required autofocus></div>
      <button class="btn btn-primary" style="width:100%;justify-content:center" type="submit">Enter Portal</button>
    </form>
  </div>
</div></body></html><?php
        exit;
    }
}

// Sign contract as client
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['client_sign'])) {
    $cid = (int)$_POST['contract_id'];
    $sig = $_POST['sig_data'] ?? '';
    $c   = fetchOne("SELECT id FROM contracts WHERE id = ?", [$cid]);
    if ($c && $sig) {
        update('contracts', ['client_signature' => $sig, 'status' => 'signed', 'signed_at' => date('Y-m-d H:i:s')], 'id = ?', [$cid]);
    }
    // Log activity
    $pid = fetchOne("SELECT project_id FROM contracts WHERE id = ?", [$cid])['project_id'] ?? 0;
    if ($pid) insert('portal_activity', ['client_id' => $client['id'], 'project_id' => $pid, 'action' => 'signed_contract']);
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}

// Accept/decline quote
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quote_action'])) {
    $qid    = (int)$_POST['quote_id'];
    $action = $_POST['quote_action'] === 'accept' ? 'accepted' : 'declined';
    update('quotes', ['status' => $action], 'id = ?', [$qid]);
    $pid = fetchOne("SELECT project_id FROM quotes WHERE id = ?", [$qid])['project_id'] ?? 0;
    if ($pid) insert('portal_activity', ['client_id' => $client['id'], 'project_id' => $pid, 'action' => $action . '_quote']);
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}

$projects = fetchAll(
    "SELECT p.* FROM projects p WHERE p.client_id = ? ORDER BY p.updated_at DESC",
    [$client['id']]
);

?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= e($client['name']) ?> — Client Portal</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;700;800&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= APP_URL ?>/assets/css/app.css">
</head>
<body style="background:var(--bg)">
<div class="portal-wrap">
  <div class="portal-header">
    <div class="auth-logo" style="justify-content:center;margin-bottom:16px">
      <span class="brand-mark">D</span><span class="brand-name">debrieft</span>
    </div>
    <h1>Welcome, <?= e($client['name']) ?></h1>
    <p style="color:var(--text2);margin-top:8px">Your client portal — track project progress, review quotes and contracts.</p>
  </div>

  <?php foreach ($projects as $proj): ?>
  <?php
    $brief    = fetchOne("SELECT * FROM briefs WHERE project_id = ?",    [$proj['id']]);
    $quote    = fetchOne("SELECT * FROM quotes WHERE project_id = ?",    [$proj['id']]);
    $qItems   = $quote ? fetchAll("SELECT * FROM quote_items WHERE quote_id = ?", [$quote['id']]) : [];
    $contract = fetchOne("SELECT * FROM contracts WHERE project_id = ?", [$proj['id']]);
    $handover = fetchAll("SELECT * FROM handover_items WHERE project_id = ? AND is_sensitive = 0", [$proj['id']]);
    $pipeline = ['intake','brief','quote','contract','active','handover','completed'];
    $curIdx   = array_search($proj['status'], $pipeline);
  ?>
  <div class="card" style="margin-bottom:32px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
      <h2 style="font-family:'Syne',sans-serif;font-size:20px;font-weight:700"><?= e($proj['title']) ?></h2>
      <?= statusBadge($proj['status']) ?>
    </div>

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

    <?php if ($brief): ?>
    <div class="portal-section">
      <h2>Project Brief</h2>
      <div class="brief-content"><?= markdownToHtml($brief['content']) ?></div>
    </div>
    <?php endif; ?>

    <?php if ($quote): ?>
    <div class="portal-section">
      <h2>Quote <?= e($quote['quote_number']) ?> — <?= statusBadge($quote['status']) ?></h2>
      <table>
        <thead><tr><th>Description</th><th>Qty</th><th>Unit Price</th><th>Total</th></tr></thead>
        <tbody>
          <?php foreach ($qItems as $item): ?>
          <tr>
            <td><?= e($item['description']) ?></td>
            <td><?= $item['quantity'] ?></td>
            <td><?= formatMoney($item['unit_price']) ?></td>
            <td><?= formatMoney($item['quantity'] * $item['unit_price']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php
        $sub  = array_sum(array_map(fn($i) => $i['quantity'] * $i['unit_price'], $qItems));
        $disc = (float)$quote['discount'];
        $tax  = ($sub - $disc) * ($quote['tax_percent'] / 100);
        $tot  = $sub - $disc + $tax;
      ?>
      <div class="quote-summary" style="margin-top:12px">
        <?php if ($disc > 0): ?><div class="row"><span>Discount</span><span>- <?= formatMoney($disc) ?></span></div><?php endif; ?>
        <?php if ($quote['tax_percent'] > 0): ?><div class="row"><span>Tax (<?= $quote['tax_percent'] ?>%)</span><span><?= formatMoney($tax) ?></span></div><?php endif; ?>
        <div class="row total"><span>Total</span><span><?= formatMoney($tot) ?></span></div>
      </div>
      <?php if ($quote['status'] === 'sent'): ?>
      <div style="display:flex;gap:8px;margin-top:16px">
        <form method="POST" style="display:inline">
          <input type="hidden" name="quote_action" value="accept">
          <input type="hidden" name="quote_id" value="<?= $quote['id'] ?>">
          <button class="btn btn-primary" type="submit">✓ Accept Quote</button>
        </form>
        <form method="POST" style="display:inline">
          <input type="hidden" name="quote_action" value="decline">
          <input type="hidden" name="quote_id" value="<?= $quote['id'] ?>">
          <button class="btn btn-danger" type="submit">✕ Decline</button>
        </form>
      </div>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php if ($contract): ?>
    <div class="portal-section">
      <h2>Contract — <?= statusBadge($contract['status']) ?></h2>
      <div class="brief-content" style="max-height:360px;overflow-y:auto"><?= markdownToHtml($contract['content']) ?></div>
      <?php if ($contract['status'] !== 'signed'): ?>
      <div style="margin-top:20px">
        <p style="font-size:14px;color:var(--text2);margin-bottom:10px">Sign below to accept the contract:</p>
        <form method="POST">
          <input type="hidden" name="client_sign" value="1">
          <input type="hidden" name="contract_id" value="<?= $contract['id'] ?>">
          <input type="hidden" name="sig_data" id="sig-data">
          <div class="sig-wrap"><canvas id="sig-canvas" width="500" height="140"></canvas></div>
          <div style="display:flex;gap:8px;margin-top:10px">
            <button type="button" id="sig-clear" class="btn btn-ghost btn-sm">Clear</button>
            <button type="submit" class="btn btn-primary">Sign Contract</button>
          </div>
        </form>
      </div>
      <?php else: ?>
      <p style="color:var(--green);margin-top:12px;font-size:14px">✓ Signed on <?= formatDate($contract['signed_at']) ?></p>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php if ($handover): ?>
    <div class="portal-section">
      <h2>Project Handover</h2>
      <div class="handover-grid">
        <?php foreach ($handover as $item): ?>
        <div class="handover-item">
          <div class="handover-item-title" style="margin-bottom:8px"><?= e($item['title']) ?></div>
          <div class="handover-item-content"><?= e($item['content']) ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>

  <?php if (!$projects): ?>
  <div class="empty-state">
    <div class="big-icon">📋</div>
    <h3>No active projects</h3>
    <p>Your designer hasn't started a project for you yet.</p>
  </div>
  <?php endif; ?>

  <p style="text-align:center;color:var(--text2);font-size:12px;margin-top:48px">Powered by <strong>Debrieft</strong></p>
</div>
<script src="<?= APP_URL ?>/assets/js/app.js"></script>
</body>
</html>
