
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php $view='leads/index.php'; ?>

<?php $sf = $_SESSION['leads_filters'] ?? []; ?>

<!-- DataTables (Bootstrap 5) -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">

<div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
  <h4 class="mb-0"><?= e(t('leads.title')) ?></h4>

  <div class="d-flex gap-2 flex-wrap align-items-center">
    <?php if (has_role($u, ['ADMIN','MARKETING','CC_SUP'])): ?>
      <a class="btn btn-primary" href="<?= e(base_url($config, '/index.php?r=leads/create')) ?>">
        <?= e(t('leads.create')) ?>
      </a>
    <?php endif; ?>
  </div>
</div>

<?php if (has_role($u, ['CC_SUP','ADMIN'])): ?>
<form id="bulkAssignForm" method="post" action="<?= e(base_url($config, '/index.php?r=leads/bulk_assign')) ?>" class="card shadow-sm mb-3">
  <div class="card-body d-flex gap-2 align-items-end flex-wrap">
   <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">

    <div style="min-width:280px;">
      <label class="form-label mb-1"><?= e(t('leads.assign_to_agent') ?: 'Assign to Call Center Agent') ?></label>
      <select name="agent_id" class="form-select" required>
        <option value=""><?= e(t('global.select') ?: 'Select') ?></option>
        <?php foreach (($agents ?? []) as $a): ?>
          <option value="<?= (int)$a['id'] ?>"><?= e($a['name']) ?> (<?= e($a['mobile']) ?>)</option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="d-flex gap-2">
      <button type="submit" class="btn btn-primary" id="btnBulkAssign" disabled>
        <?= e(t('leads.bulk_assign') ?: 'Bulk Assign Selected') ?>
      </button>
      <button type="button" class="btn btn-outline-secondary" id="btnSelectAll">
        <?= e(t('global.select_all') ?: 'Select all') ?>
      </button>
      <button type="button" class="btn btn-outline-secondary" id="btnClearAll">
        <?= e(t('global.clear') ?: 'Clear') ?>
      </button>
    </div>

    <div class="text-muted small ms-auto">
      <span id="selectedCount">0</span> <?= e(t('global.selected') ?: 'selected') ?>
    </div>
  </div>
</form>
<?php endif; ?>

<div class="card shadow-sm">
  <div class="card-body">
    <!-- optional filters (SQL-side) -->
    <div class="row g-2 mb-3">
  <div class="col-12 col-md-3">
    <input id="filterQ" class="form-control" placeholder="<?= e(t('global.search')) ?>" value="<?= e($sf['q'] ?? '') ?>">
  </div>

  <div class="col-6 col-md-2">
    <select id="filterStatus" class="form-select">
      <option value=""><?= e(t('leads.status') ?: 'Status') ?> (<?= e(t('global.all') ?: 'All') ?>)</option>
      <option value="new">new</option>
      <option value="assigned">assigned</option>
      <option value="in_progress">in_progress</option>
      <option value="contacted">contacted</option>
      <option value="qualified">qualified</option>
      <option value="disqualified">disqualified</option>
      <option value="closed">closed</option>
    </select>
  </div>

  <div class="col-6 col-md-2">
    <input id="filterCity" class="form-control" placeholder="Lead city" value="<?= e($sf['city'] ?? '') ?>">

  </div>

  <div class="col-6 col-md-2">
    <?php $cr = (string)($sf['created_range'] ?? ''); ?>
<select id="filterCreatedRange" class="form-select">
  <option value="" <?= $cr===''?'selected':'' ?>>Creation Date (All)</option>
  <option value="today" <?= $cr==='today'?'selected':'' ?>>Today</option>
  <option value="yesterday" <?= $cr==='yesterday'?'selected':'' ?>>Yesterday</option>
  <option value="this_week" <?= $cr==='this_week'?'selected':'' ?>>This Week</option>
  <option value="this_month" <?= $cr==='this_month'?'selected':'' ?>>This Month</option>
  <option value="prev_month" <?= $cr==='prev_month'?'selected':'' ?>>Previous Month</option>
</select>
  </div>

  <div class="col-6 col-md-2">
    <?php $ar = (string)($sf['assigned_range'] ?? ''); ?>
