<?php require_once __DIR__ . '/../config.php'; require_admin(); ?>
<!doctype html>
<html lang="uz">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Plan konstruktor (Dinamik)</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.form-switch .form-check-input{ width:3em;height:1.5em;background:#e9ecef;border-radius:1em;border:0;position:relative;transition:.2s }
.form-switch .form-check-input::before{ content:"";position:absolute;top:.15em;left:.2em;width:1.2em;height:1.2em;background:#fff;border-radius:50%;box-shadow:0 1px 3px rgba(0,0,0,.2);transition:left .2s }
.form-switch .form-check-input:checked{ background:#2ecc71 }
.form-switch .form-check-input:checked::before{ left:1.6em }
.badge-soft{ background:#f1f5ff;color:#0d6efd }
.table-sticky thead th{ position:sticky; top:0; background:#fff; z-index:2 }
</style>
</head>
<body class="bg-light">

<nav class="navbar navbar-expand-lg navbar-dark" style="background:#0d6efd;">
  <div class="container">
    <a class="navbar-brand fw-bold" href="./dashboard.php">Oylik Hisob (Admin)</a>
    <ul class="navbar-nav ms-auto">
      <li class="nav-item"><a class="nav-link " href="./dashboard.php">Dashboard</a></li>
      <li class="nav-item"><a class="nav-link" href="./operators.php">Operatorlar</a></li>
      <li class="nav-item"><a class="nav-link" href="./users.php">Foydalanuvchi (Operator)</a></li>
      <li class="nav-item"><a class="nav-link active" href="./plans.php">Plan yaratish</a></li>
      <li class="nav-item"><a class="nav-link" href="./admin_review.php">Tekshirish</a></li>
      <li class="nav-item"><a class="nav-link" href="./operator_contracts.php">Shartnoma tayyorlash</a></li>
      <li class="nav-item"><a class="nav-link" href="./attendance_calc.php">Keldi / Ketdi</a></li>
      <li class="nav-item"><a class="nav-link" href="./logout.php">Chiqish</a></li>
    </ul>
  </div>
</nav>

<div class="container my-3">
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="row g-2 align-items-end">
        <div class="col-sm-3"><label class="form-label">Oy</label><input type="month" id="fYm" class="form-control" value="<?php echo date('Y-m'); ?>"></div>
        <div class="col-sm-6"><label class="form-label">Qidirish</label><input id="fQ" class="form-control" placeholder="plan nomi / tavsifi"></div>
        <div class="col-sm-3 text-end"><button class="btn btn-primary" id="btnSearch">Qidirish</button> <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#planModal" id="btnCreate">Yangi plan</button></div>
      </div>
    </div>
  </div>

  <div class="card shadow-sm">
    <div class="card-body table-responsive">
      <table class="table table-sm table-hover align-middle table-sticky" id="tblPlans">
        <thead class="table-light"><tr><th style="width:90px">Oy</th><th>Plan nomi</th><th>Tavsif</th><th style="width:260px">Amallar</th></tr></thead>
        <tbody></tbody>
      </table>
      <nav class="mt-2"><ul class="pagination" id="pager"></ul></nav>
    </div>
  </div>
</div>

<!-- Plan Modal -->
<div class="modal fade" id="planModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-primary text-white"><h5 class="modal-title">Plan</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <input type="hidden" id="pId">
    <div class="mb-2"><label class="form-label">Oy</label><input type="month" id="pYm" class="form-control" value="<?php echo date('Y-m'); ?>"></div>
    <div class="mb-2"><label class="form-label">Nomi</label><input id="pName" class="form-control"></div>
    <div class="mb-2"><label class="form-label">Tavsif</label><textarea id="pDesc" class="form-control"></textarea></div>
  </div>
  <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Bekor</button><button class="btn btn-primary" id="pSave">Saqlash</button></div>
</div></div></div>

<!-- Items Modal -->
<div class="modal fade" id="itemsModal" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header bg-success text-white"><h5 class="modal-title">Punktlar</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div><span class="badge bg-light text-dark" id="imPlanName"></span></div>
        <button class="btn btn-success btn-sm" id="addItemBtn">+ Punkt</button>
      </div>
      <div class="table-responsive">
        <table class="table table-sm align-middle" id="tblItems">
          <thead class="table-light">
            <tr>
              <th style="width:50px">#</th><th>Sarlavha</th><th>Reja</th>
              <th>Mukofot</th><th>Hisoblash usuli</th><th>Min %</th><th>100%+</th>
              <th>Dalil yuborish turlari</th><th>Majburiyatlar</th><th style="width:280px">Amallar</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-outline-primary" id="saveOrder">Tartibni saqlash</button>
      <button class="btn btn-secondary" data-bs-dismiss="modal">Yopish</button>
    </div>
  </div></div>
</div>

<!-- Item Edit Modal (to'liq dinamik) -->
<div class="modal fade" id="itemModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-info text-white"><h5 class="modal-title">Punkt</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <input type="hidden" id="iPlanId"><input type="hidden" id="iId">
    <div class="mb-2"><label class="form-label">Sarlavha</label><input id="iTitle" class="form-control" placeholder="mas: Telegram"></div>
    <div class="mb-2"><label class="form-label">Tavsif</label><textarea id="iDesc" class="form-control"></textarea></div>
    <div class="mb-2"><label class="form-label">Reja (son)</label><input id="iTarget" class="form-control" type="number" min="0" value="0"></div>

    <div class="row g-2">
      <div class="col-md-4"><label class="form-label">Mukofot (so'm)</label><input id="iReward" class="form-control" type="number" min="0" value="0"></div>
      <div class="col-md-4"><label class="form-label">Hisoblash usuli</label>
        <select id="iMode" class="form-select">
          <option value="proportional" selected>Proportional</option>
          <option value="threshold">Threshold (to‘liq/0)</option>
        </select>
      </div>
      <div class="col-md-4"><label class="form-label">Minimum foiz (%)</label><input id="iMinPct" class="form-control" type="number" min="0" max="100" value="0"></div>
    </div>

    <div class="form-check form-switch mt-2">
      <input class="form-check-input" type="checkbox" id="iAllowOver" checked>
      <label class="form-check-label" for="iAllowOver">100%+ ga ruxsat</label>
    </div>

    <label class="form-label mt-3">Dalil turlari</label>
    <div class="row row-cols-2 g-2">
      <div class="col"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" id="ev_text"><label class="form-check-label" for="ev_text">Matn</label></div></div>
      <div class="col"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" id="ev_username"><label class="form-check-label" for="ev_username">Username</label></div></div>
      <div class="col"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" id="ev_image"><label class="form-check-label" for="ev_image">Rasm</label></div></div>
      <div class="col"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" id="ev_audio"><label class="form-check-label" for="ev_audio">Audio</label></div></div>
      <div class="col"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" id="ev_video"><label class="form-check-label" for="ev_video">Video</label></div></div>
    </div>

    <div class="form-check form-switch mt-3">
      <input class="form-check-input" type="checkbox" id="iRequired" checked>
      <label class="form-check-label" for="iRequired">Majburiy</label>
    </div>
  </div>
  <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Bekor</button><button class="btn btn-primary" id="iSave">Saqlash</button></div>
</div></div></div>

<!-- Assign Modal (YANGI) -->
<div class="modal fade" id="assignModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header bg-warning text-dark">
      <h5 class="modal-title">Planga operatorlarni biriktirish</h5>
      <button class="btn-close" data-bs-dismiss="modal"></button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="asPlanId">
      <div class="row g-2 align-items-center mb-2">
        <div class="col-md-6">
          <div class="input-group">
            <span class="input-group-text">Qidirish</span>
            <input type="text" id="asSearch" class="form-control" placeholder="Ism, login, telefon...">
          </div>
        </div>
        <div class="col-md-6 text-end">
          <div class="form-check d-inline-flex align-items-center">
            <input class="form-check-input me-2" type="checkbox" id="asSelectAll">
            <label class="form-check-label" for="asSelectAll">Hammasini belgilash (shu sahifa)</label>
          </div>
        </div>
      </div>

      <div class="table-responsive border rounded">
        <table class="table table-sm align-middle mb-0" id="tblAssign">
          <thead class="table-light">
            <tr>
              <th style="width:48px">#</th>
              <th>Operator</th>
              <th>Login / Qo‘shimcha</th>
              <th style="width:80px" class="text-center">Biriktir</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>

      <nav class="mt-2"><ul class="pagination pagination-sm mb-0" id="asPager"></ul></nav>
    </div>
    <div class="modal-footer">
      <span class="me-auto small text-muted" id="asSummary"></span>
      <button class="btn btn-secondary" data-bs-dismiss="modal">Yopish</button>
      <button class="btn btn-primary" id="asSave">Saqlash</button>
    </div>
  </div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
let page=1, limit=20, total=0;

function esc(s){ return (s||'').replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;'}[m])); }
function unesc(s){ const t=document.createElement('textarea'); t.innerHTML=s||''; return t.value; }

async function j(url,opts){
  try{
    const r=await fetch(url,{credentials:'same-origin', ...opts});
    const txt=await r.text();
    if(!r.ok){ throw new Error(`HTTP ${r.status} ${r.statusText}\n${txt.slice(0,500)}`); }
    try{ return JSON.parse(txt); }catch(e){ throw new Error('JSON xato. Server javobi:\n'+txt.slice(0,500)); }
  }catch(err){
    console.error('[API error]', url, err);
    alert('So‘rov bajarilmadi:\n'+err.message);
    throw err;
  }
}

async function loadPlans(p=1){
  page=p;
  const ym=document.getElementById('fYm').value, q=document.getElementById('fQ').value;
  const d=await j('../api/plans.php?action=list_plans&ym='+encodeURIComponent(ym)+'&q='+encodeURIComponent(q)+'&page='+page+'&limit='+limit);
  const tb=document.querySelector('#tblPlans tbody'); tb.innerHTML='';
  (d.rows||[]).forEach(pl=>{
    const tr=document.createElement('tr');
    tr.innerHTML=`
      <td><span class="badge badge-soft">${pl.ym}</span></td>
      <td class="fw-semibold">${esc(pl.name)}</td>
      <td class="text-muted">${esc(pl.description||'')}</td>
      <td>
        <button class="btn btn-sm btn-outline-success me-1" data-action="items" data-id="${pl.id}" data-name="${esc(pl.name)}">Punktlar qo'shish</button>
        <button class="btn btn-sm btn-outline-warning me-1" data-action="assign" data-id="${pl.id}">Hodim biriktirish</button>
        <button class="btn btn-sm btn-outline-primary me-1" data-action="edit" data-id="${pl.id}" data-ym="${pl.ym}" data-name="${esc(pl.name)}" data-desc="${esc(pl.description||'')}">Tahrirlash</button>
        <button class="btn btn-sm btn-outline-danger" data-action="del" data-id="${pl.id}">O'chirish</button>
      </td>`;
    tb.appendChild(tr);
  });
  total=d.total||0;
  const pages=Math.max(1, Math.ceil(total/limit));
  const pg=document.getElementById('pager'); pg.innerHTML='';
  for(let i=1;i<=pages;i++){
    const li=document.createElement('li');
    li.className='page-item'+(i===page?' active':'');
    li.innerHTML=`<a class="page-link" href="#">${i}</a>`;
    li.addEventListener('click',e=>{e.preventDefault(); loadPlans(i);});
    pg.appendChild(li);
  }
}

document.getElementById('btnSearch').addEventListener('click',()=>loadPlans(1));
document.getElementById('btnCreate').addEventListener('click',()=>{
  pId.value=''; pYm.value=fYm.value; pName.value=''; pDesc.value='';
});
document.getElementById('pSave').addEventListener('click', async ()=>{
  const id=pId.value.trim();
  const body={ ym:pYm.value, name:pName.value, description:pDesc.value };
  if(!body.ym||!body.name){ alert('Oy va nom shart'); return; }
  if(id){
    await j('../api/plans.php?action=update',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...body,id:parseInt(id,10)})});
  }else{
    await j('../api/plans.php?action=create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
  }
  bootstrap.Modal.getOrCreateInstance(document.getElementById('planModal')).hide();
  loadPlans(page);
});

document.getElementById('tblPlans').addEventListener('click', async (e)=>{
  const b=e.target.closest('button'); if(!b) return;
  const id=parseInt(b.dataset.id,10); const act=b.dataset.action;
  if(act==='edit'){
    pId.value=id; pYm.value=b.dataset.ym;
    pName.value=unesc(b.dataset.name);
    pDesc.value=unesc(b.dataset.desc||'');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('planModal')).show();
  }else if(act==='del'){
    if(confirm('O‘chirsinmi?')){
      await j('../api/plans.php?action=delete',{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});
      loadPlans(page);
    }
  }else if(act==='items'){
    openItems(id, unesc(b.dataset.name));
  }else if(act==='assign'){
    openAssign(id);
  }
});

/* ITEMS */
async function openItems(plan_id, plan_name){
  document.getElementById('imPlanName').textContent=`#${plan_id} — ${plan_name}`;
  document.getElementById('iPlanId').value=plan_id;
  const d=await j('../api/plans.php?action=list_items&plan_id='+plan_id);
  const tb=document.querySelector('#tblItems tbody'); tb.innerHTML='';
  (d.items||[]).forEach((it,idx)=>{
    const ev=(it.evidence_types||'').split(',').filter(Boolean).join(',');
    const req=it.required?'Ha':'Yo‘q';
    const allow=it.reward_allow_over?'Ha':'Yo‘q';
    const tr=document.createElement('tr');
    tr.dataset.id=it.id;
    tr.innerHTML=`
      <td>${idx+1}</td>
      <td class="fw-semibold">${esc(it.title)}</td>
      <td>${it.target_int||0}</td>
      <td>${Number(it.reward_amount||0).toLocaleString('uz-UZ')}</td>
      <td>${esc(it.reward_calc||'proportional')}</td>
      <td>${(parseFloat(it.reward_min_pct||0)*100).toFixed(0)}%</td>
      <td>${allow}</td>
      <td><span class="badge text-bg-light">${ev||'-'}</span></td>
      <td>${req}</td>
      <td>
        <button class="btn btn-sm btn-outline-secondary me-1" data-i="up">↑</button>
        <button class="btn btn-sm btn-outline-secondary me-2" data-i="down">↓</button>
        <button class="btn btn-sm btn-outline-primary me-1" data-i="edit"
          data-id="${it.id}" data-title="${esc(it.title)}" data-desc="${esc(it.description||'')}"
          data-target="${it.target_int||0}" data-ev="${esc(it.evidence_types||'')}" data-req="${it.required?1:0}"
          data-reward="${it.reward_amount||0}" data-calc="${it.reward_calc||'proportional'}"
          data-min="${parseFloat(it.reward_min_pct||0)}" data-allow="${it.reward_allow_over?1:0}">Edit</button>
        <button class="btn btn-sm btn-outline-danger" data-i="del" data-id="${it.id}">Del</button>
      </td>`;
    tb.appendChild(tr);
  });
  bootstrap.Modal.getOrCreateInstance(document.getElementById('itemsModal')).show();
}

document.getElementById('addItemBtn').addEventListener('click', ()=>{
  iId.value=''; iTitle.value=''; iDesc.value=''; iTarget.value='0'; iReward.value='0'; iMode.value='proportional'; iMinPct.value='0'; iAllowOver.checked=true;
  ['ev_text','ev_username','ev_image','ev_audio','ev_video'].forEach(id=>document.getElementById(id).checked=false);
  iRequired.checked=true; bootstrap.Modal.getOrCreateInstance(document.getElementById('itemModal')).show();
});

document.getElementById('iSave').addEventListener('click', async ()=>{
  const plan_id=parseInt(iPlanId.value,10); const id=iId.value.trim();
  const ev=[]; if(ev_text.checked)ev.push('text'); if(ev_username.checked)ev.push('username'); if(ev_image.checked)ev.push('image'); if(ev_audio.checked)ev.push('audio'); if(ev_video.checked)ev.push('video');
  const body={
    plan_id,
    title:iTitle.value, description:iDesc.value,
    target_int:parseInt(iTarget.value||'0',10),
    evidence_types: ev.join(','), // string
    required:iRequired.checked?1:0,
    reward_amount:parseInt(iReward.value||'0',10),
    reward_calc:iMode.value,
    reward_min_pct: Math.max(0,Math.min(100, parseFloat(iMinPct.value||'0')))/100.0,
    reward_allow_over: iAllowOver.checked?1:0
  };
  if(!body.title){ alert('Sarlavha shart'); return; }

  if(id){
    await j('../api/plans.php?action=update_item',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...body,id:parseInt(id,10)})});
  }else{
    await j('../api/plans.php?action=add_item',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
  }
  bootstrap.Modal.getOrCreateInstance(document.getElementById('itemModal')).hide();

  const planLabel=document.getElementById('imPlanName').textContent.replace(/^#\d+\s—\s/,'');
  openItems(plan_id, planLabel);
});

document.getElementById('tblItems').addEventListener('click', async (e)=>{
  const b=e.target.closest('button'); if(!b) return;
  const plan_id=parseInt(iPlanId.value,10);
  if(b.dataset.i==='up' || b.dataset.i==='down'){
    const tr=b.closest('tr'); const tb=tr.parentElement;
    if(b.dataset.i==='up' && tr.previousElementSibling) tb.insertBefore(tr, tr.previousElementSibling);
    if(b.dataset.i==='down' && tr.nextElementSibling) tb.insertBefore(tr.nextElementSibling, tr);
  }else if(b.dataset.i==='edit'){
    iId.value=b.dataset.id;
    iTitle.value=unesc(b.dataset.title);
    iDesc.value=unesc(b.dataset.desc||'');
    iTarget.value=b.dataset.target||0;
    iReward.value=b.dataset.reward||0;
    iMode.value=b.dataset.calc||'proportional';
    iMinPct.value=((parseFloat(b.dataset.min||0)*100).toFixed(0));
    iAllowOver.checked=(parseInt(b.dataset.allow||'1',10)===1);
    ['ev_text','ev_username','ev_image','ev_audio','ev_video'].forEach(id=>document.getElementById(id).checked=false);
    unesc(b.dataset.ev||'').split(',').filter(Boolean).forEach(k=>{
      const el = ({text:ev_text,username:ev_username,image:ev_image,audio:ev_audio,video:ev_video}[k]);
      if (el) el.checked = true;
    });
    iRequired.checked=(parseInt(b.dataset.req||'1',10)===1);
    bootstrap.Modal.getOrCreateInstance(document.getElementById('itemModal')).show();
  }else if(b.dataset.i==='del'){
    if(confirm('Punktni o‘chirish?')){
      await j('../api/plans.php?action=delete_item',{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:parseInt(b.dataset.id,10)})});
      const planLabel=document.getElementById('imPlanName').textContent.replace(/^#\d+\s—\s/,'');
      openItems(plan_id, planLabel);
    }
  }
});

document.getElementById('saveOrder').addEventListener('click', async ()=>{
  const plan_id=parseInt(iPlanId.value,10);
  const ids=[...document.querySelectorAll('#tblItems tbody tr')].map(tr=>parseInt(tr.dataset.id,10));
  await j('../api/plans.php?action=reorder_items',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({plan_id, order:ids})});
  alert('Tartib saqlandi');
});

/* ===== ASSIGN UI (mustahkamlangan) ===== */
const assignState = {
  plan_id: 0,
  operators: [],         // [{id,name,username,phone,note}]
  assignedSet: new Set(),// tanlanganlar
  page: 1,
  limit: 10,
  query: ''
};

// Javobni normalize: [], {rows:[]}, {operators:[]}, {data:[]}, {list:[]}, va h.k.
function pickArray(payload){
  if (Array.isArray(payload)) return payload;
  if (!payload || typeof payload!=='object') return [];
  const keys = ['rows','operators','data','list','items','result'];
  for (const k of keys){
    if (Array.isArray(payload[k])) return payload[k];
  }
  // Ba’zi backendlarda {ok:true, data:{rows:[...]}} bo‘ladi
  if (payload.data && typeof payload.data==='object'){
    for (const k of keys){
      if (Array.isArray(payload.data[k])) return payload.data[k];
    }
  }
  return [];
}

// Operator obyektini normalize
function normalizeOperator(o){
  // mumkin bo'lgan id nomlari
  const id = Number(
    o.id ?? o.operator_id ?? o.user_id ?? o.staff_id ?? o.uid ?? 0
  );
  const name =
    (o.name ?? o.full_name ?? o.fio ?? o.title ?? o.display_name ?? '') + '';
  const username =
    (o.username ?? o.login ?? o.nick ?? o.nickname ?? o.user_name ?? '') + '';
  const phone =
    (o.phone ?? o.tel ?? o.phone_number ?? o.mobile ?? '') + '';
  const note =
    (o.note ?? o.comment ?? o.remark ?? '') + '';
  return { id, name, username, phone, note };
}

function filterOps(){
  const q = assignState.query.trim().toLowerCase();
  if(!q) return assignState.operators;
  return assignState.operators.filter(o=>{
    const s = `${o.name||''} ${o.username||''} ${o.phone||''} ${o.note||''}`.toLowerCase();
    return s.includes(q);
  });
}

function renderAssign(){
  const all = filterOps();
  const pages = Math.max(1, Math.ceil(all.length / assignState.limit));
  assignState.page = Math.min(assignState.page, pages);
  const start = (assignState.page - 1) * assignState.limit;
  const rows = all.slice(start, start + assignState.limit);

  const tb = document.querySelector('#tblAssign tbody');
  tb.innerHTML = '';

  if (rows.length === 0){
    // Bo‘sh holat
    const tr = document.createElement('tr');
    tr.innerHTML = `<td colspan="4" class="text-center text-muted py-3">Hech narsa topilmadi</td>`;
    tb.appendChild(tr);
  } else {
    rows.forEach((op, idx)=>{
      const tr = document.createElement('tr');
      const isChecked = assignState.assignedSet.has(Number(op.id));
      tr.innerHTML = `
        <td>${start+idx+1}</td>
        <td class="fw-semibold">${esc(op.name||'-')}</td>
        <td class="text-muted"><small>${esc(op.username||'-')}${op.phone?(' · '+esc(op.phone)) : ''}</small></td>
        <td class="text-center">
          <input class="form-check-input as-check" type="checkbox" data-id="${op.id}" ${isChecked?'checked':''}>
        </td>`;
      tb.appendChild(tr);
    });
  }

  // Pager
  const pg = document.getElementById('asPager'); pg.innerHTML='';
  for(let i=1;i<=pages;i++){
    const li = document.createElement('li');
    li.className = 'page-item'+(i===assignState.page?' active':'');
    li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
    li.addEventListener('click', e=>{e.preventDefault(); assignState.page=i; renderAssign();});
    pg.appendChild(li);
  }

  // Select-all holati (faqat joriy sahifa)
  const pageAllChecked = rows.length>0 && rows.every(op=>assignState.assignedSet.has(Number(op.id)));
  const selAll = document.getElementById('asSelectAll');
  if (selAll) selAll.checked = pageAllChecked;

  // Summary
  const totalChecked = assignState.operators.reduce((acc,op)=> acc + (assignState.assignedSet.has(Number(op.id))?1:0), 0);
  const sum = document.getElementById('asSummary');
  if (sum) sum.textContent = `Jami: ${assignState.operators.length} | Tanlangan: ${totalChecked}`;
}

async function openAssign(plan_id){
  assignState.plan_id = plan_id;
  document.getElementById('asPlanId').value = plan_id;
  assignState.page = 1;
  assignState.limit = 10;
  assignState.query = '';
  const searchEl = document.getElementById('asSearch');
  if(searchEl) searchEl.value = '';

  // 1) Operatorlar ro‘yxati
  const raw = await j('../api/operators.php'); // turli formatlarda bo‘lishi mumkin
  const arr = pickArray(raw);
  assignState.operators = arr.map(normalizeOperator).filter(op=>op.id>0);

  // 2) Oldindan biriktirilganlar
  const as = await j('../api/plans.php?action=list_assignments&plan_id='+plan_id);
  assignState.assignedSet = new Set((as.assigned||[]).map(Number));

  // Modalni ko‘rsatish va chizish
  bootstrap.Modal.getOrCreateInstance(document.getElementById('assignModal')).show();
  renderAssign();

  // Diagnostika (konsolda ko‘rib olasiz)
  console.info('[assign] raw operators:', raw);
  console.info('[assign] normalized count:', assignState.operators.length);
}

/* Qidirish (engil debounce) */
(function(){
  let t=null;
  const el = document.getElementById('asSearch');
  if (!el) return;
  el.addEventListener('input', (e)=>{
    const v = e.target.value;
    clearTimeout(t);
    t = setTimeout(()=>{
      assignState.query = v;
      assignState.page = 1;
      renderAssign();
    }, 200);
  });
})();

/* Jadvaldagi checkboxlarni kuzatish */
document.getElementById('tblAssign').addEventListener('change', (e)=>{
  const cb = e.target.closest('.as-check'); if(!cb) return;
  const id = Number(cb.dataset.id);
  if(cb.checked) assignState.assignedSet.add(id);
  else assignState.assignedSet.delete(id);
  renderAssign();
});

/* Sahifadagi hammasini belgilash (joriy sahifa) */
document.getElementById('asSelectAll').addEventListener('change', (e)=>{
  const all = filterOps();
  const start = (assignState.page-1)*assignState.limit;
  const rows = all.slice(start, start+assignState.limit);
  if(e.target.checked){
    rows.forEach(op=>assignState.assignedSet.add(Number(op.id)));
  }else{
    rows.forEach(op=>assignState.assignedSet.delete(Number(op.id)));
  }
  renderAssign();
});

/* Saqlash: assign_bulk / unassign_bulk (diff yuborish) */
document.getElementById('asSave').addEventListener('click', async ()=>{
  const plan_id = assignState.plan_id;

  const as = await j('../api/plans.php?action=list_assignments&plan_id='+plan_id);
  const had = new Set((as.assigned||[]).map(Number));
  const now = assignState.assignedSet;

  const toAssign = [];
  const toUnassign = [];
  now.forEach(id=>{ if(!had.has(id)) toAssign.push(id); });
  had.forEach(id=>{ if(!now.has(id)) toUnassign.push(id); });

  if(toAssign.length===0 && toUnassign.length===0){
    alert('O‘zgartirish yo‘q.');
    return;
  }

  if(toAssign.length>0){
    await j('../api/plans.php?action=assign_bulk', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ plan_id, operator_ids: toAssign })
    });
  }
  if(toUnassign.length>0){
    await j('../api/plans.php?action=unassign_bulk', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ plan_id, operator_ids: toUnassign })
    });
  }

  alert('Biriktirishlar saqlandi.');
  bootstrap.Modal.getOrCreateInstance(document.getElementById('assignModal')).hide();
});


/* init */
document.addEventListener('DOMContentLoaded', ()=>loadPlans(1));
</script>

</body>
</html>
