<?php
// =============================================
// SHARK CRM - Leads Page  (server-side filter + pagination)
// =============================================

$canLeadAdd = userCan($conn, 'leads', 'add');
$canLeadEdit = userCan($conn, 'leads', 'edit');
$canLeadDelete = userCan($conn, 'leads', 'delete');
$canLeadAction = userCan($conn, 'leads', 'take_action');
$canLeadMoveStage = userCan($conn, 'leads', 'move_stage');
$per_page = defined('CRM_DEFAULT_PER_PAGE') ? CRM_DEFAULT_PER_PAGE : 30; // global list limit

// ── فلاتر من URL ──────────────────────────────────────────
$f_stage    = isset($_GET['stage_id'])    ? (int)$_GET['stage_id']       : 0;
$f_customer = isset($_GET['customer_id']) ? (int)$_GET['customer_id']    : 0;
$f_item     = isset($_GET['item_id'])     ? (int)$_GET['item_id']        : 0;
$f_name     = isset($_GET['f_name'])      ? trim($_GET['f_name'])        : '';
$f_opp_min  = isset($_GET['opp_min'])     && $_GET['opp_min'] !== '' ? (int)$_GET['opp_min'] : '';
$f_opp_max  = isset($_GET['opp_max'])     && $_GET['opp_max'] !== '' ? (int)$_GET['opp_max'] : '';
$f_priority = isset($_GET['priority'])    && $_GET['priority'] !== '' ? (int)$_GET['priority'] : '';
$f_date_from = isset($_GET['date_from'])  ? trim($_GET['date_from'])     : '';
$f_date_to   = isset($_GET['date_to'])    ? trim($_GET['date_to'])       : '';
$page_num   = isset($_GET['p'])           ? max(1, (int)$_GET['p'])      : 1;

// ── بناء WHERE clause بشكل آمن ────────────────────────────
$where   = "l.account_id = $account_id AND l.datetime_deleted IS NULL";
$params  = [];   // للـ prepared statement
$types   = '';

if ($f_stage) {
    $where .= " AND l.stage_id = ?";
    $params[] = $f_stage; $types .= 'i';
}
if ($f_customer) {
    $where .= " AND l.customer_id = ?";
    $params[] = $f_customer; $types .= 'i';
}
if ($f_item) {
    $where .= " AND l.item_id = ?";
    $params[] = $f_item; $types .= 'i';
}
if ($f_name !== '') {
    $where .= " AND c.customer_name LIKE ?";
    $params[] = '%' . $f_name . '%'; $types .= 's';
}
if ($f_opp_min !== '') {
    $where .= " AND l.opportunity >= ?";
    $params[] = $f_opp_min; $types .= 'i';
}
if ($f_opp_max !== '') {
    $where .= " AND l.opportunity <= ?";
    $params[] = $f_opp_max; $types .= 'i';
}
if ($f_priority !== '') {
    $where .= " AND l.priority >= ?";
    $params[] = $f_priority; $types .= 'i';
}
if ($f_date_from !== '') {
    $where .= " AND DATE(l.datetime_created) >= ?";
    $params[] = $f_date_from; $types .= 's';
}
if ($f_date_to !== '') {
    $where .= " AND DATE(l.datetime_created) <= ?";
    $params[] = $f_date_to; $types .= 's';
}

$base_joins = "
  FROM leads l
  LEFT JOIN customers c ON l.customer_id = c.id
  LEFT JOIN stage s     ON l.stage_id    = s.id
  LEFT JOIN items i     ON l.item_id     = i.id
  LEFT JOIN users u     ON l.assigned_user_id = u.id
  LEFT JOIN users cu    ON l.created_by_user_id = cu.id
  WHERE $where
";

// ── عدد النتائج الكلي ──────────────────────────────────────
$count_sql = "SELECT COUNT(*) as total $base_joins";
$stmt = $conn->prepare($count_sql);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$total_rows = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();

$total_pages = max(1, ceil($total_rows / $per_page));
$page_num    = min($page_num, $total_pages);
$offset      = ($page_num - 1) * $per_page;

// ── جلب الـ leads مع LIMIT / OFFSET ──────────────────────
$data_sql = "
  SELECT l.*, c.customer_name, c.business_name,
         s.name AS stage_name, s.color AS stage_color,
         i.name AS item_name, u.name AS assigned_name, cu.name AS created_by_name
  $base_joins
  ORDER BY l.id DESC
  LIMIT ? OFFSET ?
";

$data_params  = array_merge($params, [$per_page, $offset]);
$data_types   = $types . 'ii';
$stmt2 = $conn->prepare($data_sql);
$stmt2->bind_param($data_types, ...$data_params);
$stmt2->execute();
$leads = $stmt2->get_result();

