<?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>Operator shartnomalari (Admin)</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.table-sticky thead th{position:sticky;top:0;background:#fff;z-index:2}
.badge-soft{background:#f1f5ff;color:#0d6efd}
.code-mono{font-family:ui-monospace,Menlo,Consolas,monospace}
.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-status{font-weight:600}
.badge-status.pending{background:#fff3cd;color:#664d03}
.badge-status.signed{background:#d1e7dd;color:#0f5132}
.preview-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:.5rem}
.preview-item{border:1px solid #e9ecef;border-radius:.5rem;padding:.5rem;background:#fff}
.preview-item small{display:block;color:#6c757d}
.stats-pill{background:#f8f9fa;border:1px solid #e9ecef;border-radius:999px;padding:.2rem .6rem;font-size:.85rem}
</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" 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 active" 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 id="alertBox"></div>

  <!-- CREATE PANEL -->
  <div class="card shadow-sm mb-3">
    <div class="card-header bg-light fw-semibold d-flex align-items-center justify-content-between">
      <span>Yangi shartnoma tayyorlash</span>
      <div class="d-flex gap-2 align-items-center">
        <span class="stats-pill" id="statItems">Punktlar: 0</span>
        <span class="stats-pill" id="statOps">Operatorlar: 0</span>
      </div>
    </div>
    <div class="card-body">
      <div class="row g-3 align-items-end">
        <div class="col-lg-2">
          <label class="form-label">Oy</label>
          <input type="month" id="cYm" class="form-control" value="<?php echo date('Y-m'); ?>">
        </div>
        <div class="col-lg-4">
          <label class="form-label">Plan</label>
             <label class="form-label">Oy bo‘yicha planlarni yuklab tanlang</label>
          <div class="input-group">
            
            <select id="cPlan" class="form-select">
                
              <option value="">— Avval Oy tanlang —</option>
            </select>
            <button class="btn btn-outline-secondary" id="btnLoadPlans">Yukla</button>
          </div>
       
        </div>
        <div class="col-lg-3">
          <label class="form-label">Shartnoma nomi</label>
          <input id="cTitle" class="form-control" placeholder="mas: Sentyabr operator shartnomasi">
        </div>
        <div class="col-lg-3">
          <label class="form-label">Imzo talabi</label>
          <select id="cRequireSign" class="form-select">
            <option value="1">Imzo majburiy</option>
            <option value="0">Imzo shart emas</option>
          </select>
        </div>
      </div>

      <div class="row g-3 mt-3">
        <div class="col-12">
          <label class="form-label">Admin izoh (matn)</label>
          <textarea id="cAdminNote" rows="2" class="form-control" placeholder="Shartnoma bo‘yicha qo‘shimcha izoh, topshiriqlar va sh.k."></textarea>
        </div>
      </div>

      <div class="row g-3 mt-2">
        <div class="col-12">
          <label class="form-label">Biriktirmalar (rasm / video / audio / hujjat — bir necha fayl tanlashingiz mumkin)</label>
          <input type="file" id="cFiles" class="form-control" multiple
                 accept="image/*,video/*,audio/*,application/pdf,.doc,.docx,.xls,.xlsx,.zip,.rar">
          <div class="preview-grid mt-2" id="filePreview"></div>
        </div>
      </div>

      <hr class="my-3">

      <div class="row g-3">
        <!-- ITEMS -->
        <div class="col-lg-6">
          <div class="d-flex justify-content-between align-items-center">
            <h6 class="mb-2">Punktlar</h6>
            <div class="d-flex align-items-center gap-2">
              <button class="btn btn-sm btn-outline-primary" id="btnLoadItems">Punktlarni yuklash</button>
              <div class="form-check">
                <input type="checkbox" id="chkAllItems" class="form-check-input">
                <label for="chkAllItems" class="form-check-label small">Hammasi</label>
              </div>
            </div>
          </div>
          <div class="table-responsive" style="max-height:360px;overflow:auto;border:1px solid #e9ecef;border-radius:.5rem;">
            <table class="table table-sm align-middle mb-0" id="tblItems">
              <thead class="table-light">
                <tr>
                  <th style="width:36px"></th>
                  <th>Sarlavha</th>
                  <th style="width:90px" class="text-center">Reja</th>
                  <th style="width:210px">Dalil</th>
                </tr>
              </thead>
              <tbody><!-- dinamik --></tbody>
            </table>
          </div>
          <div class="form-text">
            Punkt belgilang — **majburiy** dalillar (planda keltirilgan bo‘lsa) avtomatik ptichka bo‘ladi.
          </div>
        </div>

        <!-- OPERATORS -->
        <div class="col-lg-6">
          <div class="d-flex justify-content-between align-items-center">
            <h6 class="mb-2">Operatorlar</h6>
            <div class="input-group input-group-sm" style="max-width:320px;">
              <span class="input-group-text">Qidirish</span>
              <input id="opSearch" class="form-control" placeholder="Ism, login, tel...">
              <button class="btn btn-outline-secondary" id="btnOpsAll">Hammasi</button>
            </div>
          </div>
          <div class="table-responsive" style="max-height:360px;overflow:auto;border:1px solid #e9ecef;border-radius:.5rem;">
            <table class="table table-sm align-middle mb-0" id="tblOps">
              <thead class="table-light">
                <tr>
                  <th style="width:36px"><input type="checkbox" id="chkAllOps"></th>
                  <th>Operator</th>
                  <th>Login/Tel</th>
                </tr>
              </thead>
              <tbody><!-- dinamik --></tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="text-end mt-3">
        <button class="btn btn-success" id="btnCreate">Shartnomani yaratish</button>
      </div>
    </div>
  </div>

  <!-- LISTS -->
  <div class="card shadow-sm">
    <div class="card-header bg-light">
      <ul class="nav nav-tabs card-header-tabs" id="listTabs" role="tablist">
        <li class="nav-item" role="presentation">
          <button class="nav-link active" id="tabPending" data-bs-toggle="tab" data-bs-target="#panePending" type="button" role="tab">Kutilmoqda</button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="tabSigned" data-bs-toggle="tab" data-bs-target="#paneSigned" type="button" role="tab">Imzolangan</button>
        </li>
      </ul>
    </div>
    <div class="card-body">
      <div class="row g-2 mb-2">
        <div class="col-md-8">
          <input id="lQ" class="form-control" placeholder="Qidirish: shartnoma nomi / operator / plan">
        </div>
        <div class="col-md-4 text-end">
          <button class="btn btn-outline-primary" id="btnReloadLists">Ro‘yxatlarni yangilash</button>
        </div>
      </div>

      <div class="tab-content">
        <div class="tab-pane fade show active" id="panePending" role="tabpanel">
          <div class="table-responsive">
            <table class="table table-sm align-middle table-sticky" id="tblPending">
              <thead class="table-light">
                <tr>
                  <th>Vaqt</th>
                  <th>Shartnoma</th>
                  <th>Operator</th>
                  <th>Plan</th>
                  <th class="text-center" style="width:120px">Holat</th>
                  <th style="width:140px">Amal</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
          <div class="d-flex justify-content-between mt-2">
            <div class="text-muted small" id="pSum">Ko‘rsatilmoqda: 0–0 / Jami: 0</div>
            <ul class="pagination pagination-sm mb-0" id="pPager"></ul>
          </div>
        </div>

        <div class="tab-pane fade" id="paneSigned" role="tabpanel">
          <div class="table-responsive">
            <table class="table table-sm align-middle table-sticky" id="tblSigned">
              <thead class="table-light">
                <tr>
                  <th>Vaqt</th>
                  <th>Shartnoma</th>
                  <th>Operator</th>
                  <th>Plan</th>
                  <th class="text-center" style="width:120px">Holat</th>
                  <th style="width:140px">Amal</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
          <div class="d-flex justify-content-between mt-2">
            <div class="text-muted small" id="sSum">Ko‘rsatilmoqda: 0–0 / Jami: 0</div>
            <ul class="pagination pagination-sm mb-0" id="sPager"></ul>
          </div>
        </div>
      </div>

    </div>
  </div>
</div>

<!-- DETAIL MODAL (ixtiyoriy) -->
<div class="modal fade" id="viewModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Shartnoma</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body" id="viewBody"><div class="text-muted">Yuklanmoqda...</div></div>
  </div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
/* ===== Helpers ===== */
function esc(s){ return (s||'').replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;'}[m])); }
function showAlert(msg, type='danger'){ const b=document.getElementById('alertBox'); b.innerHTML=`<div class="alert alert-${type}">${esc(msg)}</div>`; setTimeout(()=>b.innerHTML='',5000); }
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]; }
  if(payload.data && typeof payload.data==='object'){
    for(const k of keys){ if(Array.isArray(payload.data[k])) return payload.data[k]; }
  }
  return [];
}
function fmtRange(total, page, limit){
  const start = total ? ((page-1)*limit + 1) : 0;
  const end   = total ? Math.min(total, page*limit) : 0;
  return {start,end,pages:Math.max(1, Math.ceil(total/limit))};
}

/* ===== Create form state ===== */
let opsAll=[], opsFiltered=[], items=[], pageP=1, pageS=1, limit=10;

/* File previews */
document.getElementById('cFiles').addEventListener('change', (e)=>{
  const box=document.getElementById('filePreview'); box.innerHTML='';
  const files=[...e.target.files];
  files.forEach(f=>{
    const div=document.createElement('div'); div.className='preview-item';
    const type=f.type||'';
    if(type.startsWith('image/')){
      const img=document.createElement('img');
      img.className='img-fluid rounded'; img.alt=f.name;
      img.src=URL.createObjectURL(f);
      div.appendChild(img);
    }else if(type.startsWith('video/')){
      div.innerHTML=`<video class="w-100" src="${URL.createObjectURL(f)}" muted></video>`;
    }else if(type.startsWith('audio/')){
      div.innerHTML=`<audio class="w-100" src="${URL.createObjectURL(f)}" controls></audio>`;
    }else{
      div.innerHTML=`<div class="small">${esc(f.name)}</div>`;
    }
    const meta=document.createElement('small'); meta.textContent = `${f.name} • ${(f.size/1024/1024).toFixed(1)} MB`;
    div.appendChild(meta);
    box.appendChild(div);
  });
});

/* Load Plans */
async function loadPlans(){
  const ym=document.getElementById('cYm').value;
  try{
    const r=await fetch(`../api/plans.php?action=list_plans&ym=${encodeURIComponent(ym)}&page=1&limit=200`);
    const d=await r.json();
    const sel=document.getElementById('cPlan'); sel.innerHTML='<option value="">— Plan tanlang —</option>';
    (d.rows||[]).forEach(pl=>{
      const o=document.createElement('option');
      o.value=pl.id; o.textContent=`${pl.ym} — ${pl.name}`;
      sel.appendChild(o);
    });
    if((d.rows||[]).length===0) showAlert('Bu oyga plan topilmadi','warning');
  }catch(e){ showAlert('Planlarni yuklashda xato: '+e.message); }
}

/* Load Items of Plan */
async function loadItems(){
  const pid=document.getElementById('cPlan').value;
  if(!pid){ showAlert('Avval Plan tanlang','warning'); return; }
  try{
    const r=await fetch(`../api/plans.php?action=list_items&plan_id=${pid}`);
    const d=await r.json(); items=d.items||[];
    renderItems(); updateStats();
  }catch(e){ showAlert('Punktlarni yuklashda xato: '+e.message); }
}
function renderItems(){
  const tb=document.querySelector('#tblItems tbody'); tb.innerHTML='';
  items.forEach(it=>{
    const evidDefaults = (it.evidence_types||'').split(',').filter(Boolean);
    const tr=document.createElement('tr');
    tr.innerHTML=`
      <td><input type="checkbox" class="i-choose" data-id="${it.id}"></td>
      <td>
        <div class="fw-semibold">${esc(it.title)}</div>
        <div class="text-muted small">${esc(it.description||'')}</div>
      </td>
      <td class="text-center">${it.target_int||0}</td>
      <td>
        <div class="row g-1 row-cols-2">
          ${['text','username','image','audio','video'].map(k=>`
            <div class="col">
              <div class="form-check form-check-inline">
                <input class="form-check-input i-ev" type="checkbox" data-id="${it.id}" value="${k}" id="ev_${k}_${it.id}">
                <label class="form-check-label" for="ev_${k}_${it.id}">${k==='text'?'Matn':(k==='username'?'Username':k.charAt(0).toUpperCase()+k.slice(1))}</label>
              </div>
            </div>`).join('')}
        </div>
      </td>
    `;
    tb.appendChild(tr);

    // Agar punkt belgilanganda auto ptichka bo‘lishi kerak bo‘lsa — i-choose change’da qilamiz:
    // Quyida handler bor (delegation).
    tr.dataset.defaults = evidDefaults.join(',');
  });
}

/* Delegated handlers for items */
document.getElementById('tblItems').addEventListener('change', (e)=>{
  const chk = e.target.closest('.i-choose');
  if(chk){
    const row = chk.closest('tr');
    const defaults = (row.dataset.defaults||'').split(',').filter(Boolean);
    // Tanlanganda: default evidence turlarini avtomatik ptichka
    if(chk.checked){
      defaults.forEach(k=>{
        const el = row.querySelector(`.i-ev[value="${k}"]`);
        if(el) el.checked = true;
      });
    }else{
      // Olib tashlanganda: shu qatordagi barcha evidence’ni yechib qo‘yamiz
      row.querySelectorAll('.i-ev').forEach(el=>{ el.checked=false; });
    }
    updateStats();
  }
  const ev = e.target.closest('.i-ev');
  if(ev){
    // Agar hech qanday evidence qolmasa ham, punkt belgilangani tursin — foydalanuvchi o‘zi boshqaradi.
    // Kerak bo‘lsa, shu yerda: 'kamida bitta dalil bo‘lsin' qoidasi qo‘shilishi mumkin.
  }
});
document.getElementById('chkAllItems').addEventListener('change', (e)=>{
  document.querySelectorAll('.i-choose').forEach(c=>{
    c.checked = e.target.checked;
    c.dispatchEvent(new Event('change'));
  });
});

/* Operators */
let opsSelCount = 0;
async function loadOps(){
  try{
    const r=await fetch('../api/operators.php'); const raw=await r.json();
    opsAll = pickArray(raw).map(o=>{
      const id=Number(o.id ?? o.operator_id ?? o.user_id ?? o.uid ?? 0);
      return {
        id,
        name: (o.name ?? o.full_name ?? o.title ?? '')+'',
        username: (o.username ?? o.login ?? '')+'',
        phone: (o.phone ?? o.tel ?? '')+''
      };
    }).filter(x=>x.id>0);
    opsFiltered=[...opsAll]; renderOps(); updateStats();
  }catch(e){ showAlert('Operatorlar yuklanmadi: '+e.message); }
}
function renderOps(){
  const tb=document.querySelector('#tblOps tbody'); tb.innerHTML='';
  opsFiltered.forEach(op=>{
    const tr=document.createElement('tr');
    tr.innerHTML=`
      <td><input type="checkbox" class="op-choose" data-id="${op.id}"></td>
      <td class="fw-semibold">${esc(op.name||'-')}</td>
      <td class="text-muted small"><span>@${esc(op.username||'-')}</span>${op.phone?` · ${esc(op.phone)}`:''}</td>
    `;
    tb.appendChild(tr);
  });
  opsSelCount = 0;
}
document.getElementById('chkAllOps').addEventListener('change', (e)=>{
  document.querySelectorAll('.op-choose').forEach(c=>{ c.checked = e.target.checked; });
  opsSelCount = e.target.checked ? opsFiltered.length : 0;
  updateStats();
});
document.getElementById('tblOps').addEventListener('change', (e)=>{
  const c=e.target.closest('.op-choose'); if(!c) return;
  opsSelCount += c.checked ? 1 : -1;
  updateStats();
});
document.getElementById('opSearch').addEventListener('input', (e)=>{
  const q=e.target.value.trim().toLowerCase();
  opsFiltered = !q ? [...opsAll] : opsAll.filter(o=>{
    const s=`${o.name} ${o.username} ${o.phone}`.toLowerCase(); return s.includes(q);
  });
  renderOps();
});
document.getElementById('btnOpsAll').addEventListener('click', ()=>{
  document.getElementById('chkAllOps').checked=true;
  document.querySelectorAll('.op-choose').forEach(c=>c.checked=true);
  opsSelCount = opsFiltered.length; updateStats();
});

/* Stats */
function updateStats(){
  const selItemCount = [...document.querySelectorAll('.i-choose:checked')].length;
  document.getElementById('statItems').textContent = `Punktlar: ${selItemCount}`;
  document.getElementById('statOps').textContent   = `Operatorlar: ${opsSelCount}`;
}

/* CREATE (FormData + files) */
document.getElementById('btnCreate').addEventListener('click', async ()=>{
  const ym=document.getElementById('cYm').value;
  const plan_id=parseInt(document.getElementById('cPlan').value||'0',10);
  const title=document.getElementById('cTitle').value.trim();
  const require_signature = document.getElementById('cRequireSign').value==='1'?1:0;
  const admin_note = document.getElementById('cAdminNote').value.trim();

  if(!ym || !plan_id || !title){ showAlert('Oy, Plan va Shartnoma nomi majburiy','warning'); return; }

  const chosenItems = [...document.querySelectorAll('.i-choose:checked')].map(c=>parseInt(c.dataset.id,10));
  if(chosenItems.length===0){ showAlert('Kamida bitta punkt tanlang','warning'); return; }

  // item -> evidence_types map (string)
  const itemMap = {};
  chosenItems.forEach(id=>itemMap[id]=[]);
  document.querySelectorAll('.i-ev:checked').forEach(ev=>{
    const id=parseInt(ev.dataset.id,10); if(itemMap[id]) itemMap[id].push(ev.value);
  });
  const finalItems = chosenItems.map(id=>({
    item_id: id,
    evidence_types: (itemMap[id]||[]).join(',') // string
  }));

  const operator_ids = [...document.querySelectorAll('.op-choose:checked')].map(c=>parseInt(c.dataset.id,10));
  if(operator_ids.length===0){ showAlert('Hech bo‘lmaganda bitta operator tanlang','warning'); return; }

  // Payload JSON
  const payload = {
    title, ym, plan_id,
    require_signature,
    admin_note,
    items: finalItems,
    operator_ids
  };

  // FormData + files[]
  const fd = new FormData();
  fd.append('payload', JSON.stringify(payload));
  const files = document.getElementById('cFiles').files;
  for(let i=0;i<files.length;i++){
    fd.append('files[]', files[i], files[i].name);
  }

  try{
    const r=await fetch('../api/contracts.php?action=create', { method:'POST', body: fd });
    const d=await r.json();
    if(!r.ok || !d.ok){ showAlert('Saqlash xatosi: '+(d.error||r.statusText),'danger'); return; }
    showAlert('Shartnoma yaratildi','success');

    // form tozalash
    document.getElementById('cTitle').value='';
    document.getElementById('cAdminNote').value='';
    document.getElementById('cFiles').value='';
    document.getElementById('filePreview').innerHTML='';
    document.getElementById('chkAllItems').checked=false;
    document.getElementById('chkAllOps').checked=false;
    document.querySelector('#tblItems tbody').innerHTML='';
    document.querySelectorAll('.op-choose').forEach(c=>c.checked=false);
    opsSelCount = 0; updateStats();

    await refreshLists();
  }catch(e){ showAlert('Tarmoq xatosi: '+e.message); }
});

/* LISTS (pending / signed) */
async function refreshLists(){ await Promise.all([loadList('pending'), loadList('signed')]); }
async function loadList(status){
  const q=document.getElementById('lQ').value.trim();
  const page = status==='pending' ? pageP : pageS;
  try{
    const r=await fetch(`../api/contracts.php?action=list&status=${status}&q=${encodeURIComponent(q)}&page=${page}&limit=${limit}`);
    const d=await r.json();
    const rows=d.rows||[]; const total=d.total||0;
    const {start,end,pages}=fmtRange(total, page, limit);

    const tb = document.querySelector(status==='pending' ? '#tblPending tbody' : '#tblSigned tbody'); tb.innerHTML='';
    rows.forEach(x=>{
      const when = (x.created_at||'').replace('T',' ').slice(0,19);
      const badge = `<span class="badge badge-status ${status}">${status}</span>`;
      const tr=document.createElement('tr');
      tr.innerHTML=`
        <td class="code-mono">${esc(when)}</td>
        <td><div class="fw-semibold">${esc(x.title||'-')}</div><div class="text-muted small">${esc(x.ym||'')}</div></td>
        <td>${esc(x.operator_name||'-')}</td>
        <td>${esc(x.plan_name||'-')}</td>
        <td class="text-center">${badge}</td>
        <td><button class="btn btn-sm btn-outline-primary" data-view="${x.id||''}">Ko‘rish</button></td>
      `;
      tb.appendChild(tr);
    });

    const sumEl = document.getElementById(status==='pending' ? 'pSum' : 'sSum');
    const pgEl  = document.getElementById(status==='pending' ? 'pPager' : 'sPager');
    sumEl.textContent = `Ko‘rsatilmoqda: ${start}–${end} / Jami: ${total}`;
    pgEl.innerHTML='';

    const liPrev=document.createElement('li');
    liPrev.className='page-item'+((page<=1)?' disabled':''); liPrev.innerHTML=`<a class="page-link" href="#" data-nav="prev">Orqaga</a>`;
    const liRange=document.createElement('li');
    liRange.className='page-item disabled'; liRange.innerHTML=`<span class="page-link">${start}–${end}</span>`;
    const liNext=document.createElement('li');
    liNext.className='page-item'+((page>=pages)?' disabled':''); liNext.innerHTML=`<a class="page-link" href="#" data-nav="next">Keyingi</a>`;
    pgEl.appendChild(liPrev); pgEl.appendChild(liRange); pgEl.appendChild(liNext);

    pgEl.querySelectorAll('.page-link').forEach(a=>{
      a.addEventListener('click', e=>{
        e.preventDefault();
        const nav=a.dataset.nav;
        if(status==='pending'){
          if(nav==='prev' && pageP>1){ pageP--; loadList('pending'); }
          if(nav==='next' && pageP<pages){ pageP++; loadList('pending'); }
        }else{
          if(nav==='prev' && pageS>1){ pageS--; loadList('signed'); }
          if(nav==='next' && pageS<pages){ pageS++; loadList('signed'); }
        }
      });
    });

  }catch(e){ showAlert('Ro‘yxatlarni yuklab bo‘lmadi: '+e.message); }
}
document.getElementById('btnReloadLists').addEventListener('click', ()=>{ pageP=1; pageS=1; refreshLists(); });
document.getElementById('lQ').addEventListener('input', ()=>{ pageP=1; pageS=1; refreshLists(); });

/* View detail (ixtiyoriy, agar backend bo‘lsa) */
document.addEventListener('click', async (e)=>{
  const btn = e.target.closest('button[data-view]');
  if(!btn) return;
  const id = btn.getAttribute('data-view');
  try{
    const r=await fetch(`../api/contracts.php?action=detail&id=${encodeURIComponent(id)}`);
    if(!r.ok){ showAlert('Detallar yuklanmadi','danger'); return; }
    const d=await r.json();
    const body=document.getElementById('viewBody');

    // Asosiy ma’lumotlar
    const created = (d.created_at||'').replace('T',' ').slice(0,19);
    const signedAtApi = (d.signed_at||'').replace('T',' ').slice(0,19);

    // Imzo (signature) blokini tayyorlaymiz
    const sig = d.signature || (d.signatures && d.signatures[0]) || null;
    const sigImg   = sig && (sig.image_path || sig.image) ? (sig.image_path || sig.image) : '';
    const sigTyped = sig && sig.typed_name ? sig.typed_name : '';
    const sigTime  = sig && sig.created_at ? sig.created_at.replace('T',' ').slice(0,19) : '';

    const signedTime = signedAtApi || sigTime; // qaysi biri bor bo‘lsa
    const signedBlock = (d.status === 'signed') ? `
      <hr class="my-3">
      <div class="mt-2">
        <div><strong>Imzolangan sana/vaqt:</strong> ${signedTime || '-'}</div>
        ${sigTyped ? `<div class="mt-1"><strong>Typed ism:</strong> ${esc(sigTyped)}</div>` : ``}
        ${
          sigImg
            ? `<div class="mt-2">
                 <img src="${esc(sigImg)}" alt="Imzo" style="max-width:100%;height:auto;border:1px solid #dee2e6;border-radius:.5rem;">
               </div>`
            : `<div class="text-muted mt-2">Imzo rasmi mavjud emas</div>`
        }
      </div>` : '';

    // Biriktirmalar ro‘yxati
    const attsHtml = (d.attachments||[]).length
      ? `<div class="mb-2"><strong>Biriktirmalar:</strong>
           <ul class="mb-0">
             ${(d.attachments||[]).map(a=>`<li><a href="${esc(a.url)}" target="_blank">${esc(a.name||a.url)}</a> <span class="text-muted small">(${esc(a.mime||'file')})</span></li>`).join('')}
           </ul>
         </div>`
      : '';

    // To‘liq kontent
    body.innerHTML = `
      <div class="mb-2"><strong>Shartnoma:</strong> ${esc(d.title||'-')}</div>
      <div class="mb-2"><strong>Oy:</strong> ${esc(d.ym||'-')}</div>
      <div class="mb-2"><strong>Plan:</strong> ${esc(d.plan_name||'-')}</div>
      <div class="mb-2"><strong>Status:</strong> <span class="badge ${d.status==='signed'?'badge-status signed':'badge-status pending'}">${esc(d.status||'-')}</span></div>
      <div class="mb-2"><strong>Yaratilgan:</strong> ${created || '-'}</div>
      ${d.admin_note ? `<div class="mb-2"><strong>Admin izoh:</strong><br><div class="border rounded p-2 bg-light">${esc(d.admin_note)}</div></div>` : ''}
      <div class="mb-2"><strong>Punktlar:</strong>
        <ul class="mb-0">
          ${(d.items||[]).map(it=>`<li>${esc(it.title)} — <span class="text-muted small">${esc(it.evidence_types||'-')}</span></li>`).join('')}
        </ul>
      </div>
      ${attsHtml}
      ${signedBlock}
    `;

    bootstrap.Modal.getOrCreateInstance(document.getElementById('viewModal')).show();
  }catch(e){
    showAlert('Detallar: '+e.message);
  }
});

/* INIT */
document.getElementById('btnLoadPlans').addEventListener('click', loadPlans);
document.getElementById('btnLoadItems').addEventListener('click', loadItems);
document.addEventListener('DOMContentLoaded', async ()=>{
  await loadOps();
  await loadPlans();
  await refreshLists();
});
</script>
</body>
</html>
