<?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>

<!-- Row view -->
<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 modal (ko‘rish + rad qilish) -->
<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 class="modal-footer" id="sigFooter"><button class="btn btn-secondary" data-bs-dismiss="modal">Yopish</button></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,300)}`); try{return JSON.parse(t);}catch(e){throw new Error('JSON xato: '+t.slice(0,300));} }

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?` (${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(){
  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 isFinal = (__finalizeCache[r.operator_id]?.admin_finalized ?? r.admin_finalized) ? 1:0;
      const hasSig  = !!((__finalizeCache[r.operator_id]?.operator_signature_path ?? r.operator_signature_path));
      const fin = isFinal ? "<span class='badge text-bg-success'>Hisoblandi</span>" : "<span class='badge text-bg-secondary'>Hisoblanmagan</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 sigHtml = hasSig
        ? `<button class="btn btn-sm btn-outline-secondary sigViewBtn" data-id="${r.operator_id}">Ko‘rish</button>`
        : `<span class="badge text-bg-secondary">Imzo yo‘q</span>`;

      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>${sigHtml}</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);
    });

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

    // Row details (plan breakdown)
    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;
      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; }

      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>`;

      (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>`;
      });

      viewBody.innerHTML = html;
      bootstrap.Modal.getOrCreateInstance(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(chartNet,{type:'bar',data:{labels,datasets:[{label:"Net (so'm)",data:net}]},options:{plugins:{legend:{display:false}}}});
    penChart=new Chart(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
btnFinAll.addEventListener('click', async ()=>{
  try{
    const ym=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); }
});
btnUnfinAll.addEventListener('click', async ()=>{
  try{
    const ym=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); }
});

// Jadval ustida: finalize / imzo ko‘rish
document.getElementById('tbl').addEventListener('click', async (e)=>{
  const target = e.target;
  const fin = target.closest('.finBtn');
  const viewBtn = target.closest('.sigViewBtn');
  const ym = ymInput.value;

  if(fin){
    try{
      const id=parseInt(fin.dataset.id,10), y=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:y,operator_id:id})});
      await loadFinalizePanel(); await refresh();
    }catch(e){ showAlert('Finalize: '+e.message); }
  }

  if(viewBtn){
    try{
      const id=parseInt(viewBtn.dataset.id,10);
      const d=await fetchJSON('../api/op_salary_breakdown.php?ym='+encodeURIComponent(ym)+'&operator_id='+id);
      const br=d.breakdown||{}; const body=document.getElementById('sigBody'); const foot=document.getElementById('sigFooter');
      const src = br.operator_signature_path ? (br.operator_signature_path+'?v=' + encodeURIComponent(br.operator_signed_at || Date.now())) : null;

      // Modal body
      body.innerHTML = src ? `<img src="/oylik2/public${src}" class="img-fluid rounded border"> <div class="text-muted mt-2">${esc(br.operator_signed_at||'')}</div>`
                           : `<div class="alert alert-secondary mb-0">Imzo yo‘q</div>`;

      // Modal footer: faqat modal ichida “Rad qilish”
      foot.innerHTML = src
        ? `<button class="btn btn-outline-danger" id="btnSigReject" data-id="${id}" data-ym="${esc(ym)}">Imzoni rad qilish</button>
           <button class="btn btn-secondary" data-bs-dismiss="modal">Yopish</button>`
        : `<button class="btn btn-secondary" data-bs-dismiss="modal">Yopish</button>`;

      bootstrap.Modal.getOrCreateInstance(sigModal).show();

      // Rad qilish — tasdiqlashsiz darhol
      document.getElementById('btnSigReject')?.addEventListener('click', async ()=>{
        try{
          await fetchJSON('../api/signoff.php?action=admin_reject',{
            method:'POST',headers:{'Content-Type':'application/json'},
            body: JSON.stringify({ym,operator_id:id,reason:''})
          });
          showAlert('Imzo rad qilindi','success');
          bootstrap.Modal.getOrCreateInstance(sigModal).hide();
          await loadFinalizePanel(); await refresh();
        }catch(err){ showAlert('Rad qilish xatosi: '+err.message); }
      });

    }catch(e){ showAlert('Imzo ko‘rish: '+e.message); }
  }
});

// Approve save
mSave.addEventListener('click', async ()=>{
  try{
    const body={ ym:mYm.value, operator_id:parseInt(mOpId.value,10), confirm:mConfirm.checked?1:0, amount:parseInt(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(approveModal).hide(); await refresh(); }
  }catch(e){ showAlert('Asosiy oylik: '+e.message); }
});

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

const ymInput=document.getElementById('ym');
const approveModal=document.getElementById('approveModal');
const viewModal=document.getElementById('viewModal');
const sigModal=document.getElementById('sigModal');
const chartNet=document.getElementById('chartNet');
const chartPen=document.getElementById('chartPen');
const mOpId=document.getElementById('mOpId');
const mOpName=document.getElementById('mOpName');
const mBaseAmount=document.getElementById('mBaseAmount');
const mConfirm=document.getElementById('mConfirm');
const mYm=document.getElementById('mYm');

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