// ── لوائح الـ dropdowns ────────────────────────────────────
$customers_list = $conn->query("SELECT id, customer_name, business_name FROM customers WHERE account_id = $account_id ORDER BY customer_name");
$items_list     = $conn->query("SELECT id, name, price FROM items WHERE account_id = $account_id ORDER BY name");
$stages_list    = $conn->query("SELECT id, name, color FROM stage WHERE account_id = $account_id ORDER BY position");
$users_list     = $conn->query("SELECT id, name FROM users WHERE account_id = $account_id ORDER BY name");

// serialize stages
$stages_arr = [];
while ($s = $stages_list->fetch_assoc()) $stages_arr[] = $s;
$stages_list->data_seek(0);

// ── helper: بناء URL للفلاتر مع تغيير page ────────────────
function buildUrl($extra = []) {
    $allowed = ['stage_id','item_id','f_name','opp_min','opp_max','priority','date_from','date_to','p'];
    $params  = [];
    foreach ($allowed as $k) {
        if (isset($_GET[$k]) && $_GET[$k] !== '') $params[$k] = $_GET[$k];
    }
    $params = array_merge($params, $extra);
    $params['page'] = 'leads';
    return 'index.php?' . http_build_query($params);
}
?>

<div class="fade-in">

<!-- ══ TOOLBAR ══════════════════════════════════════════════ -->
<div class="toolbar" style="justify-content:space-between;margin-bottom:12px">
  <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">

    <!-- stage quick filter -->
    <select class="form-control" style="width:auto"
            onchange="location='<?= buildUrl(['stage_id'=>'__V__','p'=>1]) ?>'.replace('__V__',this.value)">
      <option value="0" <?= !$f_stage?'selected':'' ?>>All Stages</option>
      <?php $stages_list->data_seek(0); while ($s=$stages_list->fetch_assoc()): ?>
      <option value="<?= $s['id'] ?>" <?= $f_stage==$s['id']?'selected':'' ?>>
        <?= htmlspecialchars($s['name']) ?>
      </option>
      <?php endwhile; ?>
    </select>

    <a href="index.php?page=pipeline" class="btn btn-secondary">📊 Pipeline</a>

    <!-- زر فتح/اقفال الفلاتر -->
    <button class="btn btn-secondary" id="toggleFiltersBtn" onclick="toggleFilters()" style="gap:6px">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;height:14px">
        <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>
      </svg>
      Filters
      <?php
        $active = array_filter([$f_stage,$f_customer,$f_item,$f_name,$f_opp_min,$f_opp_max,$f_priority,$f_date_from,$f_date_to]);
        if (count($active)):
      ?>
      <span style="background:#6366f1;color:#fff;border-radius:99px;padding:1px 7px;font-size:11px;font-weight:700;">
        <?= count($active) ?>
      </span>
      <?php endif; ?>
    </button>

    <?php if (count($active)): ?>
    <a href="index.php?page=leads" class="btn btn-secondary" style="color:#ef4444">✕ Clear</a>
    <?php endif; ?>
  </div>

  <?php if ($canLeadAdd): ?><button class="btn btn-primary" data-permission="add" onclick="openModal('addLeadModal')">+ Add Lead</button><?php endif; ?>
</div>

<!-- ══ FILTER PANEL ══════════════════════════════════════════ -->
<div id="filterPanel" style="display:<?= count($active)?'block':'none' ?>;margin-bottom:12px">
  <form method="GET" action="index.php" id="filterForm">
    <input type="hidden" name="page" value="leads">
    <input type="hidden" name="p"    value="1">

    <div class="card" style="padding:16px 20px">
      <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end">

        <!-- اسم العميل -->
        <div style="flex:1;min-width:150px">
          <label class="form-label" style="font-size:12px;margin-bottom:4px">Client name</label>
          <input type="text" name="f_name" class="form-control"
                 placeholder="Search client..." value="<?= htmlspecialchars($f_name) ?>">
        </div>

        <!-- Item -->
        <div style="flex:1;min-width:150px">
          <label class="form-label" style="font-size:12px;margin-bottom:4px">Item / Product</label>
          <select name="item_id" class="form-control">
            <option value="">All Items</option>
            <?php $items_list->data_seek(0); while ($it=$items_list->fetch_assoc()): ?>
            <option value="<?= $it['id'] ?>" <?= $f_item==$it['id']?'selected':'' ?>>
              <?= htmlspecialchars($it['name']) ?>
            </option>
            <?php endwhile; ?>
          </select>
        </div>

        <!-- Opportunity min-max -->
        <div style="flex:1;min-width:180px">
          <label class="form-label" style="font-size:12px;margin-bottom:4px">Opportunity %</label>
          <div style="display:flex;gap:6px;align-items:center">
            <input type="number" name="opp_min" class="form-control" placeholder="Min" min="0" max="100"
                   value="<?= htmlspecialchars($f_opp_min) ?>" style="width:70px">
            <span style="color:var(--text-muted);font-size:12px">–</span>
            <input type="number" name="opp_max" class="form-control" placeholder="Max" min="0" max="100"
                   value="<?= htmlspecialchars($f_opp_max) ?>" style="width:70px">
          </div>
        </div>

        <!-- Priority -->
        <div style="flex:1;min-width:150px">
          <label class="form-label" style="font-size:12px;margin-bottom:4px">
            Priority (min ★)
          </label>
          <select name="priority" class="form-control">
            <option value="">Any</option>
            <?php for ($i=1;$i<=5;$i++): ?>
            <option value="<?= $i ?>" <?= $f_priority===$i?'selected':'' ?>>
              <?= str_repeat('★',$i) . str_repeat('☆',5-$i) ?>
            </option>
            <?php endfor; ?>
          </select>
        </div>

        <!-- Date from -->
        <div style="flex:1;min-width:140px">
          <label class="form-label" style="font-size:12px;margin-bottom:4px">Date from</label>
          <input type="date" name="date_from" class="form-control"
                 value="<?= htmlspecialchars($f_date_from) ?>">
        </div>

        <!-- Date to -->
        <div style="flex:1;min-width:140px">
          <label class="form-label" style="font-size:12px;margin-bottom:4px">Date to</label>
          <input type="date" name="date_to" class="form-control"
                 value="<?= htmlspecialchars($f_date_to) ?>">
        </div>

        <div style="align-self:flex-end;display:flex;gap:8px">
          <button type="submit" class="btn btn-primary">🔍 Apply</button>
          <a href="index.php?page=leads" class="btn btn-secondary">✕ Reset</a>
        </div>
      </div>
    </div>
  </form>
