<?php
require_once __DIR__ . '/../config.php';
require_operator();
$u = current_user();
$op_id = (int)($u['operator_id'] ?? 0);
if ($op_id <= 0) { http_response_code(403); exit('Operator bog`lanmagan'); }

$db = contracts_db();
mysqli_set_charset($db,'utf8mb4');
@$db->query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
date_default_timezone_set('Asia/Tashkent');

// operator ma'lumotlari
$op = $db->query("SELECT id, code, name, department, region FROM operators WHERE id={$op_id} LIMIT 1")->fetch_assoc();
$op_code = $op['code'] ?? null;
$op_name = $op['name'] ?? null;
$ym = isset($_GET['ym']) && preg_match('~^\d{4}-\d{2}$~', $_GET['ym']) ? $_GET['ym'] : date('Y-m');
?>
<!doctype html>
<html lang="uz">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Keldi/Ketdi & Jarimalar — Hodim</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}
.small-mono{font:12px ui-monospace,Menlo,Consolas,monospace;color:#6c757d}
.badge-soft{background:#f1f5ff;color:#0d6efd}
</style>
</head>
<body class="bg-light">
<nav class="navbar navbar-dark bg-primary">
  <div class="container">
    <span class="navbar-brand fw-semibold">Keldi/Ketdi & Jarimalar</span>
    <a class="btn btn-outline-light btn-sm" href="./op_dashboard.php">← Kabinet</a>
  </div>
</nav>
<div class="container my-3">
  <div id="alertBox"></div>

  <div class="row g-2 align-items-end mb-3">
    <div class="col-sm-4">
      <label class="form-label">Oy</label>
      <input id="fYm" type="month" class="form-control" value="<?php echo htmlspecialchars($ym); ?>">
    </div>
    <div class="col-sm-5">
      <label class="form-label">Operator</label>
      <input class="form-control" value="<?php echo htmlspecialchars(($op['name']??'').' ('.($op['code']??'').')'); ?>" disabled>
    </div>
    <div class="col-sm-3 d-grid">
      <label class="form-label"> </label>
      <button class="btn btn-primary" id="btnRun">Hisoblash</button>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-lg-5">
      <div class="card">
        <div class="card-header bg-light fw-semibold">Keldi/Ketdi — oylik umumiy</div>
        <div class="card-body" id="attSummary">
          <div class="text-muted">Hisoblanmoqda…</div>
        </div>
      </div>
      <div class="card mt-3">
        <div class="card-header bg-light fw-semibold">Jarimalar (batafsil)</div>
        <div class="card-body" id="penBox">
          <div class="text-muted">Yuklanmoqda…</div>
        </div>
      </div>
    </div>
    <div class="col-lg-7">
      <div class="card">
        <div class="card-header bg-light fw-semibold">Kunlik tafsilot</div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-sm table-bordered mb-0 table-sticky" id="tblDays">
              <thead class="table-light">
                <tr>
                  <th>Sana</th>
                  <th class="text-center">Holat</th>
                  <th class="text-end">Kechikish (min)</th>
                  <th class="text-end">Ish vaqti (soat)</th>
                  <th class="text-end">Jarima</th>
                  <th class="text-end">Bonus</th>
                  <th>Izoh</th>
                </tr>
              </thead>
              <tbody></tbody>
              <tfoot class="table-light">
                <tr>
                  <th>Jami</th>
                  <th></th>
                  <th class="text-end" id="tLate">0</th>
                  <th class="text-end" id="tWorked">0</th>
                  <th class="text-end" id="tPen">0</th>
                  <th class="text-end" id="tBon">0</th>
                  <th></th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

<script>
const OP_ID  = <?php echo (int)$op_id; ?>;
const OP_CODE = <?php echo json_encode($op_code, JSON_UNESCAPED_UNICODE); ?>;

function esc(s){ return (s||'').toString().replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m])); }
function fmtUZS(n){ n=Math.round(n||0); return n.toLocaleString('uz-UZ')+' so\'m'; }
function showAlert(msg,type='info'){ const b=document.getElementById('alertBox'); b.innerHTML=`<div class="alert alert-${type}">${esc(msg)}</div>`; setTimeout(()=>b.innerHTML='',4000); }

