<?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>Hodimlar — Keldi/Ketdi loglari</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}
</style>
</head>
<body class="bg-light">
<nav class="navbar navbar-dark bg-primary">
  <div class="container">
    <a class="navbar-brand fw-semibold" href="#">Hodimlar | Keldi–ketdi</a>
    <label class="btn btn-outline-light btn-sm mb-0">
      CSV yuklash
      <input id="csvInput" type="file" accept=".csv" hidden>
    </label>
  </div>
</nav>

<div class="container my-3">
  <div id="alertBox"></div>

  <div class="card 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="fYm" class="form-control" value="<?php echo date('Y-m'); ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Qidirish (FIO/EmpCode/bo‘lim)</label>
          <input id="fQ" class="form-control" placeholder="FIO yoki emp_code">
        </div>
        <div class="col-md-2">
          <label class="form-label">Sahifa hajmi</label>
          <select id="fLimit" class="form-select"><option>10</option><option>20</option><option>50</option></select>
        </div>
        <div class="col-md-2 text-end">
          <button class="btn btn-primary w-100" id="btnSearch">Qidirish</button>
        </div>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-body table-responsive">
      <table class="table table-sm table-hover table-sticky align-middle" id="tblEmp">
        <thead class="table-light"><tr><th>ID</th><th>EmpCode</th><th>FIO</th><th>Bo‘lim</th><th>Lavozim</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="small text-muted" id="empRange">0–0 / 0</div>
        <ul class="pagination pagination-sm mb-0" id="empPager"></ul>
      </div>
    </div>
  </div>
</div>

