<?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>Dalillarni tekshirish (Admin)</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.badge-status { font-weight:600; }
.badge-status.pending { background:#fff3cd; color:#664d03; }
.badge-status.approved { background:#d1e7dd; color:#0f5132; }
.badge-status.rejected { background:#f8d7da; color:#842029; }
.preview-box { border:1px solid #e9ecef; border-radius:.5rem; padding:.75rem; background:#fff; }
.table-sticky thead th { position: sticky; top: 0; background:#fff; z-index:2; }
.code-mono { font-family: ui-monospace, Menlo, Consolas, monospace; font-size:.9em; }
</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 active" 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" id="app">
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="row g-2 align-items-end">
        <div class="col-md-2"><label class="form-label">Oy</label><input type="month" id="ym" class="form-control" value="<?php echo date('Y-m'); ?>"></div>
        <div class="col-md-2">
          <label class="form-label">Holat</label>
          <select id="status" class="form-select">
            <option value="pending">pending</option>
            <option value="approved">approved</option>
            <option value="rejected">rejected</option>
            <option value="all" selected>all</option>
          </select>
        </div>
        <div class="col-md-2"><label class="form-label">Plan ID</label><input id="plan_id" class="form-control" placeholder="ixtiyoriy"></div>
        <div class="col-md-2"><label class="form-label">Operator ID</label><input id="op_id" class="form-control" placeholder="ixtiyoriy"></div>
        <div class="col-md-2"><label class="form-label">Qidirish</label><input id="q" class="form-control" placeholder="operator/plan/punkt/matn"></div>
        <div class="col-md-2"><button id="load" class="btn btn-primary w-100">Yuklash</button></div>
      </div>
    </div>
  </div>

  <div id="alertBox"></div>

  <div class="card shadow-sm">
    <div class="card-body table-responsive">
      <table class="table table-sm align-middle table-hover table-sticky" id="tbl">
        <thead class="table-light">
          <tr>
            <th style="width:140px">Vaqt</th>
            <th>Operator</th>
            <th>Plan / Punkt</th>
            <th>Dalil</th>
            <th style="width:120px">Holat</th>
            <th style="width:160px">Amal</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
      <div class="d-flex justify-content-between align-items-center mt-2">
        <div class="text-muted small" id="sumInfo">0 ta</div>
        <nav><ul class="pagination pagination-sm mb-0" id="pager"></ul></nav>
      </div>
    </div>
  </div>
</div>

<!-- Review Modal -->
<div class="modal fade" id="revModal" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">Dalil</h5>
      <button class="btn-close" data-bs-dismiss="modal"></button>
    </div>
    <div class="modal-body">
      <div class="row g-3">
        <div class="col-lg-7">
          <div class="preview-box" id="revPreview"><div class="text-muted">Podrobnostlar...</div></div>
        </div>
        <div class="col-lg-5">
          <div class="card mb-3"><div class="card-header bg-light">Ma’lumot</div><div class="card-body" id="revInfo"></div></div>
          <div class="card">
            <div class="card-header bg-light">Statusni o‘zgartirish</div>
            <div class="card-body">
              <div class="mb-2">
                <select id="revStatus" class="form-select">
                  <option value="pending">pending</option>
                  <option value="approved">approved</option>
                  <option value="rejected">rejected</option>
                </select>
              </div>
              <div class="mb-2">
                <label class="form-label">Izoh (ixtiyoriy)</label>
                <textarea id="revNote" class="form-control" rows="2"></textarea>
              </div>
              <div class="d-flex gap-2">
                <button class="btn btn-success" id="btnApprove">Tasdiqlash</button>
                <button class="btn btn-danger" id="btnReject">Rad etish</button>
                <button class="btn btn-secondary" id="btnPending">Pending</button>
                <button class="btn btn-outline-primary ms-auto" id="btnPrev">← Prev</button>
                <button class="btn btn-outline-primary" id="btnNext">Next →</button>
              </div>
              <div class="small text-muted mt-2">Modal fokusida ←/→ tugmalari bilan ham o‘tasiz.</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div></div>
</div>

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

function esc(s){ return (s||'').replace(/[&<>"']/g, m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;' }[m])); }
function badge(st){ const cls=st==='approved'?'approved':(st==='rejected'?'rejected':'pending'); return `<span class="badge badge-status ${cls}">${st}</span>`; }
function fmtSize(b){ if(!b) return '-'; const u=['B','KB','MB','GB']; let i=0,s=b; while(s>=1024&&i<u.length-1){ s/=1024;i++; } return (Math.round(s*10)/10)+' '+u[i]; }

// Bir dona umumiy alert helper
function showAlert(msg, type='danger'){
  document.getElementById('alertBox').innerHTML = `<div class="alert alert-${type}">${esc(msg)}</div>`;
  setTimeout(()=>document.getElementById('alertBox').innerHTML='', 5000);
}

async function loadList(p=1){
  page=p;
  const ym=document.getElementById('ym').value, status=document.getElementById('status').value,
        pid=document.getElementById('plan_id').value.trim(), oid=document.getElementById('op_id').value.trim(),
        q=document.getElementById('q').value.trim();

  const url=`../api/review_list.php?ym=${encodeURIComponent(ym)}&status=${encodeURIComponent(status)}${pid?`&plan_id=${encodeURIComponent(pid)}`:''}${oid?`&operator_id=${encodeURIComponent(oid)}`:''}${q?`&q=${encodeURIComponent(q)}`:''}&page=${page}&limit=${limit}`;

  let d;
  try{
    const res=await fetch(url);
    if(!res.ok){
      const txt=await res.text();
      showAlert(`API xato (${res.status}): ${txt}`,'danger');
      return;
    }
    d = await res.json();
  }catch(e){
    showAlert('API bilan aloqa bo‘lmadi: '+e.message, 'danger');
    return;
  }

  if (d.error){
    showAlert('API xabari: '+(d.detail? (d.error+' — '+d.detail) : d.error), 'warning');
    return;
  }

  rows=d.rows||[]; total=d.total||0;
  const tb=document.querySelector('#tbl tbody'); tb.innerHTML='';
  rows.forEach((x,i)=>{
    const when = x.created_at ? x.created_at.replace('T',' ').slice(0,19) : '';
    const fileLbl = x.file_mime ? x.file_mime.split('/')[0] : (x.file_path? 'file' : (x.username_ref?'username':(x.text_content?'text':'-')));
    const dalil = x.file_path ? `<span class="badge text-bg-light">${esc(fileLbl)}</span>` :
                  (x.username_ref? `<span class="badge text-bg-light">@${esc(x.username_ref)}</span>` :
                  (x.text_content? `<span class="badge text-bg-light">text</span>` : '-'));
    const tr=document.createElement('tr'); tr.dataset.idx=i;
    tr.innerHTML=`
      <td class="code-mono">${when}</td>
      <td><strong>${esc(x.operator_name)}</strong><div class="text-muted small">${esc(x.operator_code||'')}</div></td>
      <td><div class="small text-muted">${esc(x.plan_name)}</div><div class="fw-semibold">${esc(x.item_title)}</div></td>
      <td>${dalil}</td>
      <td>${badge(x.status)}</td>
      <td>
        <button class="btn btn-sm btn-outline-primary me-1" data-action="view">Ko‘rish</button>
        <button class="btn btn-sm btn-outline-success me-1" data-action="quick" data-st="approved">OK</button>
        <button class="btn btn-sm btn-outline-danger" data-action="quick" data-st="rejected">RAD</button>
      </td>`;
    tb.appendChild(tr);
  });

  // --- YANGI: diapazon matni va pager ----
  const pages = Math.max(1, Math.ceil(total/limit));
  const start = total ? ((page-1)*limit + 1) : 0;
  const end   = total ? Math.min(total, page*limit) : 0;

  document.getElementById('sumInfo').textContent = `Ko‘rsatilmoqda: ${start}–${end} / Jami: ${total}`;

  const pg=document.getElementById('pager'); pg.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>`;
  pg.appendChild(liPrev);

  const liRange = document.createElement('li');
  liRange.className = 'page-item disabled';
  liRange.innerHTML = `<span class="page-link">${start}–${end}</span>`;
  pg.appendChild(liRange);

  const liNext = document.createElement('li');
  liNext.className = 'page-item' + (page>=pages ? ' disabled' : '');
  liNext.innerHTML = `<a class="page-link" href="#" data-nav="next">Keyingi</a>`;
  pg.appendChild(liNext);

  pg.querySelectorAll('.page-link').forEach(a=>{
    a.addEventListener('click', e=>{
      e.preventDefault();
      const nav = a.dataset.nav;
      if(nav==='prev' && page>1) loadList(page-1);
      if(nav==='next' && page<pages) loadList(page+1);
    });
  });
  // --- /YANGI ---
}

function renderPreview(x){
  const box=document.getElementById('revPreview'); let html='';
  if(x.file_path && x.file_mime){
    if(x.file_mime.startsWith('image/')) html = `<img src="${x.file_path}" class="img-fluid rounded">`;
    else if(x.file_mime.startsWith('audio/')) html = `<audio controls class="w-100" src="${x.file_path}"></audio>`;
    else if(x.file_mime.startsWith('video/')) html = `<video controls class="w-100" src="${x.file_path}"></video>`;
    else html = `<a href="${x.file_path}" target="_blank" class="btn btn-outline-secondary">Faylni ochish</a>`;
  }
  if(x.username_ref) html += `<div class="mt-2"><strong>Username:</strong> ${esc(x.username_ref)}</div>`;
  if(x.text_content) html += `<div class="mt-2"><strong>Matn:</strong><div class="border rounded p-2 bg-light">${esc(x.text_content)}</div></div>`;
  if(!html) html = `<div class="text-muted">Fayl/matn yo‘q</div>`;
  box.innerHTML = html;
}
function renderInfo(x){
  const info=document.getElementById('revInfo');
  const created = x.created_at ? x.created_at.replace('T',' ').slice(0,19) : '-';
  const reviewed = x.reviewed_at ? x.reviewed_at.replace('T',' ').slice(0,19) : '-';
  info.innerHTML = `
    <div class="mb-1"><strong>Operator:</strong> ${esc(x.operator_name)} <span class="text-muted">(${esc(x.operator_code||'')})</span></div>
    <div class="mb-1"><strong>Plan/Punkt:</strong> ${esc(x.plan_name)} / <span class="fw-semibold">${esc(x.item_title)}</span></div>
    <div class="mb-1"><strong>Oy:</strong> ${esc(x.ym)}</div>
    <div class="mb-1"><strong>Holat:</strong> ${badge(x.status)}</div>
    <div class="mb-1"><strong>O‘lcham:</strong> ${fmtSize(x.file_size||0)} <span class="text-muted">(${esc(x.file_mime||'-')})</span></div>
    ${x.file_hash ? `<div class="mb-1 code-mono"><strong>Hash:</strong> ${esc(x.file_hash)}</div>` : ''}
    <div class="mb-1"><strong>Yaratildi:</strong> ${created}</div>
    <div class="mb-1"><strong>Ko‘rib chiqildi:</strong> ${reviewed} ${x.reviewer_name?`<span class="text-muted">(by ${esc(x.reviewer_name)})</span>`:''}</div>
  `;
}
function openByIndex(i){
  if(i<0 || i>=rows.length) return; curIdx=i;
  const x=rows[i];
  document.querySelector('#revModal .modal-title').innerHTML = `Dalil #${x.id} — <span class="text-muted small">${esc(x.plan_name)} / ${esc(x.item_title)}</span>`;
  renderPreview(x); renderInfo(x);
  document.getElementById('revStatus').value = x.status;
  document.getElementById('revNote').value = x.review_note || '';
  bootstrap.Modal.getOrCreateInstance(document.getElementById('revModal')).show();
}
async function updateStatus(id, st, note){
  try{
    const r = await fetch('../api/review.php', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id, status:st, note}) });
    if(!r.ok){ const txt=await r.text(); showAlert(`Status xatosi (${r.status}): ${txt}`); return false; }
    const d = await r.json(); if(!d.ok){ showAlert('API: '+JSON.stringify(d)); return false; }
    return true;
  }catch(e){ showAlert('Tarmoq xatosi: '+e.message); return false; }
}

document.getElementById('tbl').addEventListener('click', async (e)=>{
  const btn=e.target.closest('button'); if(!btn) return;
  const tr=btn.closest('tr'); const idx=parseInt(tr.dataset.idx,10); const x=rows[idx];
  if(btn.dataset.action==='view'){ openByIndex(idx); }
  else if(btn.dataset.action==='quick'){
    const st=btn.dataset.st; if(await updateStatus(x.id, st, '')){ rows[idx].status=st; tr.children[4].innerHTML=badge(st); }
  }
});
document.getElementById('btnApprove').addEventListener('click', async ()=>{
  const x=rows[curIdx]; const note=document.getElementById('revNote').value.trim();
  if(await updateStatus(x.id, 'approved', note)){ rows[curIdx].status='approved'; document.getElementById('revStatus').value='approved'; renderInfo(rows[curIdx]); const tr=document.querySelector(`#tbl tbody tr[data-idx='${curIdx}']`); if(tr) tr.children[4].innerHTML=badge('approved'); }
});
document.getElementById('btnReject').addEventListener('click', async ()=>{
  const x=rows[curIdx]; const note=document.getElementById('revNote').value.trim();
  if(await updateStatus(x.id, 'rejected', note)){ rows[curIdx].status='rejected'; document.getElementById('revStatus').value='rejected'; renderInfo(rows[curIdx]); const tr=document.querySelector(`#tbl tbody tr[data-idx='${curIdx}']`); if(tr) tr.children[4].innerHTML=badge('rejected'); }
});
document.getElementById('btnPending').addEventListener('click', async ()=>{
  const x=rows[curIdx]; const note=document.getElementById('revNote').value.trim();
  if(await updateStatus(x.id, 'pending', note)){ rows[curIdx].status='pending'; document.getElementById('revStatus').value='pending'; renderInfo(rows[curIdx]); const tr=document.querySelector(`#tbl tbody tr[data-idx='${curIdx}']`); if(tr) tr.children[4].innerHTML=badge('pending'); }
});
document.getElementById('revStatus').addEventListener('change', async (e)=>{
  const st=e.target.value; const x=rows[curIdx]; const note=document.getElementById('revNote').value.trim();
  if(await updateStatus(x.id, st, note)){ rows[curIdx].status=st; renderInfo(rows[curIdx]); const tr=document.querySelector(`#tbl tbody tr[data-idx='${curIdx}']`); if(tr) tr.children[4].innerHTML=badge(st); }
});
document.getElementById('btnPrev').addEventListener('click', ()=>{ if(curIdx>0) openByIndex(curIdx-1); });
document.getElementById('btnNext').addEventListener('click', ()=>{ if(curIdx<rows.length-1) openByIndex(curIdx+1); });
document.getElementById('revModal').addEventListener('keydown', (e)=>{ if(e.key==='ArrowLeft') document.getElementById('btnPrev').click(); if(e.key==='ArrowRight') document.getElementById('btnNext').click(); });

document.getElementById('load').addEventListener('click', ()=>loadList(1));
document.addEventListener('DOMContentLoaded', ()=>loadList(1));
</script>
</body>
</html>
