<?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>Admin — Dashboard (Dinamik)</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<style>.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 active" 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" 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-4">
  <div id="alertBox"></div>

  <div class="d-flex align-items-end gap-3 flex-wrap mb-3">
    <div><label class="form-label">Oy</label><input type="month" id="ym" class="form-control" value="<?php echo date('Y-m'); ?>"></div>
    <div><label class="form-label">Hodim</label><select id="fOp" class="form-select"></select></div>
    <div><label class="form-label">Bo‘lim</label><input id="fDept" class="form-control" placeholder="Sales"></div>
    <div><label class="form-label">Hudud</label><input id="fReg" class="form-control" placeholder="Chilonzor"></div>
    <div><label class="form-label">Qidirish</label><input id="fQ" class="form-control" placeholder="ism yoki kod"></div>
    <button id="refreshBtn" class="btn btn-primary">Hisobla</button>
  </div>

  <div class="mb-2">
    <a id="btnCsv" class="btn btn-outline-secondary btn-sm me-2" href="#">CSV</a>
    <a id="btnXls" class="btn btn-outline-secondary btn-sm me-2" href="#">Excel (XLS)</a>
    <a id="btnPdf" class="btn btn-outline-secondary btn-sm" href="#">PDF</a>
  </div>

  <div class="row g-3 mb-3">
    <div class="col-md-3"><div class="card border-primary"><div class="card-body"><div class="text-muted">Umumiy fiksalar summasi</div><div class="h4 mb-0" id="tBase">—</div></div></div></div>
    <div class="col-md-3"><div class="card border-info"><div class="card-body"><div class="text-muted">Jami summa</div><div class="h4 mb-0" id="tGross">—</div></div></div></div>
    <div class="col-md-3"><div class="card border-warning"><div class="card-body"><div class="text-muted">Jami Jarimalar</div><div class="h4 mb-0" id="tPen">—</div></div></div></div>
    <div class="col-md-3"><div class="card border-success"><div class="card-body"><div class="text-muted">Yakuniy hisoblangan summa</div><div class="h4 mb-0" id="tNet">—</div></div></div></div>
  </div>

  <!-- Finalize panel -->
  <div class="card shadow-sm mb-3">
    <div class="card-body d-flex flex-wrap gap-2 align-items-end">
      <div><label class="form-label">Finalize uchun oy</label><input type="month" id="fy" class="form-control" value="<?php echo date('Y-m'); ?>"></div>
      <button class="btn btn-success" id="btnFinAll">Oyliklarni hisoblash</button>
      <button class="btn btn-outline-secondary" id="btnUnfinAll">Bekor qilish</button>
      <span class="text-muted small ms-auto" id="finInfo">—</span>
    </div>
  </div>

  <div class="card shadow-sm mb-4">
    <div class="card-body table-responsive">
      <table class="table table-sm table-hover align-middle table-sticky" id="tbl">
        <thead class="table-primary"><tr>
          <th>Hodim</th><th>Bo‘lim</th><th>Hudud</th>
          <th>Asosiy</th><th>Plan % (asli)</th><th>Bonus summalar</th>
          <th>Jami summa</th><th>Jarima</th><th>Yakuniy summa</th>
          <th>Hisoblangan fiksa</th><th>Imzo</th><th>Amal</th>
        </tr></thead>
        <tbody></tbody>
      </table>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-md-6"><div class="card shadow-sm"><div class="card-body"><canvas id="chartNet"></canvas></div></div></div>
    <div class="col-md-6"><div class="card shadow-sm"><div class="card-body"><canvas id="chartPen"></canvas></div></div></div>
  </div>
</div>