</div>

<!-- ══ LEADS TABLE ═══════════════════════════════════════════ -->
<div class="card">

  <div class="table-wrapper">
    <table class="crm-table" id="leadsTable">
      <thead>
        <tr>
          <th>ID</th>
          <th>Customer</th>
          <th>Item</th>
          <th>Est. Price</th>
          <th>Opportunity</th>
          <th>Priority</th>
          <th>Stage</th>
          <th>Note</th>
          <th>Date</th>
          <th>Added By</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($total_rows === 0): ?>
        <tr>
          <td colspan="11" class="text-center text-muted" style="padding:40px">
            No leads found matching the current filters
          </td>
        </tr>
        <?php else: ?>
        <?php while ($l = $leads->fetch_assoc()): ?>
        <tr>
          <td><div class="font-bold">#<?= $l['id'] ?></div></td>
          <td>
            <div><?= htmlspecialchars($l['customer_name']) ?></div>
            <div class="text-xs text-muted"><?= htmlspecialchars($l['business_name'] ?: '') ?></div>
          </td>
          <td><?= htmlspecialchars($l['item_name'] ?: '—') ?></td>
          <td class="text-accent font-bold">$<?= number_format($l['estimated_price'], 0) ?></td>
          <td style="min-width:100px">
            <div class="progress-wrap">
              <div class="progress-bar" style="width:<?= $l['opportunity'] ?>%"></div>
            </div>
            <div class="text-xs text-muted"><?= $l['opportunity'] ?>%</div>
          </td>
          <td><span class="stars"><?= renderStars($l['priority']) ?></span></td>
          <td>
            <span class="stage-pill"
              style="color:<?= $l['stage_color']?:'var(--accent)' ?>;
                     background:<?= $l['stage_color']?:'var(--accent)' ?>22;
                     border-color:<?= $l['stage_color']?:'var(--accent)' ?>44">
              <?= htmlspecialchars($l['stage_name'] ?? 'N/A') ?>
            </span>
          </td>
          <td style="max-width:180px">
            <div class="note-preview"
                 onclick="openNoteModal(<?= $l['id'] ?>, <?= htmlspecialchars(json_encode($l['note']), ENT_QUOTES) ?>)"
                 style="cursor:pointer;color:var(--text-muted);font-size:12px;white-space:nowrap;
                        overflow:hidden;text-overflow:ellipsis;max-width:160px"
                 title="Click to view full note">
              📝 View
            </div>
          </td>
          <td class="text-muted text-xs"><?= formatDate($l['datetime_created']) ?></td>
          <td><?= htmlspecialchars($l['created_by_name'] ?: $l['assigned_name'] ?: '—') ?></td>
          <td>
            <div class="d-flex gap-8">
              <button class="btn btn-primary btn-sm"   onclick="viewLead(<?= $l['id'] ?>)">Open</button>
              <?php if ($canLeadEdit): ?><button class="btn btn-secondary btn-sm" data-permission="edit" onclick="editLead(<?= $l['id'] ?>)">Edit</button><?php endif; ?>
              <?php if ($canLeadDelete): ?><button class="btn btn-danger btn-sm" data-permission="delete" onclick="deleteLead(<?= $l['id'] ?>)">Del</button><?php endif; ?>
              <button class="btn btn-primary btn-sm"   onclick="window.location.href='?page=lead&id=<?= $l['id'] ?>'">View</button>
            </div>
          </td>
        </tr>
        <?php endwhile; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- ══ LIST FOOTER ══════════════════════════════════════════ -->
  <div class="list-footer">
    <div class="list-count">
      Showing <strong><?= $total_rows ? number_format(($page_num-1)*$per_page + 1) : 0 ?> – <?= number_format(min($page_num*$per_page,$total_rows)) ?></strong>
      of <strong><?= number_format($total_rows) ?></strong> leads
    </div>
    <div class="pagination">
      <?php if ($total_pages > 1): ?>
        <?php if ($page_num > 1): ?><a href="<?= buildUrl(['p' => $page_num - 1]) ?>" class="btn btn-secondary btn-sm">‹</a><?php endif; ?>
        <?php $range=2; $start=max(1,$page_num-$range); $end=min($total_pages,$page_num+$range); ?>
        <?php if ($start > 1): ?><a href="<?= buildUrl(['p'=>1]) ?>" class="btn btn-secondary btn-sm">1</a><?php if ($start > 2): ?><span>…</span><?php endif; ?><?php endif; ?>
        <?php for ($pg=$start; $pg<=$end; $pg++): ?>
          <a href="<?= buildUrl(['p'=>$pg]) ?>" class="btn <?= $pg===$page_num ? 'btn-primary' : 'btn-secondary' ?> btn-sm"><?= $pg ?></a>
        <?php endfor; ?>
        <?php if ($end < $total_pages): ?><?php if ($end < $total_pages - 1): ?><span>…</span><?php endif; ?><a href="<?= buildUrl(['p'=>$total_pages]) ?>" class="btn btn-secondary btn-sm"><?= $total_pages ?></a><?php endif; ?>
        <?php if ($page_num < $total_pages): ?><a href="<?= buildUrl(['p' => $page_num + 1]) ?>" class="btn btn-secondary btn-sm">›</a><?php endif; ?>
      <?php endif; ?>
    </div>
    <div class="footer-spacer"></div>
  </div>

