
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php $view='opps/index.php'; ?>
<?php $sf = $_SESSION['opps_filters'] ?? []; ?>

<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('opps.title') ?: 'Opportunities') ?></h4>
</div>

<?php
$isBulkEnabled = has_role($u, ['ADMIN','BR_MGR']);
$isAdmin = has_role($u, ['ADMIN']);
$isRtl = is_rtl();
$curQ  = (string)($sf['q'] ?? '');
$cr = (string)($sf['created_range'] ?? '');
$ar = (string)($sf['assigned_range'] ?? '');
$st = (string)($sf['status'] ?? '');
$sg = (string)($sf['stage'] ?? '');
$bid = (int)($sf['branch_id'] ?? 0);
?>

<?php if ($isBulkEnabled): ?>
<form id="bulkOppAssignForm" method="post" action="<?= e(base_url($config, '/index.php?r=opps/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:320px;">
      <label class="form-label mb-1">Assign to Branch Agent</label>

      <!-- For Admin: agents loaded dynamically based on selected branch -->
      <select name="agent_id" id="bulkAgentSelect" class="form-select" required>
        <option value="">Select agent</option>
      </select>

      <?php if ($isAdmin): ?>
        <div class="text-muted small mt-1">
          Select a Branch in filters to load its agents.
        </div>
      <?php endif; ?>
    </div>

    <button type="submit" class="btn btn-primary" id="btnOppBulkAssign" disabled>Bulk Assign Selected</button>
    <button type="button" class="btn btn-outline-secondary" id="btnOppSelectAll">Select all</button>
    <button type="button" class="btn btn-outline-secondary" id="btnOppClearAll">Clear</button>

    <div class="text-muted small ms-auto">
      <span id="oppSelectedCount">0</span> selected
    </div>
  </div>
</form>
<?php endif; ?>

<div class="card shadow-sm">
  <div class="card-body">

    <!-- Filters -->
    <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') ?: 'Search') ?>" value="<?= e($curQ) ?>">
      </div>

      <div class="col-6 col-md-2">
        <select id="filterCreatedRange" class="form-select">
          <option value="" <?= $cr===''?'selected':'' ?>>Opportunity 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">
        <select id="filterAssignedRange" class="form-select">
          <option value="" <?= $ar===''?'selected':'' ?>>Assigned 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-2">
        <?php $curStatus = (string)($sf['status'] ?? ''); ?>
<select id="filterStatus" class="form-select">
  <option value="" <?= $curStatus===''?'selected':'' ?>>Status (All)</option>
  <option value="open" <?= $curStatus==='open'?'selected':'' ?>>open</option>
  <option value="won" <?= $curStatus==='won'?'selected':'' ?>>won</option>
  <option value="lost" <?= $curStatus==='lost'?'selected':'' ?>>lost</option>
  <option value="on_hold" <?= $curStatus==='on_hold'?'selected':'' ?>>on_hold</option>
</select>
      </div>

      <div class="col-6 col-md-1">
        <?php $curStage = (string)($sf['stage'] ?? ''); ?>
<select id="filterStage" class="form-select">
  <option value="" <?= $curStage===''?'selected':'' ?>>Stage (All)</option>
  <option value="open_opportunity" <?= $curStage==='open_opportunity'?'selected':'' ?>>Open Opportunity</option>
  <option value="test_drive" <?= $curStage==='test_drive'?'selected':'' ?>>Test Drive</option>
  <option value="quotation_offer" <?= $curStage==='quotation_offer'?'selected':'' ?>>Quotation / Offer</option>
  <option value="finance_processing" <?= $curStage==='finance_processing'?'selected':'' ?>>Finance Processing</option>
  <option value="negotiation" <?= $curStage==='negotiation'?'selected':'' ?>>Negotiation</option>
  <option value="booking" <?= $curStage==='booking'?'selected':'' ?>>Booking</option>
  <option value="delivery_sale" <?= $curStage==='delivery_sale'?'selected':'' ?>>Delivery / Sale</option>
  <option value="closed_lost" <?= $curStage==='closed_lost'?'selected':'' ?>>Closed – Lost</option>
  <option value="on_hold" <?= $curStage==='on_hold'?'selected':'' ?>>On Hold / Nurturing</option>