<!-- Approve base -->
<div class="modal fade" id="approveModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-primary text-white"><h5 class="modal-title">Asosiy oylikni tasdiqlash</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <div class="mb-2"><strong id="mOpName"></strong></div>
    <div class="mb-3"><label class="form-label">Asosiy oylik (so'm)</label><input type="number" id="mBaseAmount" class="form-control" step="1000"></div>
    <div class="form-check"><input class="form-check-input" type="checkbox" id="mConfirm"><label class="form-check-label" for="mConfirm">Tasdiqlayman</label></div>
    <input type="hidden" id="mOpId"><input type="hidden" id="mYm">
  </div>
  <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Bekor</button><button class="btn btn-primary" id="mSave">Saqlash</button></div>
</div></div></div>

<!-- View row -->
<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 bg-success text-white"><h5 class="modal-title">Hodim tafsilotlari</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
  <div class="modal-body"><div id="viewBody"></div></div>
  <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Yopish</button></div>
</div></div></div>

<!-- Signature -->
<div class="modal fade" id="sigModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Imzo</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body" id="sigBody"><div class="text-muted">—</div></div>
</div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
var lastRows=[], netChart, penChart, __finalizeCache={};

function esc(s){ return (s||'').replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;'}[m])); }
function fmt(n){ try{return new Intl.NumberFormat('uz-UZ').format(n||0)+' so`m';}catch(e){return (n||0)+' so`m';} }
function showAlert(msg,type){ const box=document.getElementById('alertBox'); box.innerHTML=`<div class="alert alert-${type||'danger'}">${esc(msg)}</div>`; setTimeout(()=>box.innerHTML='',5000); }

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(e){throw new Error('JSON xato: '+t.slice(0,200));}
}

async function loadOpFilter(){
  try{
    const d=await fetchJSON('../api/operators.php');
    const sel=document.getElementById('fOp'); sel.innerHTML='<option value="">— Barchasi —</option>';
    (d.rows||d).forEach(o=>{ const opt=document.createElement('option'); opt.value=o.id; opt.textContent=o.name+' ('+o.code+')'; sel.appendChild(opt); });
  }catch(e){ showAlert('operators: '+e.message); }
}

function updateExportLinks(){
  const ym=document.getElementById('ym').value;
  const params=new URLSearchParams({ym,dept:document.getElementById('fDept').value,region:document.getElementById('fReg').value,q:document.getElementById('fQ').value,op:document.getElementById('fOp').value});
  document.getElementById('btnCsv').href='../api/export_csv.php?'+params.toString();
  document.getElementById('btnXls').href='../api/export_xls.php?'+params.toString();
  document.getElementById('btnPdf').href='../api/export_pdf.php?'+params.toString();
}

async function loadFinalizePanel(){
  // ixtiyoriy: finalize holatini umumiy ko'rsatish uchun finalize.php ni ishlatamiz
  try{
    const ym=document.getElementById('fy').value;
    const d=await fetchJSON('../api/finalize.php?action=status&ym='+encodeURIComponent(ym));
    __finalizeCache = {}; (d.per_operator||[]).forEach(x=>{__finalizeCache[x.operator_id]=x;});
    document.getElementById('finInfo').textContent='Hisoblangan oyliklar soni: '+(d.totals?.finalized||0)+' ta | Imzolangan : '+(d.totals?.signed||0)+' ta';
  }catch(e){ /* optional */ }
}

async function refresh(){
  try{
    const ym=document.getElementById('ym').value;
    const params=new URLSearchParams({ym,dept:document.getElementById('fDept').value,region:document.getElementById('fReg').value,q:document.getElementById('fQ').value,op:document.getElementById('fOp').value});
    const data=await fetchJSON('../api/calc_payroll.php?'+params.toString());
    lastRows=data.rows||[];

    document.getElementById('tBase').innerText=fmt(data.totals?.base||0);
    document.getElementById('tGross').innerText=fmt(data.totals?.gross||0);
    document.getElementById('tPen').innerText=fmt(data.totals?.penalties||0);
    document.getElementById('tNet').innerText=fmt(data.totals?.net||0);

    const tbody=document.querySelector('#tbl tbody'); tbody.innerHTML='';
    lastRows.forEach((r,i)=>{
      const fin = (__finalizeCache[r.operator_id]?.admin_finalized ?? r.admin_finalized) ? "<span class='badge text-bg-success'>Hisoblandi</span>" : "<span class='badge text-bg-secondary'>Hisoblanmagan</span>";
      const sig = (__finalizeCache[r.operator_id]?.operator_signature_path ?? r.operator_signature_path) ? "<span class='badge text-bg-success'>Imzo bor</span>" : "<span class='badge text-bg-secondary'>Yo‘q</span>";
      const pct = (r.plan_pct_avg ?? 0);
      const pctBadge = pct>=90?'text-bg-success':(pct>=50?'text-bg-warning text-dark':'text-bg-danger');
      const tr=document.createElement('tr');
      tr.innerHTML = `
        <td>${esc(r.name)}</td>
        <td>${esc(r.department||'')}</td>
        <td>${esc(r.region||'')}</td>
        <td>${fmt(r.base_amount)}<br>${r.base_confirmed?'<span class="badge text-bg-success">Tasdiqlangan</span>':'<span class="badge text-bg-warning text-dark">Kutilmoqda</span>'}</td>
        <td><span class="badge ${pctBadge}">${pct}%</span></td>
        <td class="fw-semibold">${fmt(r.dynamic_bonus)}</td>
        <td class="fw-semibold">${fmt(r.gross)}</td>
        <td class="text-danger">-${fmt(r.penalties_total)}</td>
        <td class="fw-bold">${fmt(r.net)}</td>
        <td><button class="btn btn-sm btn-outline-dark finBtn" data-id="${r.operator_id}">${fin}</button></td>
        <td><button class="btn btn-sm btn-outline-secondary sigBtn" data-id="${r.operator_id}">${sig}</button></td>
        <td>
          <button class='btn btn-sm btn-outline-primary' data-action='approve' data-id='${r.operator_id}' data-name='${esc(r.name)}' data-base='${r.base_amount}'>Tasdiqlash</button>
          <button class='btn btn-sm btn-outline-success ms-1' data-action='view' data-index='${i}'>Ko‘rish</button>
        </td>`;
      tbody.appendChild(tr);
    });

    // bind actions
    tbody.querySelectorAll('button[data-action=approve]').forEach(btn=>btn.addEventListener('click',()=>{
      document.getElementById('mOpId').value=btn.dataset.id;
      document.getElementById('mOpName').textContent=btn.dataset.name;
      document.getElementById('mBaseAmount').value=btn.dataset.base;
      document.getElementById('mConfirm').checked=true;
      document.getElementById('mYm').value=document.getElementById('ym').value;
      bootstrap.Modal.getOrCreateInstance(document.getElementById('approveModal')).show();
    }));

  tbody.querySelectorAll('button[data-action=view]').forEach(btn => btn.addEventListener('click', async ()=>{
  const r = lastRows[parseInt(btn.dataset.index,10)];
  const ym = document.getElementById('ym').value;

  // 1) Plan breakdown (planlar + itemlar + earned)
  let d;
  try {
    const res = await fetch(`../api/plan_breakdown.php?ym=${encodeURIComponent(ym)}&operator_id=${r.operator_id}`);
    const txt = await res.text();
    if(!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText} — ${txt}`);
    d = JSON.parse(txt);
  } catch(e) {
    showAlert('Plan breakdown xatosi: ' + e.message); return;
  }

  // 2) Modal HTML: operator + totals
  const op  = d.operator || {};
  const tot = d.totals  || {};
  function fmt(n){ try{return new Intl.NumberFormat('uz-UZ').format(n||0)+' so\'m';}catch(_){return (n||0)+' so\'m';} }

  let html = `
    <div class='mb-2'><strong>${esc(op.name||r.name)}</strong> <span class='text-muted'>(${esc(op.code||r.code)}) — ${esc(op.department||r.department||'')} / ${esc(op.region||r.region||'')}</span></div>
    <div class='row g-2'>
      <div class='col-sm-6'>
        <div class='card border-success'><div class='card-header bg-success text-white'>Asosiy/Net</div><div class='card-body'>
          <div><strong>Asosiy:</strong> ${fmt(tot.base_amount)} ${tot.base_confirmed?'<span class="badge text-bg-success">OK</span>':'<span class="badge text-bg-warning text-dark">Kutilmoqda</span>'}</div>
          <div><strong>Dynamic bonus:</strong> ${fmt(tot.dynamic_bonus)}</div>
          <div class='mt-2'><strong>Gross:</strong> ${fmt(tot.gross)} &nbsp;&nbsp; <strong>Net:</strong> ${fmt(tot.net)}</div>
        </div></div>
      </div>
      <div class='col-sm-6'>
        <div class='card border-info'><div class='card-header bg-info text-white'>Reja bajarilishi</div><div class='card-body'>
          <div>Plan % (avg): <span class="badge ${(tot.avg_pct??0)>=90?'text-bg-success':((tot.avg_pct??0)>=50?'text-bg-warning text-dark':'text-bg-danger')}">${tot.avg_pct??0}%</span></div>
        </div></div>
      </div>
    </div>`;

  // 3) Har bir plan bo'yicha itemlar jadvali (reward + earned bilan)
  (d.plans||[]).forEach(p=>{
    const items = p.items || [];
    let rows = '';
    items.forEach(it=>{
      rows += `
        <tr>
          <td class="fw-semibold">${esc(it.title)}</td>
          <td>${it.target}</td>
          <td><span class="badge text-bg-success">${it.approved}</span></td>
          <td><span class="badge text-bg-warning text-dark">${it.pending}</span></td>
          <td><span class="badge text-bg-danger">${it.rejected}</span></td>
          <td>${(it.reward_amount||0).toLocaleString('uz-UZ')} so‘m</td>
          <td>${esc(it.reward_calc)}${it.reward_allow_over? ' (100%+)':''}</td>
          <td>${Math.round((it.reward_min_pct||0)*100)}%</td>
          <td class="fw-semibold">${(it.earned||0).toLocaleString('uz-UZ')} so‘m</td>
          <td><span class="badge ${(it.pct||0)>=90?'text-bg-success':((it.pct||0)>=50?'text-bg-warning text-dark':'text-bg-danger')}">${it.pct||0}%</span></td>
        </tr>`;
    });

    html += `
      <div class="card mt-3">
        <div class="card-header bg-light">
          <div class="d-flex justify-content-between">
            <div><strong>${esc(p.plan.name)}</strong> <span class="text-muted">(${esc(p.plan.ym)})</span></div>
            <div>Plan %: <span class="badge ${(p.plan_pct??0)>=90?'text-bg-success':((p.plan_pct??0)>=50?'text-bg-warning text-dark':'text-bg-danger')}">${p.plan_pct??0}%</span>
                 &nbsp;&nbsp; Plan earned: <span class="badge text-bg-success">${(p.plan_earned||0).toLocaleString('uz-UZ')} so‘m</span>
            </div>
          </div>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-sm align-middle mb-0">
              <thead class="table-light">
                <tr>
                  <th>Punkt</th><th>Reja</th><th>A</th><th>P</th><th>R</th>
                  <th>Mukofot</th><th>Usul</th><th>Min%</th><th>Earned</th><th>%</th>
                </tr>
              </thead>
              <tbody>${rows || '<tr><td colspan="10" class="text-muted">Punkt yo‘q</td></tr>'}</tbody>
            </table>
          </div>
        </div>
      </div>`;
  });

  document.getElementById('viewBody').innerHTML = html;
  bootstrap.Modal.getOrCreateInstance(document.getElementById('viewModal')).show();
}));


    // charts
    const labels=lastRows.map(x=>x.name), net=lastRows.map(x=>x.net), pen=lastRows.map(x=>x.penalties_total);
    if(netChart) netChart.destroy(); if(penChart) penChart.destroy();
    netChart=new Chart(document.getElementById('chartNet'),{type:'bar',data:{labels,datasets:[{label:"Net (so'm)",data:net}]},options:{plugins:{legend:{display:false}}}});
    penChart=new Chart(document.getElementById('chartPen'),{type:'bar',data:{labels,datasets:[{label:"Jarimalar (so'm)",data:pen}]},options:{plugins:{legend:{display:false}}}});
    updateExportLinks();
  }catch(e){ showAlert('Hisoblash xatosi: '+e.message); }
}

// finalize panel actions
document.getElementById('btnFinAll').addEventListener('click', async ()=>{
  try{
    const ym=document.getElementById('fy').value;
    await fetchJSON('../api/finalize.php?action=finalize_all',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ym})});
    await loadFinalizePanel(); await refresh();
  }catch(e){ showAlert('Finalize ALL: '+e.message); }
});
document.getElementById('btnUnfinAll').addEventListener('click', async ()=>{
  try{
    const ym=document.getElementById('fy').value;
    await fetchJSON('../api/finalize.php?action=unfinalize_all',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ym})});
    await loadFinalizePanel(); await refresh();
  }catch(e){ showAlert('Unfinalize ALL: '+e.message); }
});

document.getElementById('tbl').addEventListener('click', async (e)=>{
  const fin = e.target.closest('.finBtn');
  const sig = e.target.closest('.sigBtn');
  if(fin){
    try{
      const id=parseInt(fin.dataset.id,10), ym=document.getElementById('fy').value;
      const isOn = __finalizeCache[id]?.admin_finalized ?? 0;
      const action = isOn ? 'unfinalize_one' : 'finalize_one';
      await fetchJSON('../api/finalize.php?action='+action,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ym,operator_id:id})});
      await loadFinalizePanel(); await refresh();
    }catch(e){ showAlert('Hisoblangan oyliklar soni: '+e.message); }
  }
  if(sig){
    try{
      const id=parseInt(sig.dataset.id,10), ym=document.getElementById('ym').value;
      const d=await fetchJSON('../api/op_salary_breakdown.php?ym='+encodeURIComponent(ym)+'&operator_id='+id);
      const br=d.breakdown||{}; const box=document.getElementById('sigBody');
      const src = br.operator_signature_path ? (br.operator_signature_path+'?v=' + encodeURIComponent(br.operator_signed_at || Date.now())) : null;
      box.innerHTML = src ? `<img src="${src}" class="img-fluid rounded">` : `<div class="text-muted">Imzo yo‘q</div>`;
      bootstrap.Modal.getOrCreateInstance(document.getElementById('sigModal')).show();
    }catch(e){ showAlert('Imzo ko‘rish: '+e.message); }
  }
});

document.getElementById('mSave').addEventListener('click', async ()=>{
  try{
    const body={ ym:document.getElementById('mYm').value, operator_id:parseInt(document.getElementById('mOpId').value,10), confirm:document.getElementById('mConfirm').checked?1:0, amount:parseInt(document.getElementById('mBaseAmount').value||'0',10)};
    const d=await fetchJSON('../api/set_base_confirm.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
    if(d.ok){ bootstrap.Modal.getOrCreateInstance(document.getElementById('approveModal')).hide(); await refresh(); }
  }catch(e){ showAlert('Asosiy oylik: '+e.message); }
});

document.getElementById('refreshBtn').addEventListener('click', refresh);
document.addEventListener('input', e=>{ if(['ym','fOp','fDept','fReg','fQ'].includes(e.target.id)) updateExportLinks(); });

window.addEventListener('DOMContentLoaded', async ()=>{ await loadOpFilter(); await loadFinalizePanel(); await refresh(); });
</script>
</body>
</html>