</div>
</div><!-- .fade-in -->


<!-- ═══════════════ ADD / EDIT LEAD MODAL ═══════════════════ -->
<div class="modal-overlay" id="addLeadModal">
  <div class="modal modal-lg">
    <div class="modal-header">
      <span class="modal-title" id="addLeadTitle">Add Lead</span>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body">
      <form id="addLeadForm">
        <input type="hidden" name="edit_id" id="editLeadId" value="">
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">Customer *</label>
            <input type="text" id="customerInput" class="form-control" list="customerList"
                   placeholder="Type to search customer..." autocomplete="off">
            <datalist id="customerList">
              <?php $customers_list->data_seek(0); while ($c=$customers_list->fetch_assoc()): ?>
              <option value="<?= htmlspecialchars($c['customer_name']) ?>" data-id="<?= $c['id'] ?>">
                <?= htmlspecialchars($c['customer_name']) ?>
                <?= $c['business_name'] ? '· '.htmlspecialchars($c['business_name']) : '' ?>
              </option>
              <?php endwhile; ?>
            </datalist>
            <input type="hidden" name="customer_id" id="customerId">
          </div>
          <div class="form-group">
            <label class="form-label">Item / Product</label>
            <input type="text" id="itemInput" class="form-control" list="itemList"
                   placeholder="Type to search item..." autocomplete="off">
            <datalist id="itemList">
              <?php $items_list->data_seek(0); while ($it=$items_list->fetch_assoc()): ?>
              <option value="<?= htmlspecialchars($it['name']) ?>"
                      data-id="<?= $it['id'] ?>" data-price="<?= $it['price'] ?>">
                <?= htmlspecialchars($it['name']) ?> – $<?= number_format($it['price'],0) ?>
              </option>
              <?php endwhile; ?>
            </datalist>
            <input type="hidden" name="item_id" id="itemId">
          </div>
          <div class="form-group">
            <label class="form-label">Stage</label>
            <select name="stage_id" class="form-control">
              <option value="">Select stage...</option>
              <?php $stages_list->data_seek(0); while ($s=$stages_list->fetch_assoc()): ?>
              <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Estimated Price ($)</label>
            <input type="number" name="estimated_price" id="leadEstPrice"
                   class="form-control" step="0.01" min="0" value="0">
          </div>
          <div class="form-group">
            <label class="form-label">Opportunity %</label>
            <input type="range" name="opportunity" id="oppRange" class="form-control"
                   min="0" max="100" step="25" value="50" list="oppSteps"
                   oninput="document.getElementById('oppVal').textContent=this.value+'%'">
            <datalist id="oppSteps"><option value="0"><option value="25"><option value="50"><option value="75"><option value="100"></datalist><div class="form-hint" id="oppVal">50%</div>
          </div>
            <input type="hidden" name="assigned_user_id" value="<?php echo $_SESSION['user_id']; ?>">
          <div class="form-group">
            <label class="form-label">Priority (Stars)</label>
            <div class="star-rating-wrap d-flex align-center gap-8">
              <?php for ($i=1;$i<=5;$i++): ?>
              <span class="star-input" style="font-size:22px;cursor:pointer;color:var(--text-muted)">★</span>
              <?php endfor; ?>
              <input type="hidden" name="priority" value="3">
            </div>
          </div>
          <div class="form-group span-2">
            <label class="form-label">Note</label>
            <textarea name="note" class="form-control" rows="3"
                      placeholder="Add any notes about this lead..."></textarea>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer" style="display:block">
      <div id="duplicateLeadConfirmBox" class="duplicate-confirm-box">
        <div style="font-weight:700;margin-bottom:6px">Duplicate lead found</div>
        <div id="duplicateLeadMessage" class="text-sm text-muted" style="margin-bottom:12px"></div>
        <div class="d-flex gap-8" style="justify-content:flex-end">
          <button type="button" class="btn btn-secondary btn-sm" onclick="cancelDuplicateLead()">Cancel</button>
          <button type="button" class="btn btn-primary btn-sm" onclick="confirmDuplicateLead()">Yes, save anyway</button>
        </div>
      </div>
      <div class="d-flex gap-8" style="justify-content:flex-end">
        <button class="btn btn-secondary" onclick="closeModal('addLeadModal')">Cancel</button>
        <?php if ($canLeadAdd || $canLeadEdit): ?><button id="saveLeadBtn" class="btn btn-primary" data-permission="add" onclick="submitLead()">Save Lead</button><?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- ═══════════════ VIEW LEAD MODAL ═════════════════════════ -->