async function fetchJSON(url,opts){ const r=await fetch(url,opts||{}); const t=await r.text(); try{ return JSON.parse(t); }catch{ throw new Error('API noto\'g\'ri javob: '+t.slice(0,200)); } }

function minsToHrs(m){ const h=Math.floor(m/60); const mm=m%60; return h+':' + String(mm).padStart(2,'0'); }

async function loadAll(){
  const ym = document.getElementById('fYm').value || (new Date()).toISOString().slice(0,7);

  // 1) Attendance (employee_month_calc)
  let att = null;
  try{
    const url = '../api/attendance.php?action=employee_month_calc&ym=' + encodeURIComponent(ym) + '&emp_code=' + encodeURIComponent(OP_CODE||'');
    att = await fetchJSON(url);
  }catch(e){ showAlert('Keldi/ketdi ma\'lumotini olishda xato: '+e.message,'danger'); }

  if(att && att.ok){
    const s = att.summary || {};
    const days = att.days || [];
    // Summary box
    document.getElementById('attSummary').innerHTML = `
      <div class="row g-2">
        <div class="col-6"><div class="border rounded p-2"><div class="text-muted small">Kelgan kunlar</div><div class="fs-5">${(s.present_days??0)}</div></div></div>
        <div class="col-6"><div class="border rounded p-2"><div class="text-muted small">Kelmagan kunlar</div><div class="fs-5">${(s.absent_days??0)}</div></div></div>
        <div class="col-6"><div class="border rounded p-2"><div class="text-muted small">Kechikish (min)</div><div class="fs-5">${(s.late_min??0)}</div></div></div>
        <div class="col-6"><div class="border rounded p-2"><div class="text-muted small">Ish vaqti (soat)</div><div class="fs-5">${minsToHrs(s.worked_min||0)}</div></div></div>
        <div class="col-6"><div class="border rounded p-2"><div class="text-muted small">Jarima (keldi/ketdi)</div><div class="fs-5">${fmtUZS(s.penalty||0)}</div></div></div>
        <div class="col-6"><div class="border rounded p-2"><div class="text-muted small">Bonus (keldi/ketdi)</div><div class="fs-5">${fmtUZS(s.bonus||0)}</div></div></div>
      </div>
      <div class="small-mono mt-2 text-muted">Jadval: dushanba–yakshanba ish kunlari va kechikish stavkalari attendance sozlamalaridan olinadi.</div>
    `;

    // Days table
    const tb = document.querySelector('#tblDays tbody');
    tb.innerHTML = '';
    let sumLate=0, sumWorked=0, sumPen=0, sumBon=0;
    days.forEach(d=>{
      sumLate += (d.late_min||0);
      sumWorked += (d.worked_min||0);
      sumPen += (d.penalty||0);
      sumBon += (d.bonus||0);
      const status = (d.absent ? '<span class="badge text-bg-danger">Kelmagan</span>' : '<span class="badge text-bg-success">Kelgan</span>') + (d.excused? ' <span class="badge badge-soft">Sababli</span>':'');
      const note = esc(d.note||'');
      const dayStr = esc(d.day || '');
      tb.insertAdjacentHTML('beforeend', `
        <tr>
          <td>${dayStr}</td>
          <td class="text-center">${status}</td>
          <td class="text-end">${(d.late_min||0)}</td>
          <td class="text-end">${minsToHrs(d.worked_min||0)}</td>
          <td class="text-end">${fmtUZS(d.penalty||0)}</td>
          <td class="text-end">${fmtUZS(d.bonus||0)}</td>
          <td>${note}</td>
        </tr>
      `);
    });
    document.getElementById('tLate').textContent = sumLate;
    document.getElementById('tWorked').textContent = minsToHrs(sumWorked);
    document.getElementById('tPen').textContent = fmtUZS(sumPen);
    document.getElementById('tBon').textContent = fmtUZS(sumBon);
  }else{
    document.getElementById('attSummary').innerHTML = '<div class="text-danger">Ma\'lumot topilmadi</div>';
  }

  // 2) Penalties (manual + metrics-based) via op_penalties.php
  let pen=null;
  try{
    pen = await fetchJSON('../api/op_penalties.php?ym=' + encodeURIComponent(ym));
  }catch(e){
    document.getElementById('penBox').innerHTML = '<div class="text-danger">Jarimalarni olishda xatolik: '+esc(e.message)+'</div>';
    pen=null;
  }
  if(pen && pen.ok){
    const m = pen.metrics||{};
    const att = pen.attendance_penalties || {};
    const items = pen.items || [];
    const attRows = Object.keys(att).map(k=>({reason:k, amount:att[k]||0}));
    const itemsRows = items.map(it=>({reason:(it.reason||'-'), amount:(it.amount||0), created_at: it.created_at||''}));

    const attHtml = attRows.length ? attRows.map(p=>`<tr><td>${esc(p.reason)}</td><td class="text-end">${fmtUZS(p.amount)}</td></tr>`).join('') : '<tr><td colspan="2" class="text-muted">Keldi/ketdi bo\'yicha jarima yo\'q</td></tr>';
    const itemsHtml = itemsRows.length ? itemsRows.map(p=>`<tr><td>${esc(p.reason)}</td><td class="text-end">${fmtUZS(p.amount)}</td><td class="text-nowrap small">${esc(p.created_at||'')}</td></tr>`).join('') : '<tr><td colspan="3" class="text-muted">Qo\'shimcha jarima yo\'q</td></tr>';

    document.getElementById('penBox').innerHTML = `
      <div class="row g-3">
        <div class="col-md-6">
          <div class="border rounded p-2">
            <div class="fw-semibold mb-2">Keldi/ketdi bo\'yicha</div>
            <div class="table-responsive"><table class="table table-sm"><thead class="table-light"><tr><th>Sabab</th><th class="text-end">Summasi</th></tr></thead><tbody>${attHtml}</tbody></table></div>
          </div>
        </div>
        <div class="col-md-6">
          <div class="border rounded p-2">
            <div class="fw-semibold mb-2">Qo\'shimcha (admin qo\'shgan)</div>
            <div class="table-responsive"><table class="table table-sm"><thead class="table-light"><tr><th>Sabab</th><th class="text-end">Summasi</th><th>Sana</th></tr></thead><tbody>${itemsHtml}</tbody></table></div>
          </div>
        </div>
      </div>
      <div class="row g-2 mt-2">
        <div class="col-sm-4"><div class="border rounded p-2"><div class="text-muted small">Jami keldi/ketdi jarimalari</div><div class="fs-5">${fmtUZS(pen.attendance_total||0)}</div></div></div>
        <div class="col-sm-4"><div class="border rounded p-2"><div class="text-muted small">Jami qo\'shimcha jarimalar</div><div class="fs-5">${fmtUZS(pen.items_total||0)}</div></div></div>
        <div class="col-sm-4"><div class="border rounded p-2"><div class="text-muted small">Birga (oy bo\'yicha)</div><div class="fs-5">${fmtUZS(pen.total||0)}</div></div></div>
      </div>
      <div class="small-mono mt-2 text-muted">* Admin kiritgan qo\'shimcha jarimalar (operator_penalties) faqat o\'qish uchun ko\'rsatiladi.</div>
    `;
  }else{
    document.getElementById('penBox').innerHTML = '<div class="text-muted">Jarimalar topilmadi</div>';
  }
}

document.getElementById('btnRun').addEventListener('click', loadAll);
document.addEventListener('DOMContentLoaded', loadAll);
</script>
</body></html>
