<?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>Jarimalar (Admin)</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<nav class="navbar navbar-dark bg-primary">
  <div class="container">
    <a class="navbar-brand" href="#">Jarimalar boshqaruvi</a>
    <a class="btn btn-outline-light btn-sm" href="./dashboard.php">Dashboard</a>
  </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">
        <div class="col-sm-3">
          <label class="form-label">Oy</label>
          <input type="month" id="ym" class="form-control" value="<?php echo date('Y-m'); ?>">
        </div>
        <div class="col-sm-6">
          <label class="form-label">Operator</label>
          <select id="op" class="form-select"></select>
        </div>
        <div class="col-sm-3 d-flex align-items-end justify-content-end">
          <button class="btn btn-primary w-100" id="btnLoad">Yuklash</button>
        </div>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-lg-6">
      <div class="card">
        <div class="card-header bg-light">Hisob (operator_monthly_metrics)</div>
        <div class="card-body">
          <div class="row g-2">
            <div class="col-6"><label class="form-label">Asosiy oylik</label><input id="base_amount" type="number" class="form-control" value="0"></div>
            <div class="col-6"><label class="form-label">Base tasdiqlangan</label><select id="base_confirmed" class="form-select"><option value="0">Yo‘q</option><option value="1">Ha</option></select></div>
            <div class="col-6"><label class="form-label">Kechikish (daq)</label><input id="late_minutes" type="number" class="form-control" value="0"></div>
            <div class="col-6"><label class="form-label">Kelmaslik (kun)</label><input id="absent_days" type="number" class="form-control" value="0"></div>
            <div class="col-6"><label class="form-label">Yomon aloqa</label><input id="bad_comm_count" type="number" class="form-control" value="0"></div>
            <div class="col-6"><label class="form-label">Ma’lumot yetishmasligi</label><input id="missing_info_count" type="number" class="form-control" value="0"></div>
            <div class="col-6"><label class="form-label">Boshqa jarima</label><input id="other_penalty" type="number" class="form-control" value="0"></div>
            <div class="col-6"><label class="form-label">Boshqa bonus</label><input id="other_bonus" type="number" class="form-control" value="0"></div>
            <div class="col-6"><label class="form-label">Admin finalized</label><select id="admin_finalized" class="form-select"><option value="0">Yo‘q</option><option value="1">Ha</option></select></div>
          </div>
          <div class="text-end mt-3"><button class="btn btn-success" id="btnSaveMetrics">Saqlash</button></div>
        </div>
      </div>
    </div>

    <div class="col-lg-6">
      <div class="card">
        <div class="card-header bg-light">Qo‘shimcha jarimalar (operator_penalties)</div>
        <div class="card-body">
          <div class="d-flex gap-2 mb-2">
            <input id="pReason" class="form-control" placeholder="Sabab (masalan: mijozga qattiq gap)">
            <input id="pAmount" class="form-control" type="number" placeholder="Summasi" value="0">
            <button class="btn btn-outline-primary" id="btnAddPen">+ Qo‘shish</button>
          </div>
          <div class="table-responsive">
            <table class="table table-sm" id="tblPen">
              <thead class="table-light"><tr><th>Sabab</th><th class="text-end">Summasi</th><th style="width:130px">Amal</th></tr></thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<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 loadOps(){
  try{
    const r=await fetch('../api/operators.php'); const d=await r.json();
    const sel=document.getElementById('op'); sel.innerHTML='';
    (d||[]).forEach(o=>{
      const opt=document.createElement('option');
      opt.value=o.id; opt.textContent=`#${o.id} — ${o.name||''}`;
      sel.appendChild(opt);
    });
  }catch(e){ show('Operatorlar olinmadi: '+e.message,'danger'); }
}
async function loadSummary(){
  const ym=document.getElementById('ym').value;
  const op_id=parseInt(document.getElementById('op').value,10);
  if(!op_id){ show('Operator tanlang','warning'); return; }
  try{
    const r=await fetch(`../api/penalties.php?action=summary&ym=${encodeURIComponent(ym)}&operator_id=${op_id}`);
    const d=await r.json();
    if(!d.ok){ show('API xato: '+(d.error||''),'danger'); return; }
    const m=d.metrics||{};
    ['base_amount','base_confirmed','late_minutes','absent_days','bad_comm_count','missing_info_count','other_penalty','other_bonus','admin_finalized'].forEach(k=>{
      const el=document.getElementById(k); if(!el) return;
      const v=(m[k]!==undefined&&m[k]!==null)?m[k]:'';
      el.value = (el.type==='number' || el.type==='select-one') ? v : v;
      if(el.tagName==='SELECT'){ el.value = String(v||0); }
    });

    const tb=document.querySelector('#tblPen tbody'); tb.innerHTML='';
    (d.items||[]).forEach(it=>{
      const tr=document.createElement('tr');
      tr.innerHTML=`
        <td><input class="form-control form-control-sm pReason" value="${esc(it.reason)}"></td>
        <td><input class="form-control form-control-sm text-end pAmount" type="number" value="${it.amount||0}"></td>
        <td class="text-end">
          <button class="btn btn-sm btn-outline-success me-1 btnSave" data-id="${it.id}">Saqlash</button>
          <button class="btn btn-sm btn-outline-danger btnDel" data-id="${it.id}">O‘chirish</button>
        </td>`;
      tb.appendChild(tr);
    });
  }catch(e){ show('Summary xatosi: '+e.message,'danger'); }
}
document.getElementById('btnLoad').addEventListener('click', loadSummary);
document.getElementById('btnSaveMetrics').addEventListener('click', async ()=>{
  const ym=document.getElementById('ym').value; const op_id=parseInt(document.getElementById('op').value,10);
  const body={
    ym, operator_id:op_id,
    base_amount:parseInt(base_amount.value||'0',10),
    base_confirmed:parseInt(base_confirmed.value||'0',10),
    late_minutes:parseInt(late_minutes.value||'0',10),
    absent_days:parseInt(absent_days.value||'0',10),
    bad_comm_count:parseInt(bad_comm_count.value||'0',10),
    missing_info_count:parseInt(missing_info_count.value||'0',10),
    other_penalty:parseInt(other_penalty.value||'0',10),
    other_bonus:parseInt(other_bonus.value||'0',10),
    admin_finalized:parseInt(admin_finalized.value||'0',10)
  };
  try{
    const r=await fetch('../api/penalties.php?action=save_metrics',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
    const d=await r.json(); if(!d.ok){ show('Saqlash xatosi: '+(d.error||''),'danger'); return; }
    show('Metrics saqlandi','success');
  }catch(e){ show('Saqlash xatosi: '+e.message,'danger'); }
});
document.getElementById('btnAddPen').addEventListener('click', async ()=>{
  const ym=document.getElementById('ym').value; const op_id=parseInt(document.getElementById('op').value,10);
  const reason=document.getElementById('pReason').value.trim(); const amount=parseInt(document.getElementById('pAmount').value||'0',10);
  if(!reason){ show('Sabab kiriting','warning'); return; }
  try{
    const r=await fetch('../api/penalties.php?action=add_item',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ym,operator_id:op_id,reason,amount})});
    const d=await r.json(); if(!d.ok){ show('Qo‘shish xatosi: '+(d.error||''),'danger'); return; }
    document.getElementById('pReason').value=''; document.getElementById('pAmount').value='0';
    loadSummary();
  }catch(e){ show('Qo‘shish xatosi: '+e.message,'danger'); }
});
document.getElementById('tblPen').addEventListener('click', async (e)=>{
  const btn=e.target.closest('button'); if(!btn) return;
  const id=parseInt(btn.dataset.id,10);
  if(btn.classList.contains('btnSave')){
    const tr=btn.closest('tr');
    const reason=tr.querySelector('.pReason').value.trim();
    const amount=parseInt(tr.querySelector('.pAmount').value||'0',10);
    const r=await fetch('../api/penalties.php?action=update_item',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,reason,amount})});
    const d=await r.json(); if(!d.ok){ show('Saqlash xatosi: '+(d.error||''),'danger'); return; }
    show('Yangilandi','success');
  }else if(btn.classList.contains('btnDel')){
    if(!confirm('O‘chirsinmi?')) return;
    const r=await fetch('../api/penalties.php?action=delete_item',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});
    const d=await r.json(); if(!d.ok){ show('O‘chirish xatosi: '+(d.error||''),'danger'); return; }
    btn.closest('tr').remove(); show('O‘chirildi','success');
  }
});
(async function init(){ await loadOps(); })();
</script>
</body>
</html>