<div class="modal-overlay" id="viewLeadModal">
  <div class="modal modal-xl">
    <div class="modal-header">
      <span class="modal-title" id="viewLeadTitle">Lead Details</span>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body" id="viewLeadBody">
      <div class="text-center" style="padding:40px"><div class="spinner"></div></div>
    </div>
  </div>
</div>

<!-- ═══════════════ NOTE MODAL ══════════════════════════════ -->
<div class="modal-overlay" id="noteModal">
  <div class="modal" style="max-width:520px;width:100%">
    <div class="modal-header">
      <span class="modal-title">📝 Lead Note</span>
      <button class="modal-close" onclick="closeModal('noteModal')">✕</button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="noteLeadId" value="">
      <div class="form-group mb-0">
        <label class="form-label">Note</label>
        <textarea id="noteTextarea" class="form-control" rows="8"
                  placeholder="Write your note here..."></textarea>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('noteModal')">Cancel</button>
      <?php if ($canLeadEdit): ?><button class="btn btn-primary" data-permission="edit" onclick="saveNote()">💾 Save Note</button><?php endif; ?>
    </div>
  </div>
</div>

<script>
const CAN_LEAD_ADD = <?= $canLeadAdd ? 'true' : 'false' ?>;
const CAN_LEAD_EDIT = <?= $canLeadEdit ? 'true' : 'false' ?>;
const CAN_LEAD_DELETE = <?= $canLeadDelete ? 'true' : 'false' ?>;
const CAN_LEAD_ACTION = <?= $canLeadAction ? 'true' : 'false' ?>;
const CAN_LEAD_MOVE_STAGE = <?= $canLeadMoveStage ? 'true' : 'false' ?>;
// ─── Filter panel toggle ─────────────────────────────────────
function toggleFilters() {
  const panel = document.getElementById('filterPanel');
  const open  = panel.style.display !== 'none';
  panel.style.display = open ? 'none' : 'block';
  document.getElementById('toggleFiltersBtn').style.outline =
    open ? '' : '2px solid var(--accent,#6366f1)';
}

// ─── Add / Edit Lead ────────────────────────────────────────
document.getElementById('itemInput').addEventListener('change', function () {
  const opts = document.getElementById('itemList').options;
  for (let o of opts) {
    if (o.value === this.value) {
      if (o.dataset.price) document.getElementById('leadEstPrice').value = o.dataset.price;
      document.getElementById('itemId').value = o.dataset.id;
      break;
    }
  }
});
document.getElementById('customerInput').addEventListener('change', function () {
  const opts = document.getElementById('customerList').options;
  for (let o of opts) {
    if (o.value === this.value) { document.getElementById('customerId').value = o.dataset.id; break; }
  }
});
document.getElementById('customerInput').addEventListener('input', function () {
  const opts = document.getElementById('customerList').options;
  let found = false;
  for (let o of opts) if (o.value === this.value) { found = true; break; }
  if (!found) document.getElementById('customerId').value = '';
});
document.getElementById('itemInput').addEventListener('input', function () {
  const opts = document.getElementById('itemList').options;
  let found = false;
  for (let o of opts) if (o.value === this.value) { found = true; break; }
  if (!found) { document.getElementById('itemId').value = ''; document.getElementById('leadEstPrice').value = ''; }
});

function initStarRating(container) {
  const stars  = container.querySelectorAll('.star-input');
  const hidden = container.querySelector('input[name="priority"]');
  stars.forEach((star, idx) => {
    star.addEventListener('click', () => {
      hidden.value = idx + 1;
      stars.forEach((s, i) => s.style.color = i <= idx ? 'var(--yellow)' : 'var(--text-muted)');
    });
  });
}
const wrap = document.querySelector('#addLeadModal .star-rating-wrap');
if (wrap) initStarRating(wrap);

