/////////////////////////////// Group assing ///////////////////////////////

(function () {
    'use strict';
  
    let assigneeList = [];
    let dropdownVisible = false;
  
    // ─── Styles ───────────────────────────────────────────────────────────────
    const style = document.createElement('style');
    style.textContent = `
      #whmcs-bulk-bar {
        display: flex; align-items: center; gap: 10px;
        padding: 8px 14px; background: #1e293b; border-radius: 8px;
        margin-bottom: 10px; font-family: Tahoma, Arial, sans-serif;
        direction: rtl; box-shadow: 0 2px 8px rgba(0,0,0,0.25);
        position: relative;
      }
      #whmcs-bulk-bar .bulk-label { color: #94a3b8; font-size: 13px; white-space: nowrap; }
      #whmcs-bulk-bar .bulk-count {
        background: #3b82f6; color: #fff; border-radius: 20px;
        padding: 2px 10px; font-size: 13px; font-weight: bold;
        min-width: 28px; text-align: center;
      }
      #whmcs-bulk-assign-btn {
        background: #3b82f6; color: #fff; border: none; border-radius: 6px;
        padding: 6px 16px; font-size: 13px; font-family: Tahoma, Arial, sans-serif;
        cursor: pointer; transition: background 0.2s; white-space: nowrap;
      }
      #whmcs-bulk-assign-btn:hover { background: #2563eb; }
      #whmcs-bulk-assign-btn:disabled { background: #475569; cursor: not-allowed; }
      #whmcs-bulk-assign-btn.loading { background: #475569; cursor: wait; }
  
      #whmcs-assign-dropdown {
        position: absolute; top: calc(100% + 6px); right: 14px;
        background: #1e293b; border: 1px solid #334155; border-radius: 10px;
        box-shadow: 0 8px 32px rgba(0,0,0,0.45); z-index: 9999;
        width: 280px; overflow: hidden; direction: rtl;
        font-family: Tahoma, Arial, sans-serif;
      }
      #whmcs-assign-dropdown .dd-header { padding: 10px 14px 6px; border-bottom: 1px solid #334155; }
      #whmcs-assign-dropdown .dd-search {
        width: 100%; box-sizing: border-box; background: #0f172a;
        border: 1px solid #475569; border-radius: 6px; color: #e2e8f0;
        font-size: 13px; font-family: Tahoma, Arial, sans-serif;
        padding: 6px 10px; outline: none; direction: rtl;
      }
      #whmcs-assign-dropdown .dd-search:focus { border-color: #3b82f6; }
      #whmcs-assign-dropdown .dd-search::placeholder { color: #64748b; }
      #whmcs-assign-dropdown .dd-list { max-height: 240px; overflow-y: auto; padding: 6px 0; }
      #whmcs-assign-dropdown .dd-list::-webkit-scrollbar { width: 5px; }
      #whmcs-assign-dropdown .dd-list::-webkit-scrollbar-thumb { background: #475569; border-radius: 3px; }
      #whmcs-assign-dropdown .dd-item {
        padding: 8px 16px; color: #cbd5e1; font-size: 13px;
        cursor: pointer; transition: background 0.15s;
      }
      #whmcs-assign-dropdown .dd-item:hover { background: #334155; color: #fff; }
      #whmcs-assign-dropdown .dd-empty { padding: 14px 16px; color: #64748b; font-size: 13px; text-align: center; }
  
      #whmcs-progress-overlay {
        position: fixed; inset: 0; background: rgba(0,0,0,0.55);
        z-index: 99999; display: flex; align-items: center;
        justify-content: center; font-family: Tahoma, Arial, sans-serif;
      }
      #whmcs-progress-box {
        background: #1e293b; border: 1px solid #334155; border-radius: 14px;
        padding: 28px 36px; min-width: 340px; text-align: center;
        box-shadow: 0 16px 48px rgba(0,0,0,0.6); direction: rtl;
      }
      #whmcs-progress-box h3 { color: #e2e8f0; margin: 0 0 16px; font-size: 15px; }
      #whmcs-progress-track {
        background: #0f172a; border-radius: 99px; height: 10px;
        overflow: hidden; margin-bottom: 10px;
      }
      #whmcs-progress-fill {
        height: 100%; background: linear-gradient(90deg, #3b82f6, #60a5fa);
        border-radius: 99px; transition: width 0.3s ease; width: 0%;
      }
      #whmcs-progress-text { color: #94a3b8; font-size: 13px; }
      #whmcs-progress-log {
        max-height: 110px; overflow-y: auto; margin-top: 10px;
        text-align: right; font-size: 12px; color: #64748b; line-height: 1.8;
      }
      #whmcs-progress-log .ok  { color: #4ade80; }
      #whmcs-progress-log .err { color: #f87171; }
      #whmcs-progress-done {
        margin-top: 16px; background: #3b82f6; color: #fff; border: none;
        border-radius: 6px; padding: 7px 22px; font-size: 13px;
        font-family: Tahoma, Arial, sans-serif; cursor: pointer; display: none;
      }
    `;
    document.head.appendChild(style);
  
    // ─── Parse ticket page HTML and extract all fields ────────────────────────
    // Field map based on actual DOM (id-based, not name-based):
    //   token          → input[name="token"]  (first one)
    //   currentflagto  → #currentflagto
    //   currentdeptid  → #currentdeptid
    //   currentpriority→ #currentpriority
    //   currentUserId  → #currentUserId
    //   currentStatus  → #currentStatus
    //   currentSubject → #currentSubject
    //   currentCc      → #currentCc
    //   lastReplyId    → #lastReplyId
    //   flagto options → select#flagto
  
    function parseTicketPage(html) {
      const doc = new DOMParser().parseFromString(html, 'text/html');
  
      const val = (id) => {
        const el = doc.getElementById(id);
        return el ? el.value : '';
      };
  
      // Token: first hidden input with name="token"
      const tokenEl = doc.querySelector('input[name="token"]');
      const token = tokenEl ? tokenEl.value : '';
  
      // Assignee list from select#flagto (sidebar select, not the reply-form ones)
      const flagtoSel = doc.getElementById('flagto');
      const assignees = flagtoSel
        ? Array.from(flagtoSel.options)
            .filter(o => o.value !== '0' && o.value !== 'nochange' && o.value !== '')
            .map(o => ({ value: o.value, label: o.textContent.trim() }))
        : [];
  
      return {
        token,
        assignees,
        currentValue:        val('currentflagto'),
        currentDepartmentId: val('currentdeptid'),
        currentPriority:     val('currentpriority'),
        currentUserId:       val('currentUserId'),
        currentStatus:       val('currentStatus'),
        currentSubject:      val('currentSubject'),
        currentCc:           val('currentCc'),
        lastReplyId:         val('lastReplyId'),
      };
    }
  
    // ─── Fetch ticket page ────────────────────────────────────────────────────
  
    async function fetchTicketPage(ticketId) {
      const url = `${location.origin}/manager/supporttickets.php?action=view&id=${ticketId}`;
      const res = await fetch(url, {
        credentials: 'include',
        headers: { 'accept': 'text/html' },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return res.text();
    }
  
    // ─── Assign a single ticket ───────────────────────────────────────────────
  
    async function assignTicket(ticketId, assigneeValue) {
      const html = await fetchTicketPage(ticketId);
      const f = parseTicketPage(html);
  
      console.log(`[BulkAssign] ticket ${ticketId} fields:`, f);
  
      if (!f.token) throw new Error('token not found in ticket page');
  
      const base = location.origin;
      const headers = {
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-requested-with': 'XMLHttpRequest',
      };
  
      // POST 1 – update flagto
      const body1 = new URLSearchParams({
        action:              'viewticket',
        id:                  ticketId,
        updateticket:        'flagto',
        value:               assigneeValue,
        currentValue:        f.currentValue,
        lastReplyId:         f.lastReplyId,
        currentSubject:      f.currentSubject,
        currentCc:           f.currentCc,
        currentUserId:       f.currentUserId,
        currentDepartmentId: f.currentDepartmentId,
        currentFlag:         '0',
        currentPriority:     f.currentPriority,
        currentStatus:       f.currentStatus,
        skip:                '0',
        token:               f.token,
      });
  
      const r1 = await fetch(`${base}/manager/supporttickets.php`, {
        method: 'POST', headers, body: body1.toString(), credentials: 'include',
      });
      const t1 = await r1.text();
      console.log(`[BulkAssign] flagto response (${ticketId}):`, t1);
  
      // POST 2 – change_assign_ticket
      const body2 = new URLSearchParams({
        action:   'change_assign_ticket',
        ticketId: ticketId,
        to:       assigneeValue,
      });
  
      const r2 = await fetch(`${base}/manager/addonmodules.php?module=is_support&page=Ticket`, {
        method: 'POST', headers, body: body2.toString(), credentials: 'include',
      });
      const t2 = await r2.text();
      console.log(`[BulkAssign] change_assign response (${ticketId}):`, t2);
  
      // Consider success if both requests returned 200
      if (!r1.ok) throw new Error(`flagto failed: HTTP ${r1.status}`);
      if (!r2.ok) throw new Error(`change_assign failed: HTTP ${r2.status}`);
    }
  
    // ─── UI ───────────────────────────────────────────────────────────────────
  
    function getFirstTicketId() {
      const cb = document.querySelector('#sortabletbl2 input.checkall');
      return cb ? cb.value : null;
    }
  
    function createBulkBar(table) {
      if (document.getElementById('whmcs-bulk-bar')) return;
  
      const bar = document.createElement('div');
      bar.id = 'whmcs-bulk-bar';
      bar.innerHTML = `
        <span class="bulk-label">اساین گروهی:</span>
        <span class="bulk-count" id="whmcs-selected-count">0</span>
        <span class="bulk-label">تیکت انتخاب‌شده</span>
        <button type="button" id="whmcs-bulk-assign-btn" disabled>اساین به کارشناس ▾</button>
      `;
      table.parentNode.insertBefore(bar, table);
  
      const dropdown = document.createElement('div');
      dropdown.id = 'whmcs-assign-dropdown';
      dropdown.style.display = 'none';
      dropdown.innerHTML = `
        <div class="dd-header">
          <input class="dd-search" id="whmcs-dd-search" type="text" placeholder="جستجوی کارشناس..." autocomplete="off">
        </div>
        <div class="dd-list" id="whmcs-dd-list"></div>
      `;
      bar.appendChild(dropdown);
  
      const btn = document.getElementById('whmcs-bulk-assign-btn');
  
      btn.addEventListener('click', async (e) => {
        e.preventDefault();
        e.stopPropagation();
        if (btn.disabled || btn.classList.contains('loading')) return;
  
        if (dropdownVisible) { hideDropdown(); return; }
  
        if (assigneeList.length === 0) {
          const ticketId = getFirstTicketId();
          if (!ticketId) { showDropdown(); return; }
  
          btn.classList.add('loading');
          btn.textContent = 'در حال بارگذاری...';
          try {
            const html = await fetchTicketPage(ticketId);
            const data = parseTicketPage(html);
            assigneeList = data.assignees;
            console.log('[BulkAssign] loaded assignees:', assigneeList);
          } catch (err) {
            console.error('[BulkAssign] Failed to load assignees:', err);
          }
          btn.classList.remove('loading');
          btn.textContent = 'اساین به کارشناس ▾';
        }
  
        showDropdown();
      });
  
      document.addEventListener('input', (e) => {
        if (e.target.id === 'whmcs-dd-search') renderDropdownItems(e.target.value);
      });
      document.addEventListener('click', (e) => {
        if (dropdownVisible && !dropdown.contains(e.target) && e.target !== btn)
          hideDropdown();
      });
  
      table.addEventListener('change', () => updateCount(table));
      const chkAll = table.querySelector('#checkall2');
      if (chkAll) chkAll.addEventListener('change', () => setTimeout(() => updateCount(table), 50));
    }
  
    function updateCount(table) {
      const n = table.querySelectorAll('input.checkall:checked').length;
      const c = document.getElementById('whmcs-selected-count');
      const b = document.getElementById('whmcs-bulk-assign-btn');
      if (c) c.textContent = n;
      if (b) b.disabled = n === 0;
    }
  
    function showDropdown() {
      const dd = document.getElementById('whmcs-assign-dropdown');
      if (!dd) return;
      dd.style.display = 'block';
      dropdownVisible = true;
      renderDropdownItems('');
      setTimeout(() => {
        const s = document.getElementById('whmcs-dd-search');
        if (s) { s.value = ''; s.focus(); }
      }, 50);
    }
  
    function hideDropdown() {
      const dd = document.getElementById('whmcs-assign-dropdown');
      if (dd) dd.style.display = 'none';
      dropdownVisible = false;
    }
  
    function renderDropdownItems(query) {
      const list = document.getElementById('whmcs-dd-list');
      if (!list) return;
      const q = query.trim().toLowerCase();
      const filtered = assigneeList.filter(a => a.label.toLowerCase().includes(q));
  
      if (filtered.length === 0) {
        list.innerHTML = `<div class="dd-empty">${
          assigneeList.length === 0 ? 'لیست کارشناسان یافت نشد.' : 'کارشناسی پیدا نشد.'
        }</div>`;
        return;
      }
  
      list.innerHTML = filtered.map(a =>
        `<div class="dd-item" data-value="${a.value}">${a.label}</div>`
      ).join('');
  
      list.querySelectorAll('.dd-item').forEach(item => {
        item.addEventListener('click', () => {
          hideDropdown();
          handleBulkAssign(item.dataset.value, item.textContent.trim());
        });
      });
    }
  
    // ─── Bulk assign ──────────────────────────────────────────────────────────
  
    async function handleBulkAssign(assigneeValue, assigneeName) {
      const table = document.getElementById('sortabletbl2');
      if (!table) return;
  
      const ticketIds = Array.from(table.querySelectorAll('input.checkall:checked'))
        .map(cb => cb.value).filter(Boolean);
      if (ticketIds.length === 0) return;
  
      showProgress(ticketIds.length, assigneeName);
  
      let done = 0;
      for (const id of ticketIds) {
        try {
          await assignTicket(id, assigneeValue);
          appendLog(`تیکت ${id} ✓`, 'ok');
        } catch (err) {
          console.error(`[BulkAssign] ticket ${id} failed:`, err);
          appendLog(`تیکت ${id} ✗ ${err.message}`, 'err');
        }
        done++;
        updateProgress(done, ticketIds.length);
        await new Promise(r => setTimeout(r, 400));
      }
  
      finishProgress(done);
    }
  
    // ─── Progress ─────────────────────────────────────────────────────────────
  
    function showProgress(total, assigneeName) {
      let ov = document.getElementById('whmcs-progress-overlay');
      if (!ov) { ov = document.createElement('div'); ov.id = 'whmcs-progress-overlay'; document.body.appendChild(ov); }
      ov.innerHTML = `
        <div id="whmcs-progress-box">
          <h3 id="whmcs-progress-title">در حال اساین به ${assigneeName}...</h3>
          <div id="whmcs-progress-track"><div id="whmcs-progress-fill"></div></div>
          <div id="whmcs-progress-text">0 از ${total}</div>
          <div id="whmcs-progress-log"></div>
          <button type="button" id="whmcs-progress-done">بستن و بارگذاری مجدد</button>
        </div>`;
      document.getElementById('whmcs-progress-done').addEventListener('click', () => { ov.remove(); location.reload(); });
    }
  
    function appendLog(msg, cls) {
      const log = document.getElementById('whmcs-progress-log');
      if (log) { const d = document.createElement('div'); d.className = cls || ''; d.textContent = msg; log.appendChild(d); log.scrollTop = log.scrollHeight; }
    }
  
    function updateProgress(done, total) {
      const f = document.getElementById('whmcs-progress-fill');
      const t = document.getElementById('whmcs-progress-text');
      if (f) f.style.width = `${Math.round((done / total) * 100)}%`;
      if (t) t.textContent = `${done} از ${total}`;
    }
  
    function finishProgress(done) {
      const title = document.getElementById('whmcs-progress-title');
      const btn   = document.getElementById('whmcs-progress-done');
      if (title) title.textContent = `✓ ${done} تیکت پردازش شد`;
      if (btn)   btn.style.display = 'inline-block';
    }
  
    // ─── Init ─────────────────────────────────────────────────────────────────
  
    function init() {
      const table = document.getElementById('sortabletbl2');
      if (table) createBulkBar(table);
    }
  
    init();
    new MutationObserver(() => {
      if (document.getElementById('sortabletbl2') && !document.getElementById('whmcs-bulk-bar')) init();
    }).observe(document.body, { childList: true, subtree: true });
  
  })();

/////////////////////////////// Staff Stats Panel (below bulk bar) ///////////////////////////////
(function () {
'use strict';

const STATS_URL = 'https://hub.iranserver.com/manager/addonmodules.php?module=is_support&action=Staff/showAdminsTicketsInfo&dept_id=1&level=all';
const CACHE_KEY = 'staffStatsCache';
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

let statsPanel = null;

// ─── Cache helpers ────────────────────────────────────────────────────────

function readCache() {
    try {
        const raw = localStorage.getItem(CACHE_KEY);
        if (!raw) return null;
        const obj = JSON.parse(raw);
        if (Date.now() - obj.timestamp > CACHE_TTL) return null;
        return obj.data;
    } catch { return null; }
}

function writeCache(data) {
    try {
        localStorage.setItem(CACHE_KEY, JSON.stringify({ timestamp: Date.now(), data }));
    } catch {}
}

// ─── Fetch staff stats ────────────────────────────────────────────────────

async function fetchStaffStats() {
    const cached = readCache();
    if (cached) return cached;

    const res = await fetch(STATS_URL, { credentials: 'include' });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const data = await res.json();
    writeCache(data);
    return data;
}

// ─── Render panel ─────────────────────────────────────────────────────────

function renderStatsPanel(data) {
    if (!statsPanel) return;

    // Filter: current_tickets > 1 OR answered_tickets > 1
    const active = Object.values(data).filter(
        s => s.current_tickets >= 1 || s.answered_tickets >= 1
    );

    if (active.length === 0) {
        statsPanel.innerHTML = '<span style="color:#64748b;font-size:12px;">کارشناس فعالی یافت نشد</span>';
        return;
    }

    // Sort by current_tickets desc, then answered_tickets desc
    active.sort((a, b) =>
        (b.current_tickets - a.current_tickets) || (b.answered_tickets - a.answered_tickets)
    );

    statsPanel.style.cssText = 'display:flex; flex-wrap:wrap; gap:2px; direction:rtl;';

    statsPanel.innerHTML = active.map(s => `
        <div style="
            width:140px; min-height:52px; box-sizing:border-box;
            display:flex; flex-direction:column; align-items:center; justify-content:center;
            padding:5px 6px; border-radius:7px;
            background:#0f172a; border:1px solid #1e3a5f;
            font-family:Tahoma,Arial,sans-serif; direction:rtl; text-align:center;
            gap:4px;
        ">
            <span style="color:#e2e8f0;font-size:11px;font-weight:bold;line-height:1.3;word-break:break-word;">${s.name}</span>
            <span style="color:#94a3b8;font-size:10px;line-height:1.4;">
                <b style="color:#60a5fa">${s.current_tickets}/${s.current_weight}</b>
                &nbsp;·&nbsp;
                <b style="color:#4ade80">${s.answered_tickets}/${s.answered_weight}</b>
            </span>
        </div>
    `).join('');
    
}

// ─── Inject panel below bulk bar ──────────────────────────────────────────

function injectPanel() {
    const bar = document.getElementById('whmcs-bulk-bar');
    if (!bar || document.getElementById('whmcs-staff-stats-panel')) return;

    const wrapper = document.createElement('div');
    wrapper.id = 'whmcs-staff-stats-panel';
    wrapper.style.cssText = `
        background: #1e293b; border-radius: 8px; padding: 8px 10px;
        margin-bottom: 10px; direction: rtl;
        font-family: Tahoma, Arial, sans-serif;
        box-shadow: 0 2px 8px rgba(0,0,0,0.25);
    `;

    const header = document.createElement('div');
    header.style.cssText = 'display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;';
    header.innerHTML = `
        <span style="color:#94a3b8;font-size:12px;">📊 کارشناسان فعال</span>
        <span id="whmcs-stats-timer" style="color:#475569;font-size:11px;"></span>
    `;

    statsPanel = document.createElement('div');

    wrapper.appendChild(header);
    wrapper.appendChild(statsPanel);
    bar.insertAdjacentElement('afterend', wrapper);

    loadAndRender();
}

// ─── Load + render + schedule refresh ────────────────────────────────────

async function loadAndRender() {
    if (!statsPanel) return;
    try {
        const data = await fetchStaffStats();
        renderStatsPanel(data);
        updateTimer();
    } catch (err) {
        if (statsPanel) statsPanel.innerHTML = `<span style="color:#f87171;font-size:12px;">خطا در دریافت اطلاعات</span>`;
        console.error('[StaffStats]', err);
    }
}

function updateTimer() {
    const timerEl = document.getElementById('whmcs-stats-timer');
    if (!timerEl) return;
    const cached = readCache();
    if (!cached) { timerEl.textContent = ''; return; }
    const remaining = Math.max(0, Math.ceil((CACHE_TTL - (Date.now() - JSON.parse(localStorage.getItem(CACHE_KEY)).timestamp)) / 1000));
    const mins = Math.floor(remaining / 60);
    const secs = remaining % 60;
    timerEl.textContent = `آپدیت: ${mins}:${secs.toString().padStart(2, '0')}`;
}

// Refresh every 5 min, update timer every second
setInterval(() => {
    localStorage.removeItem(CACHE_KEY); // force fresh fetch
    loadAndRender();
}, CACHE_TTL);

setInterval(updateTimer, 1000);

// ─── Init: wait for bulk bar to appear ───────────────────────────────────

function tryInit() {
    if (document.getElementById('whmcs-bulk-bar')) {
        injectPanel();
    }
}

// MutationObserver to catch when bulk bar is injected
new MutationObserver(() => {
    if (document.getElementById('whmcs-bulk-bar') && !document.getElementById('whmcs-staff-stats-panel')) {
        injectPanel();
    }
}).observe(document.body, { childList: true, subtree: true });

tryInit();

})();