<?php
// SHARK CRM - Pipeline (Kanban) with same filters as Leads list
$canLeadAdd = userCan($conn, 'leads', 'add');
$f_name = trim($_GET['f_name'] ?? '');
$f_item = isset($_GET['item_id']) ? crmId($_GET['item_id']) : 0;
$f_priority = isset($_GET['priority']) && $_GET['priority'] !== '' ? (int)$_GET['priority'] : '';
$f_date_from = trim($_GET['date_from'] ?? '');
$f_date_to = trim($_GET['date_to'] ?? '');
$f_added_by = isset($_GET['added_by']) && $_GET['added_by'] !== '' ? (int)$_GET['added_by'] : 0;
$filterSql = " AND l.status='open'";
if ($f_name !== '') { $safe=sanitize($conn,$f_name); $filterSql .= " AND (c.customer_name LIKE '%$safe%' OR l.title LIKE '%$safe%')"; }
if ($f_item) $filterSql .= " AND l.item_id=$f_item";
if ($f_priority !== '') $filterSql .= " AND l.priority >= $f_priority";
if ($f_date_from !== '') { $safe=sanitize($conn,$f_date_from); $filterSql .= " AND DATE(l.datetime_created) >= '$safe'"; }
if ($f_date_to !== '') { $safe=sanitize($conn,$f_date_to); $filterSql .= " AND DATE(l.datetime_created) <= '$safe'"; }
if ($f_added_by) $filterSql .= " AND l.created_by_user_id=$f_added_by";
$items_list = $conn->query("SELECT id,name FROM items WHERE account_id=$account_id ORDER BY name");
$users_list = $conn->query("SELECT id,name FROM users WHERE account_id=$account_id ORDER BY name");
$stages = $conn->query("SELECT * FROM stage WHERE account_id = $account_id ORDER BY position");
$stages_arr = [];
while ($s = $stages->fetch_assoc()) {
    $sid=(int)$s['id'];
    $leads_q = $conn->query("SELECT l.*, c.customer_name, c.business_name, i.currency AS item_currency FROM leads l LEFT JOIN customers c ON l.customer_id=c.id LEFT JOIN items i ON i.id=l.item_id WHERE l.stage_id=$sid AND l.account_id=$account_id AND l.datetime_deleted IS NULL $filterSql ORDER BY l.datetime_created DESC");
    $s['leads'] = [];
    while ($lead = $leads_q->fetch_assoc()) $s['leads'][] = $lead;
    $stages_arr[] = $s;
}
$active = array_filter([$f_name,$f_item,$f_priority,$f_date_from,$f_date_to,$f_added_by], fn($v)=>$v!=='' && $v!==0);
?>
<div class="fade-in">
<div class="toolbar" style="justify-content:space-between;gap:10px;flex-wrap:wrap">
  <div class="d-flex gap-8" style="flex-wrap:wrap"><a href="index.php?page=leads&view=list" class="btn btn-secondary">☰ List</a><button class="btn btn-secondary" onclick="toggleFilters()">Filters <?= count($active)?'('.count($active).')':'' ?></button><?php if(count($active)): ?><a href="index.php?page=pipeline" class="btn btn-secondary" style="color:#ef4444">✕ Clear</a><?php endif; ?></div>
  <div class="d-flex gap-8"><?php if ($canLeadAdd): ?><button class="btn btn-primary" data-page="leads" data-permission="add" onclick="window.location='index.php?page=leads&view=list'">+ New Lead</button><?php endif; ?><button class="btn btn-secondary" data-page="settings" data-permission="tab_stages" onclick="window.location='index.php?page=settings&tab=stages'">⚙ Manage Stages</button></div>
</div>
<div id="filterPanel" style="display:<?= count($active)?'block':'none' ?>;margin-bottom:12px"><form method="get" action="index.php" class="card" style="padding:16px"><input type="hidden" name="page" value="pipeline"><div style="display:flex;gap:10px;flex-wrap:wrap;align-items:end"><div><label class="form-label">Client / Lead</label><input class="form-control" name="f_name" value="<?= htmlspecialchars($f_name) ?>" placeholder="Search..."></div><div><label class="form-label">Item</label><select class="form-control" name="item_id"><option value="">All</option><?php while($it=$items_list->fetch_assoc()): ?><option value="<?= crmEid($it['id']) ?>" <?= $f_item==$it['id']?'selected':'' ?>><?= htmlspecialchars($it['name']) ?></option><?php endwhile; ?></select></div><div><label class="form-label">Priority ≥</label><select class="form-control" name="priority"><option value="">All</option><?php for($i=1;$i<=5;$i++): ?><option value="<?= $i ?>" <?= $f_priority===$i?'selected':'' ?>><?= $i ?></option><?php endfor; ?></select></div><div><label class="form-label">From</label><input type="date" class="form-control" name="date_from" value="<?= htmlspecialchars($f_date_from) ?>"></div><div><label class="form-label">To</label><input type="date" class="form-control" name="date_to" value="<?= htmlspecialchars($f_date_to) ?>"></div><div><label class="form-label">Added By</label><select class="form-control" name="added_by"><option value="">All</option><?php while($u=$users_list->fetch_assoc()): ?><option value="<?= $u['id'] ?>" <?= $f_added_by==$u['id']?'selected':'' ?>><?= htmlspecialchars($u['name']) ?></option><?php endwhile; ?></select></div><button class="btn btn-primary">Apply</button></div></form></div>
<div class="pipeline-wrap">
  <?php foreach ($stages_arr as $stage): ?>
  <div class="kanban-col"><div class="kanban-col-header"><div class="kanban-col-dot" style="background:<?= htmlspecialchars($stage['color']) ?>"></div><div class="kanban-col-name"><?= htmlspecialchars($stage['name']) ?></div><div class="kanban-col-count"><?= count($stage['leads']) ?></div></div><div class="kanban-cards" data-stage="<?= $stage['id'] ?>">
      <?php foreach ($stage['leads'] as $lead): ?>
      <div class="kanban-card" draggable="true" data-id="<?= crmEid($lead['id']) ?>" onclick="window.location='index.php?page=lead&id=<?= crmEid($lead['id']) ?>'"><div class="kanban-card-title"><?= htmlspecialchars($lead['title'] ?: 'Lead') ?></div><div class="kanban-card-customer"><span>👤</span><?= htmlspecialchars($lead['customer_name']) ?></div><div class="kanban-card-price"><?= crmMoney($lead['estimated_price'], $lead['item_currency'] ?: 'USD') ?></div><div class="kanban-card-footer"><div class="progress-wrap" style="flex:1;margin-right:8px"><div class="progress-bar" style="width:<?= (int)$lead['opportunity'] ?>%"></div></div><span class="text-xs text-muted"><?= (int)$lead['opportunity'] ?>%</span></div><div style="margin-top:6px"><span class="stars"><?= renderStars($lead['priority']) ?></span></div></div>
      <?php endforeach; ?>
    </div></div>
  <?php endforeach; ?>
</div></div>
<script>function toggleFilters(){const p=document.getElementById('filterPanel');p.style.display=p.style.display==='none'?'block':'none';}</script>