<select id="filterAssignedRange" class="form-select">
  <option value="" <?= $ar===''?'selected':'' ?>>Assign Date (All)</option>
  <option value="today" <?= $ar==='today'?'selected':'' ?>>Today</option>
  <option value="yesterday" <?= $ar==='yesterday'?'selected':'' ?>>Yesterday</option>
  <option value="this_week" <?= $ar==='this_week'?'selected':'' ?>>This Week</option>
  <option value="this_month" <?= $ar==='this_month'?'selected':'' ?>>This Month</option>
  <option value="prev_month" <?= $ar==='prev_month'?'selected':'' ?>>Previous Month</option>
</select>
  </div>

  <div class="col-6 col-md-1">
    <?php $pt = (string)($sf['pref_time'] ?? ''); ?>
<select id="filterPrefTime" class="form-select">
  <option value="" <?= $pt===''?'selected':'' ?>>Pref Time (All)</option>
  <option value="morning" <?= $pt==='morning'?'selected':'' ?>>morning</option>
  <option value="afternoon" <?= $pt==='afternoon'?'selected':'' ?>>afternoon</option>
  <option value="evening" <?= $pt==='evening'?'selected':'' ?>>evening</option>
  <option value="anytime" <?= $pt==='anytime'?'selected':'' ?>>anytime</option>
</select>
  </div>

  <div class="col-6 col-md-12 col-lg-2 d-grid">
    <button class="btn btn-outline-primary" id="btnApplyFilters" type="button">
      <?= e(t('global.search')) ?>
    </button>
    
     <button class="btn btn-outline-secondary" id="btnResetFilters" type="button"><?= e(t('global.reset')) ?></button>
  </div>
  
 

</div>

    <div class="table-responsive">
      <table id="leadsTable" class="table table-striped table-hover align-middle w-100">
        <thead>
          <tr>
            <?php if (has_role($u, ['CC_SUP','ADMIN'])): ?>
              <th style="width:36px;"><input type="checkbox" id="checkAll"></th>
            <?php endif; ?>
            <th style="width:70px;">#</th>
            <th><?= e(t('contacts.mobile')) ?></th>
            <th><?= e(t('contacts.name')) ?></th>
            <th><?= e(t('leads.source')) ?></th>
            <th><?= e(t('leads.status')) ?></th>
            <th><?= e(t('leads.vehicle_of_interest')) ?></th>
            <th><?= e(t('leads.first_view_at')) ?></th>
          </tr>
        </thead>
        <tbody>
          <!-- Server-side DataTables will fill this -->
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- jQuery + DataTables -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>