async function submitLead() {
  const form = document.getElementById('addLeadForm');
  const fd   = new FormData(form);
  const editId = document.getElementById('editLeadId').value;
  
  console.log("editId:", editId);
  
  if ((editId && !CAN_LEAD_EDIT) || (!editId && !CAN_LEAD_ADD)) {
    showToast('Permission denied', 'error'); 
    return; 
  }
  
  const customerId = document.getElementById('customerId').value;
  if (!customerId) { 
    showToast('Please select a valid customer from the list', 'error'); 
    return; 
  }
  
  fd.set('customer_id', customerId);
  fd.append('action', editId ? 'edit' : 'add');
  
  let res = await apiCall('handlers/leads.php', fd);
  if (!res.success && (res.message || '').indexOf('DUPLICATE_LEAD_ITEM:') === 0) {
    window.pendingDuplicateLeadFormData = fd;
    document.getElementById('duplicateLeadMessage').textContent = (res.message || '').replace('DUPLICATE_LEAD_ITEM:', '').trim();
    document.getElementById('duplicateLeadConfirmBox').classList.add('active');
    document.getElementById('saveLeadBtn').disabled = true;
    return;
  }
  if (res.success) {
    showToast(editId ? 'Lead updated!' : 'Lead added!', 'success');
    closeModal('addLeadModal');
    setTimeout(() => location.reload(), 600);
  } else {
    showToast((res.message || 'Error saving lead').replace('DUPLICATE_LEAD_ITEM:', '').trim(), 'error');
  }
}

function cancelDuplicateLead(){
  window.pendingDuplicateLeadFormData = null;
  const box = document.getElementById('duplicateLeadConfirmBox');
  if(box) box.classList.remove('active');
  const btn = document.getElementById('saveLeadBtn');
  if(btn) btn.disabled = false;
}

async function confirmDuplicateLead(){
  const fd = window.pendingDuplicateLeadFormData;
  if(!fd) return cancelDuplicateLead();
  fd.set('force_duplicate','1');
  const res = await apiCall('handlers/leads.php', fd);
  if(res.success){
    showToast('Lead added!', 'success');
    closeModal('addLeadModal');
    setTimeout(() => location.reload(), 600);
  } else {
    showToast((res.message || 'Error saving lead').replace('DUPLICATE_LEAD_ITEM:', '').trim(), 'error');
    cancelDuplicateLead();
  }
}

async function editLead(id) {
  if (!CAN_LEAD_EDIT) { showToast('Permission denied', 'error'); return; }
  const res = await apiCall('handlers/leads.php', { action: 'get', id });
  if (!res.success) { showToast('Error', 'error'); return; }
  const l = res.data;
  const f = document.getElementById('addLeadForm');
  if (l.customer_name) {
    document.getElementById('customerInput').value = l.customer_name;
    document.getElementById('customerId').value    = l.customer_id;
  }
  if (l.item_name) {
    document.getElementById('itemInput').value = l.item_name;
    document.getElementById('itemId').value    = l.item_id || '';
  } else {
    document.getElementById('itemInput').value = '';
    document.getElementById('itemId').value    = '';
  }
  f.querySelector('[name=stage_id]').value          = l.stage_id || '';
  f.querySelector('[name=estimated_price]').value   = l.estimated_price;
  f.querySelector('[name=opportunity]').value       = l.opportunity;
  document.getElementById('oppVal').textContent     = l.opportunity + '%';
  f.querySelector('[name=assigned_user_id]').value  = l.assigned_user_id || '';
  f.querySelector('[name=priority]').value          = l.priority;
  f.querySelector('[name=note]').value              = l.note || '';
  document.getElementById('editLeadId').value       = id;
  f.querySelectorAll('.star-input').forEach((s,i) =>
    s.style.color = i < l.priority ? 'var(--yellow)' : 'var(--text-muted)');
  document.getElementById('addLeadTitle').textContent = 'Edit Lead';
  openModal('addLeadModal');
}