</select>
      </div>

      <div class="col-12 col-md-2">
        <select id="filterBranch" class="form-select">
          <option value="" <?= $bid===0?'selected':'' ?>>Branch (All)</option>
          <?php foreach (($branches ?? []) as $b): ?>
            <option value="<?= (int)$b['id'] ?>" <?= $bid===(int)$b['id']?'selected':'' ?>>
              <?= e(is_rtl() ? $b['name_ar'] : $b['name_en']) ?> (<?= e($b['city']) ?>)
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-12 col-md-2 d-grid">
        <button class="btn btn-outline-primary" id="btnApplyFilters" type="button"><?= e(t('global.search') ?: 'Search') ?></button>
      </div>

      <div class="col-12 col-md-2 d-grid">
        <button class="btn btn-outline-secondary" id="btnResetFilters" type="button"><?= e(t('global.reset') ?: 'Reset') ?></button>
      </div>
    </div>

    <!-- Table -->
    <div class="table-responsive">
      <table id="oppsTable" class="table table-striped table-hover align-middle w-100">
        <thead>
          <tr>
            <?php if ($isBulkEnabled): ?>
              <th style="width:36px;"><input type="checkbox" id="oppCheckAll"></th>
            <?php endif; ?>
            <th style="width:70px;">#</th>
            <th><?= e(t('contacts.mobile') ?: 'Mobile') ?></th>
            <th><?= e(t('contacts.name') ?: 'Name') ?></th>
            <th>Branch</th>
            <th>Stage</th>
            <th>Stage Status</th>
            <th>Status</th>
            <th>Assigned At</th>
            <th>Created At</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>

  </div>
</div>

