<?php
// =============================================
// SHARK CRM - Pipeline (Kanban)
// =============================================

$stages = $conn->query("SELECT * FROM stage WHERE account_id = $account_id ORDER BY position");
$stages_arr = [];
while ($s = $stages->fetch_assoc()) {
    $leads_q = $conn->query("
        SELECT l.*, c.customer_name, c.business_name
        FROM leads l
        LEFT JOIN customers c ON l.customer_id = c.id
        WHERE l.stage_id = {$s['id']} AND l.account_id = $account_id AND l.status = 'open'
        ORDER BY l.datetime_created DESC
    ");
    $s['leads'] = [];
    while ($lead = $leads_q->fetch_assoc()) $s['leads'][] = $lead;
    $stages_arr[] = $s;
}
?>

<div class="fade-in">
<div class="toolbar">
  <div style="flex:1">
    <span class="text-secondary text-sm">Drag cards between columns to update stages</span>
  </div>
  <button class="btn btn-primary" onclick="window.location='index.php?page=leads'">+ New Lead</button>
  <button class="btn btn-secondary" onclick="openModal('manageStagesModal')">⚙ Manage Stages</button>
</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:<?= $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="<?= $lead['id'] ?>">
        <div class="kanban-card-title"><?= htmlspecialchars($lead['title'] ?: 'Lead #'.$lead['id']) ?></div>
        <div class="kanban-card-customer">
          <span>👤</span><?= htmlspecialchars($lead['customer_name']) ?>
        </div>
        <div class="kanban-card-price">$<?= number_format($lead['estimated_price'], 0) ?></div>
        <div class="kanban-card-footer">
          <div class="progress-wrap" style="flex:1;margin-right:8px">
            <div class="progress-bar" style="width:<?= $lead['opportunity'] ?>%"></div>
          </div>
          <span class="text-xs text-muted"><?= $lead['opportunity'] ?>%</span>
          <button class="btn btn-secondary btn-sm" style="margin-left:8px;padding:2px 8px"
                  onclick="event.stopPropagation();window.location='index.php?page=leads'">→</button>
        </div>
        <div style="margin-top:6px">
          <span class="stars"><?= renderStars($lead['priority']) ?></span>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>
</div>

<!-- ===================== MANAGE STAGES MODAL ===================== -->
<div class="modal-overlay" id="manageStagesModal">
  <div class="modal">
    <div class="modal-header">
      <span class="modal-title">Manage Stages</span>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body">
      <div id="stagesListContainer">
        <?php foreach ($stages_arr as $s): ?>
        <div class="d-flex align-center gap-8 mb-12" id="stage_row_<?= $s['id'] ?>">
          <div style="width:16px;height:16px;border-radius:50%;background:<?= $s['color'] ?>;flex-shrink:0"></div>
          <span style="flex:1"><?= htmlspecialchars($s['name']) ?></span>
          <span class="badge badge-gray">pos <?= $s['position'] ?></span>
          <?php if ($s['is_start']): ?><span class="badge badge-teal">Start</span><?php endif; ?>
          <?php if ($s['is_end']): ?><span class="badge badge-red">End</span><?php endif; ?>
          <button class="btn btn-danger btn-sm" onclick="deleteStage(<?= $s['id'] ?>, '<?= addslashes($s['name']) ?>')">Del</button>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="hr"></div>
      <label class="form-label">Add New Stage</label>
      <form id="addStageForm">
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">Stage Name</label>
            <input type="text" name="name" class="form-control" required>
          </div>
          <div class="form-group">
            <label class="form-label">Color</label>
            <input type="color" name="color" class="form-control" value="#00e5c3">
          </div>
          <div class="form-group">
            <label class="form-label">Position</label>
            <input type="number" name="position" class="form-control" value="<?= count($stages_arr) + 1 ?>">
          </div>
        </div>
        <div class="d-flex gap-8">
          <label class="d-flex align-center gap-8" style="font-size:13px;cursor:pointer">
            <input type="checkbox" name="is_start"> Start Stage
          </label>
          <label class="d-flex align-center gap-8" style="font-size:13px;cursor:pointer">
            <input type="checkbox" name="is_end"> End Stage
          </label>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('manageStagesModal')">Close</button>
      <button class="btn btn-primary" onclick="addStage()">Add Stage</button>
    </div>
  </div>
</div>

<script>
async function addStage() {
  const form = document.getElementById('addStageForm');
  const fd = new FormData(form);
  fd.append('action', 'add');
  const res = await apiCall('handlers/stages.php', fd);
  if (res.success) { showToast('Stage added!', 'success'); setTimeout(() => location.reload(), 600); }
  else showToast(res.message || 'Error', 'error');
}

async function deleteStage(id, name) {
  confirmAction(`Delete stage "${name}"?`, async () => {
    const res = await apiCall('handlers/stages.php', { action: 'delete', id });
    if (res.success) {
      showToast('Stage deleted', 'success');
      const el = document.getElementById('stage_row_' + id);
      if (el) el.remove();
    } else showToast(res.message || 'Error', 'error');
  });
}
</script>