// ─── View Lead ──────────────────────────────────────────────
async function viewLead(id) {
  openModal('viewLeadModal');
  document.getElementById('viewLeadBody').innerHTML =
    '<div class="text-center" style="padding:40px"><div class="spinner"></div></div>';
  const res = await apiCall('handlers/leads.php', { action: 'get_full', id });
  if (!res.success) {
    document.getElementById('viewLeadBody').innerHTML = '<p class="text-red">Error loading lead</p>';
    return;
  }
  const l = res.data;
  document.getElementById('viewLeadTitle').textContent = l.title || ('Lead #' + l.id);

  const followups  = res.followups  || [];
  const activities = res.activities || [];

  let fuHtml = followups.map(f => `
    <div class="timeline-item">
      <div class="timeline-dot"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg></div>
      <div class="timeline-content">
        <div class="timeline-header">
          <span class="timeline-author">${f.user_name || 'User'}</span>
          <span class="timeline-time">${formatDate(f.datetime)}</span>
        </div>
        <div class="timeline-text">${f.comment}</div>
      </div>
    </div>`).join('') || '<p class="text-muted text-sm">No comments yet</p>';

  let actHtml = activities.map(a => `
    <div class="timeline-item">
      <div class="timeline-dot">📌</div>
      <div class="timeline-content">
        <div class="timeline-header">
          <span class="timeline-author">${a.type_name || 'Activity'}</span>
          <span class="timeline-time">${formatDate(a.datetime)}</span>
        </div>
        <div class="timeline-text">${a.text || ''}</div>
        <div class="timeline-text">Activity date: ${a.date_activitie || ''}</div>
      </div>
    </div>`).join('') || '<p class="text-muted text-sm">No activities yet</p>';

  const noteHtml = l.note
    ? `<div style="background:var(--bg-secondary,#f9f9f9);border:1px solid var(--border-color,#e0e0e0);
                  border-radius:8px;padding:14px 16px;white-space:pre-wrap;font-size:14px;
                  line-height:1.6;color:var(--text)">${escapeHtml(l.note)}</div>`
    : `<p class="text-muted text-sm">No note added yet.</p>`;

  document.getElementById('viewLeadBody').innerHTML = `
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
      <div>
        <div class="form-grid mb-16" style="grid-template-columns:1fr 1fr">
          <div><label class="form-label">Customer</label><p>${l.customer_name}</p></div>
          <div><label class="form-label">Item</label><p>${l.item_name || '—'}</p></div>
          <div><label class="form-label">Stage</label>
            <span class="stage-pill">${l.stage_name || 'N/A'}</span></div>
          <div><label class="form-label">Estimated Price</label>
            <p class="text-accent font-bold">$${parseFloat(l.estimated_price).toLocaleString()}</p></div>
          <div><label class="form-label">Opportunity</label>
            <div class="progress-wrap"><div class="progress-bar" style="width:${l.opportunity}%"></div></div>
            <div class="text-xs text-muted">${l.opportunity}%</div></div>
          <div><label class="form-label">Priority</label>${renderPriority(l.priority)}</div>
          <div><label class="form-label">Assigned To</label><p>${l.assigned_name || 'Unassigned'}</p></div>
        </div>
        <div class="hr"></div>
        <label class="form-label">Log Activity</label>
        <div class="form-grid" style="grid-template-columns:1fr 1fr;margin-bottom:8px">
          <select id="actType" class="form-control">
            <?php $act_types=$conn->query("SELECT id,name FROM activity_type"); while($at=$act_types->fetch_assoc()): ?>
            <option value="<?= $at['id'] ?>"><?= htmlspecialchars($at['name']) ?></option>
            <?php endwhile; ?>
          </select>
          <input type="text" id="actText" class="form-control" placeholder="Activity notes...">
          <input type="date" id="actdate" class="form-control">
        </div>
        ${CAN_LEAD_ACTION ? `<button class="btn btn-secondary btn-sm" onclick="logActivity(${l.id})">Take Action</button>` : ''}
        <div class="hr" style="margin-top:20px"></div>
        <label class="form-label" style="margin-bottom:8px">📝 Note</label>
        ${noteHtml}
      </div>
      <div>
        <label class="form-label">Timeline & Comments</label>
        <div class="tabs">
          <button class="tab-btn active" data-tab="tab-followups">Comments</button>
          <button class="tab-btn"        data-tab="tab-activities">Activities</button>
        </div>
        <div class="tab-pane active" id="tab-followups">
          <div class="timeline" id="followupsTimeline">${fuHtml}</div>
          <div class="hr"></div>
          <div class="form-group mb-0">
            <textarea id="newComment" class="form-control" placeholder="Add a comment..." rows="3"></textarea>
          </div>
          ${CAN_LEAD_ACTION ? `<button class="btn btn-primary btn-sm mt-8" onclick="addFollowup(${l.id})">Post Comment</button>` : ''}
        </div>
        <div class="tab-pane" id="tab-activities">
          <div class="timeline" id="activitiesTimeline">${actHtml}</div>
        </div>
      </div>
    </div>`;
  initTabs(document.getElementById('viewLeadBody'));
}

// ─── Note Modal ─────────────────────────────────────────────
function openNoteModal(leadId, currentNote) {
  document.getElementById('noteLeadId').value   = leadId;
  document.getElementById('noteTextarea').value = currentNote || '';
  openModal('noteModal');
}
async function saveNote() {
  if (!CAN_LEAD_EDIT) { showToast('Permission denied', 'error'); return; }
  const leadId = document.getElementById('noteLeadId').value;
  const note   = document.getElementById('noteTextarea').value;
  const res = await apiCall('handlers/leads.php', { action:'save_note', id:leadId, note });
  if (res.success) {
    showToast('Note saved!', 'success');
    closeModal('noteModal');
    setTimeout(() => location.reload(), 600);
  } else showToast(res.message || 'Error saving note', 'error');
}