<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 = <?= $isBulkEnabled ? 'true' : 'false' ?>;
  const isAdmin = <?= $isAdmin ? 'true' : 'false' ?>;
  const isRtl = <?= $isRtl ? 'true' : 'false' ?>;

  const selected = new Set();

  function updateSelectedUI(){
    const count = selected.size;
    const el = document.getElementById('oppSelectedCount');
    if (el) el.textContent = String(count);

    const btn = document.getElementById('btnOppBulkAssign');
    if (btn) btn.disabled = (count === 0);

    // attach hidden inputs to form
    const form = document.getElementById('bulkOppAssignForm');
    if (isBulkEnabled && form){
      form.querySelectorAll('input[name="opp_ids[]"]').forEach(n => n.remove());
      selected.forEach(id => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'opp_ids[]';
        input.value = id;
        form.appendChild(input);
      });
    }
  }

  function selectAllOnPage(val){
    document.querySelectorAll('.oppRowCheck').forEach(cb => {
      cb.checked = val;
      const id = cb.value;
      if (val) selected.add(id); else selected.delete(id);
    });
    updateSelectedUI();
  }

  function saveOppFilters(){
    return fetch("<?= e(base_url($config, '/index.php?r=opps/save_filters')) ?>", {
      method: "POST",
      headers: {"Content-Type":"application/x-www-form-urlencoded"},
      body: new URLSearchParams({
        _csrf: "<?= e(csrf_token()) ?>",
        q: $('#filterQ').val() || '',
        created_range: $('#filterCreatedRange').val() || '',
        assigned_range: $('#filterAssignedRange').val() || '',
        status: $('#filterStatus').val() || '',
        stage: $('#filterStage').val() || '',
        branch_id: $('#filterBranch').val() || ''
      })
    }).then(r => r.json()).catch(() => ({ok:false}));
  }

  function resetOppFilters(){
    return fetch("<?= e(base_url($config, '/index.php?r=opps/reset_filters')) ?>", {
      method: "POST",
      headers: {"Content-Type":"application/x-www-form-urlencoded"},
      body: new URLSearchParams({_csrf: "<?= e(csrf_token()) ?>"})
    }).then(r => r.json()).catch(() => ({ok:false}));
  }

  function loadAgentsForBranch(branchId){
    const sel = document.getElementById('bulkAgentSelect');
    if (!sel) return;

    // For admin, require branch selection
    if (isAdmin && (!branchId || String(branchId).trim() === '')) {
      sel.innerHTML = `<option value="">Select branch first</option>`;
      sel.disabled = true;
      return;
    }

    sel.disabled = true;
    sel.innerHTML = `<option value="">Loading...</option>`;

    fetch("<?= e(base_url($config, '/index.php?r=opps/agents')) ?>&branch_id=" + encodeURIComponent(branchId || ''), {
      method: "GET"
    })
      .then(r => r.json())
      .then(json => {
        const agents = json.agents || [];
        const options = ['<option value="">Select agent</option>'];
        for (const a of agents) {
          options.push(`<option value="${a.id}">${escapeHtml(a.name)} (${escapeHtml(a.mobile || '')})</option>`);
        }
        sel.innerHTML = options.join('');
        sel.disabled = false;
      })
      .catch(() => {
        sel.innerHTML = `<option value="">Failed to load</option>`;
        sel.disabled = false;
      });
  }

  function escapeHtml(str){
    return String(str ?? '').replace(/[&<>"']/g, function(m){
      return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]);
    });
  }

  // DataTable init
  const table = $('#oppsTable').DataTable({
    processing: true,
    serverSide: true,
    searching: false,
    pageLength: 25,
    lengthMenu: [10,25,50,100],
    order: [[ isBulkEnabled ? 1 : 0, 'desc' ]],
    ajax: {
      url: "<?= e(base_url($config, '/index.php?r=opps/datatables')) ?>",
      type: "GET",
      data: function(d){
        d.q = $('#filterQ').val() || '';
        d.created_range = $('#filterCreatedRange').val() || '';
        d.assigned_range = $('#filterAssignedRange').val() || '';
        d.status = $('#filterStatus').val() || '';
        d.stage = $('#filterStage').val() || '';
        d.branch_id = $('#filterBranch').val() || '';
      }
    },
    columns: [
      <?php if ($isBulkEnabled): ?>
      {
        data: "id",
        orderable: false,
        render: function(data){
          const checked = selected.has(String(data)) ? 'checked' : '';
          return `<input class="form-check-input oppRowCheck" type="checkbox" value="${data}" ${checked}>`;
        }
      },
      <?php endif; ?>
      {
        data: "id",
        render: function(data){
          const url = "<?= e(base_url($config, '/index.php?r=opps/view&id=')) ?>" + data;
          return `<a href="${url}">#${data}</a>`;
        }
      },
      { data: "mobile" },
      { data: "full_name" },
      {
        data: null,
        render: function(row){
          const name = isRtl ? (row.branch_name_ar || '') : (row.branch_name_en || '');
          return name;
        }
      },
      { data: "stage" },
      { data: "stage_status" },
      {
        data: "status",
        render: function(data){
          data = data || '';
          return `<span class="badge text-bg-secondary">${data}</span>`;
        }
      },
      { data: "assigned_at" },
      { data: "created_at" }
    ],
    drawCallback: function(){
      if (isBulkEnabled){
        document.querySelectorAll('.oppRowCheck').forEach(cb => {
          cb.addEventListener('change', function(){
            if (this.checked) selected.add(this.value);
            else selected.delete(this.value);
            updateSelectedUI();
          });
        });

        const all = document.querySelectorAll('.oppRowCheck');
        const checked = document.querySelectorAll('.oppRowCheck:checked');
        const checkAll = document.getElementById('oppCheckAll');
        if (checkAll){
          checkAll.checked = (all.length > 0 && checked.length === all.length);
        }
      }
      updateSelectedUI();
    }
  });

  // Apply filters
  document.getElementById('btnApplyFilters')?.addEventListener('click', function(){
    saveOppFilters().then(() => {
      table.ajax.reload();
      if (isBulkEnabled) {
        loadAgentsForBranch($('#filterBranch').val() || '');
      }
    });
  });

  // Enter on search
  document.getElementById('filterQ')?.addEventListener('keydown', function(e){
    if (e.key === 'Enter') {
      e.preventDefault();
      document.getElementById('btnApplyFilters')?.click();
    }
  });

  // Reset filters
  document.getElementById('btnResetFilters')?.addEventListener('click', function(){
    resetOppFilters().then(() => {
      $('#filterQ').val('');
      $('#filterCreatedRange').val('');
      $('#filterAssignedRange').val('');
      $('#filterStatus').val('');
      $('#filterStage').val('');
      $('#filterBranch').val('');

      saveOppFilters().then(() => {
        table.ajax.reload();
        if (isBulkEnabled) loadAgentsForBranch('');
      });
    });
  });

  // Bulk selection buttons
  if (isBulkEnabled){
    document.getElementById('oppCheckAll')?.addEventListener('change', function(){
      selectAllOnPage(this.checked);
    });
    document.getElementById('btnOppSelectAll')?.addEventListener('click', function(){
      selectAllOnPage(true);
    });
    document.getElementById('btnOppClearAll')?.addEventListener('click', function(){
      selected.clear();
      selectAllOnPage(false);
      updateSelectedUI();
    });

    document.getElementById('bulkOppAssignForm')?.addEventListener('submit', function(e){
      const agent = document.getElementById('bulkAgentSelect')?.value || '';
      if (!agent){
        e.preventDefault();
        alert('Please select an agent');
        return;
      }
      if (selected.size === 0){
        e.preventDefault();
        alert('Please select at least one opportunity');
        return;
      }
    });

    // initial load agents based on saved branch filter
    loadAgentsForBranch($('#filterBranch').val() || '');
  }
})();
</script>
