<?php
requirePermission($conn, 'deals', 'view');
$search = trim($_GET['search'] ?? '');
$page_num = max(1, (int)($_GET['p'] ?? 1)); $per_page=25; $offset=($page_num-1)*$per_page;
$stageWonExpr = columnExists($conn, 'stage', 'result_type') ? "(s.result_type='won' OR LOWER(s.name)='won' OR LOWER(l.status)='won')" : "(LOWER(s.name)='won' OR LOWER(l.status)='won')";
$where = "l.account_id=$account_id AND l.datetime_deleted IS NULL AND $stageWonExpr";
if ($search !== '') { $safe=sanitize($conn,$search); $where .= " AND (l.title LIKE '%$safe%' OR c.customer_name LIKE '%$safe%' OR c.business_name LIKE '%$safe%' OR i.name LIKE '%$safe%')"; }
$totalQ=$conn->query("SELECT COUNT(*) total FROM leads l LEFT JOIN stage s ON s.id=l.stage_id LEFT JOIN customers c ON c.id=l.customer_id LEFT JOIN items i ON i.id=l.item_id WHERE $where");
$total_rows=$totalQ?(int)$totalQ->fetch_assoc()['total']:0; $total_pages=max(1,(int)ceil($total_rows/$per_page));
$list=$conn->query("SELECT l.*, c.customer_name, c.business_name, i.name item_name, i.currency item_currency, s.name stage_name, s.color stage_color FROM leads l LEFT JOIN stage s ON s.id=l.stage_id LEFT JOIN customers c ON c.id=l.customer_id LEFT JOIN items i ON i.id=l.item_id WHERE $where ORDER BY l.datetime_updated DESC, l.datetime_created DESC LIMIT $offset,$per_page");
function dealQuotationCount($conn,$account_id,$customer_id,$item_id){ $customer_id=(int)$customer_id; $item_id=(int)$item_id; $sql="SELECT COUNT(*) cnt FROM quotations q WHERE q.account_id=$account_id AND q.customer_id=$customer_id"; if($item_id) $sql.=" AND (q.item_id=$item_id OR EXISTS(SELECT 1 FROM quotation_items qi WHERE qi.quotation_id=q.id AND qi.item_id=$item_id))"; $r=$conn->query($sql); return $r?(int)$r->fetch_assoc()['cnt']:0; }
?>
<div class="fade-in">
  <div class="toolbar" style="justify-content:space-between;gap:12px;flex-wrap:wrap"><div><span class="card-title">Deals</span><div class="text-xs text-muted">Won leads only</div></div><form method="get" class="deals-search-form"><input type="hidden" name="page" value="deals"><input class="form-control" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search deal / customer / item"><button class="btn btn-primary">Search</button><a class="btn btn-secondary" href="index.php?page=deals">Clear</a></form></div>
  <style>
  .deals-search-form{display:grid;grid-template-columns:minmax(260px,1fr) auto auto;gap:10px;align-items:center;max-width:580px;width:100%;}
  .deals-search-form .form-control{height:46px;border-radius:12px;padding:0 16px;font-weight:600;}
  .deals-search-form .btn{height:46px;border-radius:12px;padding:0 22px;display:inline-flex;align-items:center;justify-content:center;}
  @media(max-width:700px){.deals-search-form{grid-template-columns:1fr}.deals-search-form .btn{width:100%;}}
  </style>
  <div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>#</th><th>Deal</th><th>Customer</th><th>Item</th><th>Value</th><th>Stage</th><th>Quotations</th><th>Actions</th></tr></thead><tbody>
  <?php if(!$list || $list->num_rows===0): ?><tr><td colspan="8" class="text-center text-muted" style="padding:36px">No won deals found</td></tr><?php else: while($d=$list->fetch_assoc()): $qc=dealQuotationCount($conn,$account_id,$d['customer_id'],$d['item_id']); ?>
  <tr><td>—</td><td><strong><?= htmlspecialchars($d['title'] ?: 'Deal') ?></strong><div class="text-xs text-muted"><?= formatDateTime($d['datetime_updated'] ?: $d['datetime_created']) ?></div></td><td><?= htmlspecialchars($d['customer_name'] ?: '—') ?><div class="text-xs text-muted"><?= htmlspecialchars($d['business_name'] ?: '') ?></div></td><td><?= htmlspecialchars($d['item_name'] ?: '—') ?></td><td><?= crmMoney($d['estimated_price'], $d['item_currency'] ?: 'USD') ?></td><td><span class="badge badge-green"><?= htmlspecialchars($d['stage_name'] ?: 'Won') ?></span></td><td><span class="badge badge-blue"><?= $qc ?> quotation<?= $qc==1?'':'s' ?></span></td><td class="d-flex gap-8"><a class="btn btn-primary btn-sm" href="index.php?page=lead&id=<?= crmEid($d['id']) ?>">Details</a><?php if($qc): ?><a class="btn btn-secondary btn-sm" href="index.php?page=quotations&amp;quotation_search=<?= urlencode($d['customer_name']) ?>">Quotations</a><?php endif; ?></td></tr>
  <?php endwhile; endif; ?>
  </tbody></table></div><div class="list-footer"><div class="list-count">Showing <strong><?= $total_rows ? number_format($offset+1) : 0 ?> – <?= number_format(min($offset+($list?$list->num_rows:0),$total_rows)) ?></strong> of <strong><?= number_format($total_rows) ?></strong> deals</div><div class="pagination"><?php if($total_pages>1): $base=$_GET; $base['page']='deals'; unset($base['p']); if($page_num>1): $base['p']=$page_num-1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($base) ?>">‹</a><?php endif; ?><span class="btn btn-primary btn-sm">Page <?= $page_num ?> / <?= $total_pages ?></span><?php if($page_num<$total_pages): $base['p']=$page_num+1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($base) ?>">›</a><?php endif; endif; ?></div></div></div>
</div>
