<?php require_once __DIR__ . '/../config.php'; require_operator(); ?>
<!doctype html>
<html lang="uz">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mening rejalrim</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.progress-sm { height: 8px; }
.card-plan:hover { box-shadow:0 6px 18px rgba(0,0,0,.08); transition:.2s; }
.badge-soft { background:#f1f5ff; color:#0d6efd; }
.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:#1e90ff;">
  <div class="container">
    <a class="navbar-brand fw-bold" href="./op_dashboard.php">Hodim portali</a>
    <ul class="navbar-nav ms-auto">
      <li class="nav-item"><a class="nav-link " href="./op_dashboard.php">Dashboard</a></li>
      <li class="nav-item"><a class="nav-link active" href="./op_plans.php">Mening rejalarim</a></li>
       <li class="nav-item"><a class="nav-link" href="./operator_sign.php">Mening shartnomalarim</a></li>
      <li class="nav-item"><a class="nav-link" href="./logout.php">Chiqish</a></li>
    </ul>
  </div>
</nav>

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

  <div class="d-flex align-items-end gap-2 mb-3">
    <div><label class="form-label">Oy</label><input type="month" id="ym" class="form-control" value="<?php echo date('Y-m'); ?>"></div>
    <button class="btn btn-primary" id="refresh">Yuklash</button>
  </div>

  <div id="list" class="row g-3"></div>
</div>

<!-- Plan detail modal -->
<div class="modal fade" id="planModal" 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" id="pmTitle">Plan</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
      <div id="pmBody"></div>
    </div>
    <div class="modal-footer">
      <a class="btn btn-outline-primary" href="./op_dashboard.php">Dalil yuborish</a>
      <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>
function esc(s){ return (s||'').replace(/[&<>"']/g, m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;' }[m])); }
function badgePct(p){ p=+p||0; return (p>=90)?'text-bg-success':(p>=50?'text-bg-warning text-dark':'text-bg-danger'); }
function showAlert(msg, type='danger'){ const box=document.getElementById('alertBox'); box.innerHTML=`<div class="alert alert-${type}">${esc(msg)}</div>`; setTimeout(()=>box.innerHTML='',5000); }

document.getElementById('refresh').addEventListener('click', loadPlans);

async function safeJSON(url, opts){
  const res = await fetch(url, opts);
  const text = await res.text();
  if(!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText} — ${text.slice(0,200)}`);
  try { return JSON.parse(text); } catch(e){ throw new Error('JSON parse xatosi: '+text.slice(0,200)); }
}

async function loadPlans(){
  const ym = document.getElementById('ym').value;
  try{
    // operatorga biriktirilgan planlar (oy bo‘yicha) + foiz/sonlar
    const d = await safeJSON('../api/op_my_plans.php?ym=' + encodeURIComponent(ym));
    const row = document.getElementById('list'); row.innerHTML='';
    (d.plans||[]).forEach(p=>{
      const pct = p.plan_pct ?? 0;
      const counts = p.plan_counts || {approved:0,pending:0,rejected:0,total:0};
      const col=document.createElement('div'); col.className='col-md-6';
      col.innerHTML=`
        <div class="card card-plan shadow-sm">
          <div class="card-body">
            <div class="d-flex justify-content-between">
              <div><span class="badge badge-soft">${d.ym}</span> <strong>${esc(p.plan.name)}</strong></div>
              <div><span class="badge ${badgePct(pct)}">${pct}%</span></div>
            </div>
            <div class="progress progress-sm mt-2"><div class="progress-bar ${pct>=90?'bg-success':(pct>=50?'bg-warning':'bg-danger')}" style="width:${pct}%"></div></div>
            <div class="mt-2">
              <span class="badge text-bg-success me-1">Approved: ${counts.approved}</span>
              <span class="badge text-bg-warning text-dark me-1">Pending: ${counts.pending}</span>
              <span class="badge text-bg-danger">Rejected: ${counts.rejected}</span>
            </div>
            <div class="text-end mt-2">
              <button class="btn btn-sm btn-outline-success" data-action="view" data-id="${p.plan.id}" data-name="${esc(p.plan.name)}">Ko‘rish</button>
            </div>
          </div>
        </div>`;
      row.appendChild(col);
    });
  }catch(e){ showAlert('Rejalar ro‘yxatini olishda xato: '+e.message); }
}

// Delegation: “Ko‘rish”
document.addEventListener('click', async (e)=>{
  const btn = e.target.closest('button[data-action=view]');
  if(!btn) return;

  const plan_id = parseInt(btn.dataset.id,10);
  const plan_name = btn.dataset.name || 'Plan';
  const ym = document.getElementById('ym').value;

  document.getElementById('pmTitle').textContent = plan_name;

  try{
    // 1) Plan + items (alias), fallback -> list_items
    let items = [];
    try{
      const A = await safeJSON('../api/plans.php?action=list&plan_id=' + plan_id);
      items = (A && A.items) ? A.items : [];
    }catch(e1){
      // fallback: faqat itemlar
      const B = await safeJSON('../api/plans.php?action=list_items&plan_id=' + plan_id);
      items = B.items || [];
    }

    // 2) Shu oy topshirilgan dalillar (operator scope)
    const S = await safeJSON('../api/submissions.php?action=list&ym=' + encodeURIComponent(ym));
    const subs = S.rows || [];

    // 3) Jadval HTML
    let html = `
      <div class="table-responsive">
        <table class="table table-sm align-middle mb-0 table-sticky">
          <thead class="table-light">
            <tr>
              <th>Punkt</th><th>Reja</th><th>Approved</th><th>Pending</th><th>Rejected</th><th>% (approved/target)</th>
            </tr>
          </thead>
          <tbody>`;

    items.forEach(it=>{
      const ap = subs.filter(x=> x.item_id==it.id && x.status==='approved').length;
      const pe = subs.filter(x=> x.item_id==it.id && x.status==='pending').length;
      const re = subs.filter(x=> x.item_id==it.id && x.status==='rejected').length;
      const tgt= parseInt(it.target_int||0,10);
      const pct= tgt>0 ? Math.round(ap*1000/tgt)/10 : 0;
      html += `
        <tr>
          <td class="fw-semibold">${esc(it.title)}</td>
          <td>${tgt}</td>
          <td><span class="badge text-bg-success">${ap}</span></td>
          <td><span class="badge text-bg-warning text-dark">${pe}</span></td>
          <td><span class="badge text-bg-danger">${re}</span></td>
          <td><span class="badge ${badgePct(pct)}">${pct}%</span></td>
        </tr>`;
    });

    html += `</tbody></table></div>
      <div class="mt-3 text-muted small">Dalillarni topshirish uchun: “Dalil yuborish” bo‘limidan foydalaning (Dashboard).</div>`;

    document.getElementById('pmBody').innerHTML = html;
    bootstrap.Modal.getOrCreateInstance(document.getElementById('planModal')).show();

  }catch(e){
    showAlert('Ko‘rish modalini tayyorlashda xato: '+e.message);
  }
});

document.getElementById('refresh').addEventListener('click', loadPlans);
window.addEventListener('DOMContentLoaded', loadPlans);
</script>
</body>
</html>