// ─── Add Followup ───────────────────────────────────────────
async function addFollowup(leadId) {
  if (!CAN_LEAD_ACTION) { showToast('Permission denied', 'error'); return; }
  const comment = document.getElementById('newComment').value.trim();
  if (!comment) { showToast('Please enter a comment', 'warning'); return; }
  const res = await apiCall('handlers/leads.php', { action:'add_followup', lead_id:leadId, comment });
  if (res.success) {
    showToast('Comment added', 'success');
    document.getElementById('newComment').value = '';
    const tl  = document.getElementById('followupsTimeline');
    const div = document.createElement('div');
    div.className = 'timeline-item';
    div.innerHTML = `<div class="timeline-dot"></div>
      <div class="timeline-content">
        <div class="timeline-header">
          <span class="timeline-author">You</span>
          <span class="timeline-time">Just now</span>
        </div>
        <div class="timeline-text">${escapeHtml(comment)}</div>
      </div>`;
    tl.insertBefore(div, tl.firstChild);
  } else showToast(res.message || 'Error', 'error');
}

// ─── Log Activity ───────────────────────────────────────────
async function logActivity(leadId) {
  if (!CAN_LEAD_ACTION) { showToast('Permission denied', 'error'); return; }
  const typeId  = document.getElementById('actType').value;
  const text    = document.getElementById('actText').value.trim();
  const actdate = document.getElementById('actdate').value;
  if (!text) { showToast('Please enter activity notes', 'warning'); return; }
  const res = await apiCall('handlers/leads.php',
    { action:'add_activity', lead_id:leadId, activity_type_id:typeId, text, actdate });
  if (res.success) {
    showToast('Activity logged', 'success');
    document.getElementById('actText').value = '';
    const upd = await apiCall('handlers/leads.php', { action:'get_full', id:leadId });
    if (upd.success && upd.activities) {
      document.getElementById('activitiesTimeline').innerHTML =
        upd.activities.map(a => `
          <div class="timeline-item">
            <div class="timeline-dot">📌</div>
            <div class="timeline-content">
              <div class="timeline-header">
                <span class="timeline-author">${a.type_name||'Activity'}</span>
                <span class="timeline-time">${formatDate(a.datetime)}</span>
              </div>
              <div class="timeline-text">${a.text||''}</div>
              <div class="timeline-text">Activity date: ${a.date_activitie||''}</div>
            </div>
          </div>`).join('') || '<p class="text-muted text-sm">No activities yet</p>';
    }
  } else showToast(res.message || 'Error', 'error');
}

// ─── Delete Lead ────────────────────────────────────────────
async function deleteLead(id) {
  if (!CAN_LEAD_DELETE) { showToast('Permission denied', 'error'); return; }
  confirmAction('Delete this lead? This cannot be undone.', async () => {
    const res = await apiCall('handlers/leads.php', { action:'delete', id });
    if (res.success) { showToast('Lead deleted', 'success'); setTimeout(() => location.reload(), 600); }
    else showToast(res.message || 'Error', 'error');
  });
}

// ─── Helpers ────────────────────────────────────────────────
function escapeHtml(text) {
  const d = document.createElement('div');
  d.textContent = text;
  return d.innerHTML;
}
function renderPriority(p) {
  return Array.from({length:5},(_,i) =>
    `<span style="color:${i<p?'var(--yellow)':'var(--text-muted)'}">★</span>`).join('');
}
function formatDate(ds) {
  return ds ? new Date(ds).toLocaleString() : '';
}
function initTabs(container) {
  container.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.dataset.tab;
      container.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
      container.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
      btn.classList.add('active');
      document.getElementById(id).classList.add('active');
    });
  });
}
function openModal(id)  { document.getElementById(id).style.display = 'flex'; }
function closeModal(id) { document.getElementById(id).style.display = 'none'; }
function showToast(msg, type) { console.log(msg, type); alert(msg); }
function confirmAction(msg, cb) { if (confirm(msg)) cb(); }

async function apiCall(url, data) {
  const fd = new FormData();
  if (data instanceof FormData) {
    for (let [k,v] of data.entries()) fd.append(k, v);
  } else {
    for (let k in data) fd.append(k, data[k]);
  }
  const r = await fetch(url, { method:'POST', body:fd });
  return r.json();
}

// Reset add modal on close
document.getElementById('addLeadModal').addEventListener('click', function(e) {
  if (e.target === this || e.target.classList.contains('modal-close')) {
    document.getElementById('editLeadId').value    = '';
    document.getElementById('addLeadTitle').textContent = 'Add Lead';
    document.getElementById('customerInput').value = '';
    document.getElementById('customerId').value    = '';
    document.getElementById('itemInput').value     = '';
    document.getElementById('itemId').value        = '';
    document.getElementById('leadEstPrice').value  = '0';
    document.getElementById('oppRange').value      = '50';
    document.getElementById('oppVal').textContent  = '50%';
    document.getElementById('addLeadForm').reset();
  }
});
</script>