<!-- LOGS MODAL -->
<div class="modal fade" id="logsModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Keldi–ketdi</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body" id="logsBody"><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>
function esc(s){ return (s||'').replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;'}[m])); }
function show(msg,type){ const b=document.getElementById('alertBox'); b.innerHTML=`<div class="alert alert-${type||'info'}">${esc(msg)}</div>`; setTimeout(()=>b.innerHTML='',4000); }
async function fetchJSON(url,opts){ const r=await fetch(url,opts); const t=await r.text(); if(!r.ok) throw new Error(`HTTP ${r.status} ${r.statusText}: ${t.slice(0,200)}`); try{return JSON.parse(t);}catch{throw new Error('JSON parse xato: '+t.slice(0,200));} }

const st={rows:[], page:1, limit:10};

async function loadEmployees(page=1){
  const q=document.getElementById('fQ').value.trim();
  const limit=parseInt(document.getElementById('fLimit').value||'10',10);
  const url=`../api/attendance.php?action=employees&q=${encodeURIComponent(q)}&page=${page}&limit=${limit}`;
  let d; try{ d=await fetchJSON(url); }catch(e){ show('Operatorlar olinmadi: '+e.message,'danger'); return; }
  if(!d.ok){ show('API xato','danger'); return; }
  st.rows=d.rows||[]; st.page=d.page||page; st.limit=d.limit||limit;
  renderEmployees();
}
function renderEmployees(){
  const {rows,page,limit}=st;
  const start=(page-1)*limit, end=Math.min(rows.length, start+limit);
  const slice=rows.slice(start,end);

  const tb=document.querySelector('#tblEmp tbody'); tb.innerHTML='';
  const ymVal=document.getElementById('fYm').value;
  slice.forEach(e=>{
    const tr=document.createElement('tr');
    tr.innerHTML=`
      <td>${e.id}</td>
      <td>${esc(e.emp_code||'')}</td>
      <td>${esc(e.fio||'')}</td>
      <td>${esc(e.dept||'')}</td>
      <td>${esc(e.position||'')}</td>
      <td>
        <button class="btn btn-sm btn-outline-primary me-1" data-emp="${e.id}">Keldi–ketdi</button>
        <div class="btn-group">
          <a class="btn btn-sm btn-outline-secondary" href="../api/attendance.php?action=export&fmt=csv&employee_id=${e.id}&ym=${encodeURIComponent(ymVal)}">CSV</a>
          <a class="btn btn-sm btn-outline-secondary" href="../api/attendance.php?action=export&fmt=xls&employee_id=${e.id}&ym=${encodeURIComponent(ymVal)}">XLS</a>
          <a class="btn btn-sm btn-outline-secondary" href="../api/attendance.php?action=export&fmt=pdf&employee_id=${e.id}&ym=${encodeURIComponent(ymVal)}">PDF</a>
        </div>
      </td>`;
    tb.appendChild(tr);
  });

  const total=rows.length, from=total?start+1:0, to=end;
  document.getElementById('empRange').textContent=`${from}–${to} / ${total}`;

  const pages=Math.max(1, Math.ceil(total/limit));
  const pg=document.getElementById('empPager'); pg.innerHTML='';
  const mk=(dis,label,nav)=>{ const li=document.createElement('li'); li.className='page-item'+(dis?' disabled':''); li.innerHTML=`<a class="page-link" href="#" data-nav="${nav||''}">${label}</a>`; return li; };
  pg.appendChild(mk(page<=1,'Orqaga','prev'));
  pg.appendChild(mk(true, `${from}–${to}`, ''));
  pg.appendChild(mk(page>=pages,'Keyingi','next'));
  pg.querySelectorAll('a.page-link').forEach(a=>{
    a.addEventListener('click',(e)=>{
      e.preventDefault();
      if(a.dataset.nav==='prev' && st.page>1){ st.page--; renderEmployees(); }
      if(a.dataset.nav==='next' && st.page<pages){ st.page++; renderEmployees(); }
    });
  });
}

// CSV upload (auto-refresh)
document.getElementById('csvInput').addEventListener('change', async (e)=>{
  const f=e.target.files[0]; if(!f) return;
  const fd=new FormData(); fd.append('ym', document.getElementById('fYm').value); fd.append('file', f, f.name);
  try{
    const d=await fetchJSON('../api/attendance.php?action=upload_csv',{method:'POST',body:fd});
    if(!d.ok){ show('Import xatosi: '+(d.error||''),'danger'); return; }
    show('CSV import qabul qilindi (#'+d.import_id+')','success');
    await loadEmployees(1);
  }catch(err){ show('Import xatosi: '+err.message,'danger'); }
});

// Keldi–ketdi modal
document.addEventListener('click', async (e)=>{
  const btn=e.target.closest('button[data-emp]'); if(!btn) return;
  const empId=parseInt(btn.getAttribute('data-emp'),10);
  const ym   =document.getElementById('fYm').value;
  let d; try{ d=await fetchJSON(`../api/attendance.php?action=employee_logs&employee_id=${empId}&ym=${encodeURIComponent(ym)}`); }
  catch(err){ show('Logs: '+err.message,'danger'); return; }
  if(!d.ok){ show('API xato: '+(d.error||''),'danger'); return; }

  const b=document.getElementById('logsBody');
  let rows='';
  (d.days||[]).forEach(day=>{
    const items = (day.events||[]).map(ev=>`<span class="badge ${ev.type==='in'?'text-bg-success':'text-bg-secondary'} me-1">${esc(ev.time)} ${esc(ev.type.toUpperCase())}</span>`).join(' ');
    rows += `<tr><td>${esc(day.day)}</td><td>${items || '<span class="text-muted">—</span>'}</td></tr>`;
  });
  b.innerHTML = `
    <div class="mb-2"><strong>${esc(d.employee.fio)}</strong> (#${d.employee.id}) — ${esc(d.ym)}</div>
    <div class="table-responsive">
      <table class="table table-sm align-middle">
        <thead class="table-light"><tr><th>Sana</th><th>Loglar</th></tr></thead>
        <tbody>${rows || '<tr><td colspan="2" class="text-muted">Ma’lumot yo‘q</td></tr>'}</tbody>
      </table>
    </div>`;
  bootstrap.Modal.getOrCreateInstance(document.getElementById('logsModal')).show();
});

// init
document.getElementById('btnSearch').addEventListener('click', ()=>loadEmployees(1));
window.addEventListener('DOMContentLoaded', ()=>loadEmployees(1));
</script>
</body>
</html>
