/*****************************************************************
 * File Name   : helpdesk.js
 * Developer   : Farhan Akhtar
 * Module      : Helpdesk Ticket Listing, Agent Assignment,
 *               Queue Assignment, Queue Management
 * Last Modified on : 12-02-2026
 * Description :
 *  - Manual Agent Assignment
 *  - Queue Based Assignment
 *  - Create Queue with multiple agents
 *  - Map Queue to Department
 *  - Export buttons & filters
 *****************************************************************/

/* ============================================================
 GLOBALS
============================================================ */

var currentAssignFilter = 'all';
var currentStatusFilter = '';
var currentDepartmentId = '';
var currentQueueId = '';

/* ============================================================
 DATATABLE
============================================================ */

function fill_datatable(
    filter_state = '',
    filter_status = '',
    filter_source = '',
    filter_priority_user = '',
    search_ticket = ''
){

    var groupid = $("#groupid").val();
    var userid  = $("#userid").val();

    $('#customer_data').DataTable({

        processing:true,
        serverSide:true,
        destroy:true,
        pageLength:10,
        order:[[11,"desc"]],
        dom:
          "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6 text-end'B>>"+
          "<'row'<'col-sm-12'tr>>"+
          "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",      
        columnDefs: [{
        targets: 13, // Assignment Remark column (counting checkbox as 0)
        orderable: false,
        searchable: false,
        className: 'text-center',
        
        render: function(data, type, row, meta){
          var remark = (data || '').toString().trim();
          if(!remark) return '';

          // Escape for data attribute
          var safe = remark
            .replace(/&/g,'&amp;')
            .replace(/</g,'&lt;')
            .replace(/>/g,'&gt;')
            .replace(/"/g,'&quot;')
            .replace(/'/g,'&#039;');

          return `
            <a href="javascript:void(0)" 
              class="remark-icon"
              data-remark="${safe}"
              title="Click to view remark">
              <i class="fa fa-sticky-note text-success"></i>
            </a>
          `;
        }
       }],

        buttons:[
            { extend:'excelHtml5', text:'<i class="fa fa-file-excel-o text-success"></i>' },
            { extend:'csvHtml5', text:'<i class="fa fa-table text-primary"></i>', title:'', messageTop:'' },
            { extend:'pdfHtml5',
              text:'<i class="fa fa-file-pdf-o text-danger"></i>',
              orientation:'landscape',
              pageSize:'A3',
              title:'',
              messageTop:'',
              customize:function(doc){
                if(typeof LOGO_BASE64!=="undefined"){
                    doc.images=doc.images||{};
                    doc.images.logo=LOGO_BASE64;
                    doc.content.unshift({
                        image:'logo',
                        width:160,
                        margin:[0,0,0,10]
                    });
                }
              }
            },
            { extend:'colvis', text:'<i class="fa fa-columns text-warning"></i>' }
        ],

        ajax:{
            url:"helpdesk/web_helpdesk_function.php",
            type:"POST",
            data:function(d){

                d.filter_state = filter_state;
                d.filter_status = filter_status;
                d.filter_source = filter_source;
                d.filter_priority_user = filter_priority_user;
                d.search_ticket = search_ticket;

                d.groupid = groupid;
                d.userid  = userid;

                if(groupid==='0000'||groupid==='080000'){
                    d.assign_filter=currentAssignFilter;
                }else{
                    d.assign_filter='all';
                }

                d.quick_status=currentStatusFilter;
                d.action='helpdesk_list';
            }
        }
    });
}

/* ============================================================
 DOCUMENT READY
============================================================ */

$(document).ready(function(){

    fill_datatable();

    $(document).on('click', '.url-link', function() {
        var ticketId = $(this).data('ticketid');
        var encodedToken = btoa('web_case_detail');
        var redirectURL = "helpdesk_index.php?token=" + encodeURIComponent(encodedToken)+"&id=" + encodeURIComponent(ticketId);
        window.location.href = redirectURL;
    });

    /* ------------------------
     SELECT ALL
    ------------------------ */
    $(document).on('change','#select_all_tickets',function(){
        $('.ticket-checkbox').prop('checked',this.checked);
    });

    /* ------------------------
     FILTER CHIPS
    ------------------------ */
    $(document).on('click','.assign-chip',function(){
        $('.assign-chip').removeClass('active');
        $(this).addClass('active');
        currentAssignFilter=$(this).data('filter');
        $('#customer_data').DataTable().ajax.reload();
    });

    /* ------------------------
     QUICK STATUS
    ------------------------ */
    $(document).on('click','.status-item',function(){
        $('.status-item').removeClass('active');
        $(this).addClass('active');
        currentStatusFilter=$(this).data('status');
        $('#customer_data').DataTable().ajax.reload();
    });

});

/* ============================================================
 AGENT DROPDOWN - FIXED WITH .OFF()
============================================================ */

/* CREATE QUEUE - Full Agent List */
$(document).off('click', '#agentSelectBox').on('click', '#agentSelectBox', function(e){
  e.preventDefault(); e.stopPropagation();

  const $dd = $('#agentDropdown');
  const $tr = $(this);

  if($dd.hasClass('show')){
    ddCloseAll();
    return;
  }

  $('#editAgentDropdown').removeClass('show').hide();

  if($('#agentList .agent-row').length === 0 && !_agentDD.mainLoading){
    _agentDD.mainLoading = true;
    $('#agentList').html('<div style="padding:24px;text-align:center;color:#999;">🔄 Loading full agent list...</div>');

    loadAgentsMulti(function(){
      _agentDD.mainLoading = false;
      ddOpen($tr, $dd, 'main');
    });
  } else {
    ddOpen($tr, $dd, 'main');
  }
});

/* EDIT QUEUE - Full Agent List */
$(document).off('click', '#editAgentSelectBox').on('click', '#editAgentSelectBox', function(e){
  e.preventDefault(); e.stopPropagation();

  const $dd = $('#editAgentDropdown');
  const $tr = $(this);

  if($dd.hasClass('show')){
    ddCloseAll();
    return;
  }

  $('#agentDropdown').removeClass('show').hide();

  if($('#editAgentList .agent-row').length === 0 && !_agentDD.editLoading){
    _agentDD.editLoading = true;
    $('#editAgentList').html('<div style="padding:24px;text-align:center;color:#999;">🔄 Loading full agent list...</div>');

    loadEditAgentDropdown(function(){
      _agentDD.editLoading = false;
      ddOpen($tr, $dd, 'edit');
    });
  } else {
    ddOpen($tr, $dd, 'edit');
  }
});


$(document).off('mousedown.agentdd').on('mousedown.agentdd', function(e){
  const inside =
    $(e.target).closest('#agentSelectBox, #editAgentSelectBox, #agentDropdown, #editAgentDropdown').length > 0;

  if(!inside) ddCloseAll();
});

// prevent inside clicks from bubbling
$(document).off('mousedown', '#agentDropdown, #editAgentDropdown')
  .on('mousedown', '#agentDropdown, #editAgentDropdown', function(e){
    e.stopPropagation();
  });



/* Close dropdowns on outside click - FIXED */
$(document).off('click.dropdown').on('click.dropdown', function(e) {
  if (!$(e.target).closest('.agent-multi-select').length) {
    $('#agentDropdown').hide();
    $('#editAgentDropdown').hide();
  }
});

/* Prevent dropdown close when clicking inside - FIXED */
$(document).off('click', '.agent-dropdown').on('click', '.agent-dropdown', function(e) {
  e.stopPropagation();
});

/* ============================================================
 OPEN ASSIGN MODAL
============================================================ */

$('#openAssignModal').click(function(){

    if($('.ticket-checkbox:checked').length==0){
        alert("Select at least one ticket");
        return;
    }

    $('#assignment_remark').val('');   // NEW

    loadAgentDropdown();
    $('#agentBox').show();
    $('#queueBox').hide();
    $('input[value="agent"]').prop('checked',true);

    $('#assign-modal').css('display','flex');
});

$('#cancel-assign').click(function(){
    $('#assign-modal').hide();
});

/* ============================================================
 CONFIRM ASSIGN
============================================================ */
$('#confirm-assign').click(function(){

    // prevent double click
    if($(this).data('busy')) return;

    $(this).data('busy', true);   // lock button
    $(this).prop('disabled', true);

    var mode = $('input[name="assign_mode"]:checked').val();
    var tickets = getSelectedTickets();

    if(tickets.length===0){
        alert("Select at least one ticket");
        unlockAssignButton();
        return;
    }

    var remark = ($('#assignment_remark').val() || '').trim();
    if(!remark){
        alert("Assignment remark is mandatory");
        $('#assignment_remark').focus();
        unlockAssignButton();
        return;
    }

    $.post("helpdesk/web_helpdesk_function.php",{
        action:'check_assigned',
        tickets:tickets
    },function(res){

        if(res.alreadyAssigned){
            let msg = "Some selected tickets are already assigned.\n\n";

            if(res.agents && res.agents.length){
                msg += "Agents: " + res.agents.join(', ') + "\n";
            }

            if(res.queues && res.queues.length){
                msg += "Queues: " + res.queues.join(', ') + "\n";
            }

            msg += "\nDo you want to reassign them?";

            if(!confirm(msg)){
                unlockAssignButton();
                return;
            }
        }

        proceedAssign(mode, tickets, remark);

    },'json');
});



/* toggle agent / queue */
$(document).on('change', 'input[name="assign_mode"]', function() {
  if (this.value === 'agent') {
    $('#agentBox').show();
    $('#queueBox').hide();
  } else {
    $('#agentBox').hide();
    $('#queueBox').show();
    
    //  ALWAYS reload fresh queues
    setTimeout(loadQueuesForAssignment, 100);  // small delay after show()
  }
});

/* ============================================================
 QUEUE MANAGEMENT MODAL - FIXED
============================================================ */

/* ============================================================
  AGENT DROPDOWN - BULLETPROOF FULL LIST (PASTE THIS)
============================================================ */

let _agentDD = {
  open: null,           // 'main' | 'edit' | null
  mainLoading: false,
  editLoading: false
};

function ddEnsureInBody($dd){
  if(!$dd.data('in-body')){
    $dd.appendTo(document.body);
    $dd.data('in-body', true);
  }
}

function ddCloseAll(){
  _agentDD.open = null;
  $('#agentDropdown, #editAgentDropdown').removeClass('show').hide();
}

function ddOpen($trigger, $dd, type){
  ddEnsureInBody($dd);
  $dd.addClass('show').css({ display: 'block' });

  const el = $trigger.get(0);
  if(!el) return;

  const rect = el.getBoundingClientRect();
  const minW = 650;  // Wider for full list
  const pad  = 8;

  let width = Math.max(rect.width, minW);
  let left  = rect.left;
  let top   = rect.bottom + 4;

  const vw = window.innerWidth;
  const vh = window.innerHeight;
  const ddH = $dd.outerHeight() || 450;

  // Clamp to viewport
  if(left + width + pad > vw) left = Math.max(pad, vw - width - pad);
  if(left < pad) left = pad;
  
  if(top + ddH + pad > vh && rect.top - ddH - 4 > pad){
    top = rect.top - ddH - 4;
  }
  if(top < pad) top = pad;

  $dd.css({
    position: 'fixed',
    top: top + 'px',
    left: left + 'px',
    width: width + 'px',
    zIndex: 99999
  });

  _agentDD.open = type;
}

let _ddRaf = null;
function ddRepositionIfOpen(){
  if(_ddRaf) cancelAnimationFrame(_ddRaf);
  _ddRaf = requestAnimationFrame(function(){
    if(_agentDD.open === 'main'){
      ddOpen($('#agentSelectBox'), $('#agentDropdown'), 'main');
    } else if(_agentDD.open === 'edit'){
      ddOpen($('#editAgentSelectBox'), $('#editAgentDropdown'), 'edit');
    }
  });
}

$(window).off('resize.agentdd scroll.agentdd').on('resize.agentdd scroll.agentdd', ddRepositionIfOpen);



$(document).off('click', '#openQueueModal').on('click', '#openQueueModal', function(){
    console.log('🚀 Opening Queue Modal');
    
    // Clear existing dropdown content
    $('#agentList').empty();
    $('#editAgentList').empty();
    
    // Hide dropdowns
    $('#agentDropdown').hide();
    $('#editAgentDropdown').hide();
    
    // Reset select boxes
    $('#agentSelectBox').text('Select Agents');
    $('#editAgentSelectBox').text('Add Agents');
    
    // Load data
    loadAgentsMulti();
    loadAllQueues();
    loadDepartmentList();
    loadQueueCards();
    
    // Show modal
    $('#queue-modal').css('display','flex');
});

$(document).off('click', '#closeQueueModal').on('click', '#closeQueueModal', function(){
    console.log('🔒 Closing Queue Modal');
    $('#queue-modal').hide();
    $('#agentDropdown').hide();
    $('#editAgentDropdown').hide();
});

/* ============================================================
 CREATE QUEUE — HARD LOCK
============================================================ */

$(document).off('click', '#createQueueBtn');

$(document).on('click', '#createQueueBtn', function (e) {

    e.preventDefault();
    e.stopImmediatePropagation();
    e.stopPropagation();

    console.log('🔥 CREATE QUEUE HANDLER FIRED');

    var btn = $(this);
    var queueName = $('#queue_name').val().trim();

    var agentsStr = $('#queue_agents').val();
    agentsStr = agentsStr ? agentsStr.trim() : '';

    console.log('AGENTS RAW:', $('#queue_agents').val());
    console.log('AGENTS CLEAN:', agentsStr);

    var agents = agentsStr.split(',').filter(Boolean);

    console.log(agents)

    if (queueName.length === 0) {
        alert("Please enter queue name");
        return false;
    }

    if (agents.length === 0) {
        alert("Select at least one agent");
        return false;
    }

    btn.prop('disabled', true).text('Creating...');

    $.ajax({
        url: "helpdesk/web_helpdesk_function.php",
        type: "POST",
        dataType: "json",
        data: {
            action: 'create_queue',
            queue_name: queueName,
            agents: agents.join(',')
        },
        success: function (res) {

            if (res.status === 'success') {

                alert("Queue created successfully");

                $('#queue_name').val('');
                $('#queue_agents').val('');
                $('#agentSelectBox').text('Select Agents');
                $('#agentList input.agent-check').prop('checked', false);

                loadAllQueues();
                loadAgentsMulti();  // refresh agents list

            } else {
                alert(res.msg || "Failed to create queue");
            }
        },
        complete: function () {
            btn.prop('disabled', false).text('Create Queue');
        }
    });

    return false;
});

/* ============================================================
 MAP QUEUE TO DEPARTMENT
============================================================ */

$('#mapQueueBtn').click(function(){

    var q=$('#map_queue').val();
    var d=$('#map_department').val();

    if(!q||!d){
        alert("Select queue & department");
        return;
    }

    $.post("helpdesk/web_helpdesk_function.php",{
        action:'map_queue_department',
        queue_id:q,
        department_id:d
    },function(res){

        if(res.status==='success'){
            alert("Mapped successfully");
        }else{
            alert(res.msg);
        }

    },'json');
});

/* ============================================================
 HELPERS
============================================================ */

function unlockAssignButton(){
    $('#confirm-assign').data('busy', false);
    $('#confirm-assign').prop('disabled', false);
}


function afterAssign(res){

    unlockAssignButton();   // always unlock

    if(res.status==='success'){
        alert("Assigned successfully");
        $('#assign-modal').hide();
        $('#customer_data').DataTable().ajax.reload(null,false);
    }else{
        alert(res.msg);
    }

    loadAgentDropdown();
    loadAgentsMulti();
}


function getSelectedTickets(){
    var t=[];
    $('.ticket-checkbox:checked').each(function(){
        t.push($(this).val());
    });
    return t;
}

/* ============================================================
 LOADERS
============================================================ */

function loadAgentDropdown(){

    $.post("helpdesk/web_helpdesk_function.php",
    {action:'get_agent_list'},
    function(res){

        var d = $('#agent_select');
        d.html('<option value="">Select Agent</option>');

        let lowestLoad = null;
        let lowestAgent = null;

        $.each(res,function(i,a){

            let load = parseInt(a.assigned || 0);

            let color = 'green';
            if(load >= 6 && load <= 15) color = 'orange';
            if(load >= 16) color = 'red';

            // auto-select logic
            if(lowestLoad === null || load < lowestLoad){
                lowestLoad = load;
                lowestAgent = a.id;
            }

            d.append(`
                <option 
                    value="${a.id}"
                    title="Queues: ${a.queue_details}"
                >
                    ● ${a.name} (${load})
                </option>
            `);

            // apply color later using css class
            d.find('option:last')[0].dataset.loadColor = color;

        });

        // Auto select least loaded agent
        if(lowestAgent){
            d.val(lowestAgent);
        }

        // Apply color dots
        $('#agent_select option').each(function(){
            let c = this.dataset.loadColor;
            if(c){
                this.style.color = 
                    (c==='green') ? '#2e7d32' :
                    (c==='orange') ? '#f9a825' :
                    '#d32f2f';
            }
        });

    },'json');
}

/* Load agents for multi-select with queue info - WITH CALLBACK */
function loadAgentsMulti(callback){
    console.log('📥 Loading agents (fresh)...');
    
    $.post("helpdesk/web_helpdesk_function.php",
    { action:'get_agent_list',
        _t: Date.now()  // cache buster
     },
    function(res){
        console.log('📥 Agents received:', res.length);
        
        let html = '';
        
        $.each(res, function(i, a){
            // Determine workload level
            let load = parseInt(a.assigned || 0);
            let workloadClass = 'low';
            let workloadText = 'Light';
            
            if(load >= 6 && load <= 15) {
                workloadClass = 'medium';
                workloadText = 'Moderate';
            } else if(load >= 16) {
                workloadClass = 'high';
                workloadText = 'Heavy';
            }
            
            // Parse queue details (format: "QueueName|Department||QueueName2|unmapped")
            let queueHTML = '';
            
            if(a.queue_details && a.queue_details !== 'none') {
                let queues = a.queue_details.split('||');
                let uniqueQueues = new Set(); // Prevent duplicates
                
                queues.forEach(q => {
                    if(!q) return;
                    
                    let [queueName, deptOrStatus] = q.split('|');
                    
                    if(uniqueQueues.has(queueName)) return; // Skip duplicates
                    uniqueQueues.add(queueName);
                    
                    if(deptOrStatus === 'unmapped') {
                        // Queue exists but not mapped to department
                        queueHTML += `<span class="queue-tag queue-unmapped">
                            <i class="fa fa-exclamation-triangle"></i>${queueName} (Not mapped)
                        </span>`;
                    } else {
                        // Queue mapped to department
                        queueHTML += `<span class="queue-tag queue-mapped">
                            <i class="fa fa-layer-group"></i>${queueName} (${deptOrStatus})
                        </span>`;
                    }
                });
            }
            
            if(!queueHTML) {
                queueHTML = '<span class="queue-tag no-queue"><i class="fa fa-user-times"></i>Not in any queue</span>';
            }
            
            html += `
                <div class="agent-row">
                    <input 
                        type="checkbox"
                        class="agent-check"
                        value="${a.id}"
                    >
                    <div class="agent-info">
                        <div class="agent-name">${a.name}</div>
                        <div class="agent-meta">
                            <div class="agent-workload">
                                <span class="workload-dot ${workloadClass}"></span>
                                <span class="workload-text">${workloadText} Load: ${load} tickets</span>
                            </div>
                            <div class="agent-queues">
                                ${queueHTML}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        
        $('#agentList').html(html);
        console.log('✅ Agents rendered:', $('#agentList .agent-row').length);
        
        // Call callback if provided
        if(typeof callback === 'function') {
            callback();
        }
        
    }, 'json')
    .fail(function(){
        console.error('❌ Failed to load agents');
        $('#agentList').html('<div style="padding:20px;text-align:center;color:#f44336;">Failed to load agents</div>');
    });
}

/* collect agents */
$(document).on('change', '.agent-check', function () {

    var ids = [];

    $('#agentList input.agent-check:checked').each(function () {
        ids.push($(this).val());
    });

    // store inside textbox
    $('#queue_agents').val(ids.join(','));

    // update label
    if (ids.length > 0) {
        $('#agentSelectBox').text(ids.length + " agent(s) selected");
    } else {
        $('#agentSelectBox').text("Select Agents");
    }

});

/* search */
$('#agentSearch').keyup(function(){

    var v=$(this).val().toLowerCase();

    $('#agentList .agent-row').filter(function(){
        $(this).toggle(
            $(this).text().toLowerCase().indexOf(v)>-1
        );
    });
});

/* departments */
function loadDepartmentList(){

    $.post("helpdesk/web_helpdesk_function.php",
    {action:'get_department_list'},function(res){

        var d=$('#map_department');
        d.html('<option value="">Select Department</option>');

        $.each(res,function(i,row){
            d.append(`<option value="${row.id}">
                ${row.name}
            </option>`);
        });
    },'json');
}

/* all queues */
function loadAllQueues(){

    $.post("helpdesk/web_helpdesk_function.php",
    {action:'get_queue_list'},function(res){

        var q=$('#map_queue');
        q.html('<option value="">Select Queue</option>');

        $.each(res,function(i,row){
            q.append(`<option value="${row.queue_id}">
                ${row.queue_name} (${row.agent_count})
            </option>`);
        });
    },'json');
}

/* queues for assignment - BULLETPROOF */
function loadQueuesForAssignment() {
  // show loading state
  $('#queue_select').html('<option>Loading queues...</option>').prop('disabled', true);
  
  $.ajax({
    url      : 'helpdesk/web_helpdesk_function.php',
    type     : 'POST',
    dataType : 'json',
    timeout  : 10000,  // 10s timeout
    data     : { action: 'get_mapped_queues' },
    success  : function(res) {
      var q = $('#queue_select');
      
      // always reset to empty first
      q.html('<option value="">Select Queue</option>').prop('disabled', false);
      
      if (!res || !Array.isArray(res) || res.length === 0) {
        q.append('<option value="" disabled>No mapped queues found</option>');
        return;
      }
      
      $.each(res, function(i, row) {
        var agentText = row.agents || row.agent_count || 'No Agents';
        var deptText  = row.departments || 'No Dept';
        
        q.append(`
          <option value="${row.queue_id}"
                  title="Agents: ${agentText}">
            ${row.queue_name} (${row.agent_count || 0}) - ${deptText}
          </option>
        `);
      });
      
      console.log(`✅ Loaded ${res.length} queues`);
    },
    error: function(xhr, status, error) {
      console.error('Queue load failed:', error);
      $('#queue_select').html('<option value="" disabled>Error loading queues</option>');
    }
  });
}

function proceedAssign(mode, tickets, remark){

    // AGENT MODE
    if(mode==='agent'){

        var agentId = $('#agent_select').val();

        if(!agentId){
            alert("Select agent");
            return;
        }

        $.post("helpdesk/web_helpdesk_function.php",{
            action:'assign_cases',
            agent_id:agentId,
            tickets:tickets,
            assignment_remark: remark
        },afterAssign,'json');
    }

    // QUEUE MODE
    else{

        var queueId = $('#queue_select').val();

        if(!queueId){
            alert("Select queue");
            return;
        }

        $.post("helpdesk/web_helpdesk_function.php",{
            action:'assign_to_queue',
            queue_id:queueId,
            tickets:tickets,
            assignment_remark: remark
        },afterAssign,'json');
    }
}

/* ===================================
   QUEUE EDIT/DELETE FUNCTIONALITY
=================================== */

let currentEditQueueId = null;
let allQueuesData = [];

/* Tab switching */
$(document).on('click', '.tab-btn', function() {
  const tab = $(this).data('tab');
  
  $('.tab-btn').removeClass('active');
  $(this).addClass('active');
  
  $('.queue-tab-content').removeClass('active');
  $(`#${tab}-tab`).addClass('active');
  
  // Load data when switching to view tab
  if (tab === 'view') {
    loadQueueCards();
  }
});

/* Load queue cards for view tab */
function loadQueueCards() {
  $.ajax({
    url: 'helpdesk/web_helpdesk_function.php',
    type: 'POST',
    dataType: 'json',
    data: { action: 'get_queue_details' },
    success: function(res) {
      allQueuesData = res;
      renderQueueCards(res);
    },
    error: function() {
      $('#queueListContainer').html('<div class="queue-empty-state"><i class="fa fa-exclamation-circle"></i><p>Failed to load queues</p></div>');
    }
  });
}

/* Render queue cards */
function renderQueueCards(queues) {
  const container = $('#queueListContainer');
  
  if (!queues || queues.length === 0) {
    container.html(`
      <div class="queue-empty-state">
        <i class="fa fa-inbox"></i>
        <p>No queues created yet</p>
      </div>
    `);
    $('#totalQueues').text('0 queues');
    return;
  }
  
  $('#totalQueues').text(`${queues.length} queue${queues.length > 1 ? 's' : ''}`);
  
  let html = '';
  
  queues.forEach(q => {
    const agentTags = q.agents && q.agents.length > 0 
      ? q.agents.map(a => `<span class="agent-tag">${a.name}</span>`).join('')
      : '<span class="agent-tag">No agents</span>';
    
    const deptText = q.departments || 'Not mapped';
    
    html += `
      <div class="queue-card" data-queue-id="${q.queue_id}">
        <div class="queue-card-header">
          <h4 class="queue-card-title">${q.queue_name}</h4>
          <span class="queue-card-badge">${q.agent_count} agent${q.agent_count !== 1 ? 's' : ''}</span>
        </div>
        <div class="queue-card-meta">
          <span><i class="fa fa-users"></i>${q.agent_count} Agents</span>
          <span><i class="fa fa-sitemap"></i>${deptText}</span>
        </div>
        <div class="queue-card-agents">
          <div class="queue-card-agents-label">Agents:</div>
          <div class="agent-tags">${agentTags}</div>
        </div>
        <div class="queue-card-actions">
          <button class="btn btn-sm btn-edit" onclick="openEditQueue(${q.queue_id})">
            <i class="fa fa-edit"></i> Edit
          </button>
          <button class="btn btn-sm btn-delete" onclick="confirmDeleteQueue(${q.queue_id}, '${q.queue_name.replace(/'/g, "\\'")}')">
            <i class="fa fa-trash"></i> Delete
          </button>
        </div>
      </div>
    `;
  });
  
  container.html(html);
}

/* Search queues */
$('#searchQueue').on('keyup', function() {
  const search = $(this).val().toLowerCase();
  
  if (!search) {
    renderQueueCards(allQueuesData);
    return;
  }
  
  const filtered = allQueuesData.filter(q => 
    q.queue_name.toLowerCase().includes(search) ||
    (q.departments && q.departments.toLowerCase().includes(search))
  );
  
  renderQueueCards(filtered);
});

/* Open edit queue modal */
window.openEditQueue = function(queueId) {
  currentEditQueueId = queueId;
  
  $.ajax({
    url: 'helpdesk/web_helpdesk_function.php',
    type: 'POST',
    dataType: 'json',
    data: {
      action: 'get_queue_details_by_id',
      queue_id: queueId
    },
    success: function(res) {
      if (res.status === 'success') {
        populateEditModal(res.data);
        ddCloseAll();
        loadEditAgentDropdown(); // preload to remove first-click race

        $('#edit-queue-overlay').css('display', 'flex');
      } else {
        alert(res.msg || 'Failed to load queue details');
      }
    }
  });
};

/* Populate edit modal */
function populateEditModal(data) {
  $('#edit_queue_id').val(data.queue_id);
  $('#edit_queue_name').val(data.queue_name);
  
  // Display current agents
  const agentContainer = $('#editAgentListContainer');
  agentContainer.empty();
  
  if (data.agents && data.agents.length > 0) {
    data.agents.forEach(agent => {
      agentContainer.append(`
        <span class="agent-tag-removable">
          ${agent.name}
          <button class="agent-tag-remove" onclick="removeAgentFromQueue(${data.queue_id}, ${agent.id})">×</button>
        </span>
      `);
    });
  } else {
    agentContainer.html('<span class="agent-tag">No agents assigned</span>');
  }
  
  // Reset add agents dropdown
  $('#edit_queue_agents').val('');
  $('#editAgentSelectBox').text('Add Agents');
  $('#editAgentList input.edit-agent-check').prop('checked', false);
  
  // Clear edit agent list for fresh load
  $('#editAgentList').empty();
}

/* Load agents for edit dropdown with queue info - WITH CALLBACK */
function loadEditAgentDropdown(callback) {
    console.log('📥 Loading edit agents (fresh)...');
    
    $.post("helpdesk/web_helpdesk_function.php",
    { action:'get_agent_list',
        _t: Date.now()  // cache buster
    },
    function(res){
        console.log('📥 Edit agents received:', res.length);
        
        let html = '';
        
        $.each(res, function(i, a){
            // Determine workload level
            let load = parseInt(a.assigned || 0);
            let workloadClass = 'low';
            let workloadText = 'Light';
            
            if(load >= 6 && load <= 15) {
                workloadClass = 'medium';
                workloadText = 'Moderate';
            } else if(load >= 16) {
                workloadClass = 'high';
                workloadText = 'Heavy';
            }
            
            // Parse queue details
            let queueHTML = '';
            
            if(a.queue_details && a.queue_details !== 'none') {
                let queues = a.queue_details.split('||');
                let uniqueQueues = new Set();
                
                queues.forEach(q => {
                    if(!q) return;
                    
                    let [queueName, deptOrStatus] = q.split('|');
                    
                    if(uniqueQueues.has(queueName)) return;
                    uniqueQueues.add(queueName);
                    
                    if(deptOrStatus === 'unmapped') {
                        queueHTML += `<span class="queue-tag queue-unmapped">
                            <i class="fa fa-exclamation-triangle"></i>${queueName} (Not mapped)
                        </span>`;
                    } else {
                        queueHTML += `<span class="queue-tag queue-mapped">
                            <i class="fa fa-layer-group"></i>${queueName} (${deptOrStatus})
                        </span>`;
                    }
                });
            }
            
            if(!queueHTML) {
                queueHTML = '<span class="queue-tag no-queue"><i class="fa fa-user-times"></i>Not in any queue</span>';
            }
            
            html += `
                <div class="agent-row">
                    <input 
                        type="checkbox"
                        class="edit-agent-check"
                        value="${a.id}"
                    >
                    <div class="agent-info">
                        <div class="agent-name">${a.name}</div>
                        <div class="agent-meta">
                            <div class="agent-workload">
                                <span class="workload-dot ${workloadClass}"></span>
                                <span class="workload-text">${workloadText} Load: ${load} tickets</span>
                            </div>
                            <div class="agent-queues">
                                ${queueHTML}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        
        $('#editAgentList').html(html);
        console.log('✅ Edit agents rendered:', $('#editAgentList .agent-row').length);
        
        // Call callback if provided
        if(typeof callback === 'function') {
            callback();
        }
        
    }, 'json')
    .fail(function(){
        console.error('❌ Failed to load edit agents');
        $('#editAgentList').html('<div style="padding:20px;text-align:center;color:#f44336;">Failed to load agents</div>');
    });
}

/* Edit agent search */
$(document).on('keyup', '#editAgentSearch', function(){
  const v = $(this).val().toLowerCase();
  $('#editAgentList .agent-row').filter(function(){
    $(this).toggle($(this).text().toLowerCase().indexOf(v) > -1);
  });
});

/* Collect selected agents for edit */
$(document).on('change', '.edit-agent-check', function() {
  const ids = [];
  $('#editAgentList .edit-agent-check:checked').each(function() {
    ids.push($(this).val());
  });
  $('#edit_queue_agents').val(ids.join(','));
  
  if (ids.length > 0) {
    $('#editAgentSelectBox').text(ids.length + " agent(s) to add");
  } else {
    $('#editAgentSelectBox').text("Add Agents");
  }
});

/* Remove agent from queue */
window.removeAgentFromQueue = function(queueId, agentId) {
  if (!confirm('Remove this agent from the queue?')) return;
  
  $.post('helpdesk/web_helpdesk_function.php', {
    action: 'remove_agent_from_queue',
    queue_id: queueId,
    agent_id: agentId
  }, function(res) {
    if (res.status === 'success') {
      openEditQueue(queueId); // Reload
      loadAgentsMulti();  // refresh agents list
    } else {
      alert(res.message || 'Failed to remove agent');
    }
  }, 'json');
};

/* Save queue changes */
$(document).off('click', '#saveQueueBtn');
$(document).on('click', '#saveQueueBtn', function() {
  const queueId = $('#edit_queue_id').val();
  const queueName = $('#edit_queue_name').val().trim();
  const newAgents = $('#edit_queue_agents').val();
  
  if (!queueName) {
    alert('Queue name required');
    return;
  }
  
  const btn = $(this);
  btn.prop('disabled', true).text('Saving...');
  
  $.ajax({
    url: 'helpdesk/web_helpdesk_function.php',
    type: 'POST',
    dataType: 'json',
    data: {
      action: 'update_queue',
      queue_id: queueId,
      queue_name: queueName,
      new_agents: newAgents
    },
    success: function(res) {
      if (res.status === 'success') {
        alert('Queue updated successfully');
        $('#edit-queue-overlay').hide();
        $('#searchQueue').val('');     // clear filter
        loadQueueCards();              // refresh cards
        loadAllQueues();               // refresh mapping dropdown
        loadAgentsMulti();  // refresh agent list
      } else {
        alert(res.msg || 'Failed to update queue');
      }
    },
    complete: function() {
      btn.prop('disabled', false).html('<i class="fa fa-save"></i> Save Changes');
    }
  });
});

/* Close edit modal */
$(document).on('click', '#closeEditModal, #cancelEditBtn', function() {
  $('#edit-queue-overlay').hide();
  loadAgentsMulti();  // refresh agents list
});

/* Confirm delete queue */
window.confirmDeleteQueue = function(queueId, queueName) {
  if (!confirm(`Delete queue "${queueName}"?\n\nThis will remove all agent assignments. Tickets assigned to this queue will become unassigned.`)) {
    return;
  }
  
  $.ajax({
    url: 'helpdesk/web_helpdesk_function.php',
    type: 'POST',
    dataType: 'json',
    data: {
      action: 'delete_queue',
      queue_id: queueId
    },
    success: function(res) {
      if (res.status === 'success') {
        alert('Queue deleted successfully');
        loadQueueCards();
        loadAllQueues();
      } else {
        alert(res.msg || 'Failed to delete queue');
      }
    }
  });
};

/* Delete from edit modal */
$(document).off('click', '#deleteQueueBtn');
$(document).on('click', '#deleteQueueBtn', function() {
  const queueId = $('#edit_queue_id').val();
  const queueName = $('#edit_queue_name').val();
  confirmDeleteQueue(queueId, queueName);
  $('#edit-queue-overlay').hide();
});


$(document).off('click.remark').on('click.remark', '.view-remark', function(){
  var ticket = $(this).data('ticket') || '';
  var remark = $(this).data('remark') || '';

  $('#remark-ticket').text(ticket ? ('Ticket: ' + ticket) : '');
  $('#remark-text').text(remark);

  $('#remark-modal').css('display','block');
});

// Icon click → show popup
$(document).off('click.remark').on('click.remark', '#customer_data .remark-icon', function(){
  var remark = $(this).data('remark') || '';
  $('#remarkPopupText').text(remark);
  $('#remarkPopup').show();
});

// Close button
$(document).off('click.closeRemark').on('click.closeRemark', '#closeRemarkPopup', function(){
  $('#remarkPopup').hide();
});

// Outside click
$(document).off('click.bgRemark').on('click.bgRemark', '#remarkPopup', function(e){
  if(e.target === this) $('#remarkPopup').hide();
});

// ESC key
$(document).off('keydown.remark').on('keydown.remark', function(e){
  if(e.key === 'Escape' && $('#remarkPopup').is(':visible')){
    $('#remarkPopup').hide();
  }
});
ś