<script>
(function(){
  const isBulkEnabled = <?= has_role($u, ['CC_SUP','ADMIN']) ? 'true' : 'false' ?>;
  const selected = new Set();
  
   function saveFiltersToSession(){
    return fetch("<?= e(base_url($config, '/index.php?r=leads/save_filters')) ?>", {
      method: "POST",
      headers: {"Content-Type":"application/x-www-form-urlencoded"},
      body: new URLSearchParams({
        _csrf: "<?= e(csrf_token()) ?>",
        q: document.getElementById('filterQ')?.value || '',
        status: document.getElementById('filterStatus')?.value || '',
        city: document.getElementById('filterCity')?.value || '',
        created_range: document.getElementById('filterCreatedRange')?.value || '',
        assigned_range: document.getElementById('filterAssignedRange')?.value || '',
        pref_time: document.getElementById('filterPrefTime')?.value || ''
      })
    }).then(r => r.json()).catch(() => ({ok:false}));
  }

  function updateSelectedUI(){
    const count = selected.size;
    const el = document.getElementById('selectedCount');
    if(el) el.textContent = String(count);

    const btn = document.getElementById('btnBulkAssign');
    if(btn) btn.disabled = (count === 0);

    // remove old hidden inputs then add again
    if(isBulkEnabled){
      const form = document.getElementById('bulkAssignForm');
      if(form){
        form.querySelectorAll('input[name="lead_ids[]"]').forEach(n => n.remove());
        selected.forEach(id => {
          const input = document.createElement('input');
          input.type = 'hidden';
          input.name = 'lead_ids[]';
          input.value = id;
          form.appendChild(input);
        });
      }
    }
  }

  function selectAllOnPage(val){
    document.querySelectorAll('.rowCheck').forEach(cb => {
      cb.checked = val;
      const id = cb.value;
      if(val) selected.add(id); else selected.delete(id);
    });
    updateSelectedUI();
  }

  // DataTable init (server-side)
  const table = $('#leadsTable').DataTable({
    processing: true,
    serverSide: true,
    searching: false, // we use our own filter inputs (SQL-side)
    pageLength: 25,
    lengthMenu: [10,25,50,100],
    order: [[ isBulkEnabled ? 1 : 0, 'desc' ]],
    ajax: {
      url: "<?= e(base_url($config, '/index.php?r=leads/datatables')) ?>",
      type: "GET",
      data: function(d){
  d.q = $('#filterQ').val() || '';
  d.status = $('#filterStatus').val() || '';
  d.city = $('#filterCity').val() || '';

  d.created_range = $('#filterCreatedRange').val() || '';
  d.assigned_range = $('#filterAssignedRange').val() || '';
  d.pref_time = $('#filterPrefTime').val() || '';
}
    },
    columns: [
      <?php if (has_role($u, ['CC_SUP','ADMIN'])): ?>
      {
        data: "id",
        orderable: false,
        render: function(data, type, row){
          const checked = selected.has(String(data)) ? 'checked' : '';
          return `<input class="form-check-input rowCheck" type="checkbox" value="${data}" ${checked}>`;
        }
      },
      <?php endif; ?>
      {
        data: "id",
        render: function(data){ 
          const url = "<?= e(base_url($config, '/index.php?r=leads/view&id=')) ?>" + data;
          return `<a href="${url}">#${data}</a>`;
        }
      },
      { data: "mobile" },
      { data: "full_name" },
      { data: "source" },
      {
        data: "status",
        render: function(data){
          data = data || '';
          return `<span class="badge text-bg-secondary">${data}</span>`;
        }
      },
      { data: "vehicle_of_interest" },
      {
        data: "first_view_at",
        render: function(data){
          return data ? `<span class="text-muted small">${data}</span>` : '';
        }
      }
    ],
    drawCallback: function(){
      // attach checkbox handlers after each draw
      if(isBulkEnabled){
        document.querySelectorAll('.rowCheck').forEach(cb => {
          cb.addEventListener('change', function(){
            if(this.checked) selected.add(this.value);
            else selected.delete(this.value);
            updateSelectedUI();
          });
        });
        // update checkAll state
        const all = document.querySelectorAll('.rowCheck');
        const checked = document.querySelectorAll('.rowCheck:checked');
        const checkAll = document.getElementById('checkAll');
        if(checkAll){
          checkAll.checked = (all.length > 0 && checked.length === all.length);
        }
      }
      updateSelectedUI();
    }
  });

  // Filters
   document.getElementById('btnApplyFilters')?.addEventListener('click', function(){
    saveFiltersToSession().then(() => table.ajax.reload());
  });
  document.getElementById('filterQ')?.addEventListener('keydown', function(e){
  if(e.key === 'Enter'){
    e.preventDefault();
    saveFiltersToSession().then(() => table.ajax.reload());
  }
});

 document.getElementById('btnResetFilters')?.addEventListener('click', function(){
    fetch("<?= e(base_url($config, '/index.php?r=leads/reset_filters')) ?>", {
      method: "POST",
      headers: {"Content-Type":"application/x-www-form-urlencoded"},
      body: new URLSearchParams({_csrf: "<?= e(csrf_token()) ?>"})
    }).then(() => {
      // reset UI
      const ids = ['filterQ','filterStatus','filterCity','filterCreatedRange','filterAssignedRange','filterPrefTime'];
      ids.forEach(id => {
        const el = document.getElementById(id);
        if (!el) return;
        el.value = '';
      });

      saveFiltersToSession().then(() => table.ajax.reload());
    });
  });

  // Bulk selection buttons
  if(isBulkEnabled){
    document.getElementById('checkAll')?.addEventListener('change', function(){
      selectAllOnPage(this.checked);
    });
    document.getElementById('btnSelectAll')?.addEventListener('click', function(){
      selectAllOnPage(true);
    });
    document.getElementById('btnClearAll')?.addEventListener('click', function(){
      // clear global selection (all pages)
      selected.clear();
      selectAllOnPage(false);
      updateSelectedUI();
    });

    // prevent bulk submit without agent
    document.getElementById('bulkAssignForm')?.addEventListener('submit', function(e){
      const agent = this.querySelector('select[name="agent_id"]')?.value || '';
      if(!agent){
        e.preventDefault();
        alert('Please select an agent');
        return;
      }
      if(selected.size === 0){
        e.preventDefault();
        alert('Please select at least one lead');
        return;
      }
    });
  }
})();






</script>