<?php
require_once __DIR__ . '/../config.php';
if (function_exists('require_operator')) {
  require_operator();
} elseif (function_exists('require_login')) {
  require_login();
}
?>
<!doctype html>
<html lang="uz">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mening shartnomalarim — Imzolash/Ko‘rish</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.badge-status{font-weight:600}
.badge-status.pending{background:#fff3cd;color:#664d03}
.badge-status.signed{background:#d1e7dd;color:#0f5132}
.code-mono{font-family:ui-monospace,Menlo,Consolas,monospace}
.table-sticky thead th{position:sticky;top:0;background:#fff;z-index:2}

/* Imzo pad: mobil va planshet uchun to‘liq tayyor */
.sig-pad{
  border:1px dashed #adb5bd;border-radius:.5rem;background:#fff;
  height:180px; cursor:crosshair;
  touch-action:none; -ms-touch-action:none;
  user-select:none; -webkit-user-select:none; -webkit-touch-callout:none;
}
.sig-pad canvas{display:block; width:100%; height:100%;}
.sig-tools .btn{padding:.25rem .5rem}
</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="#">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" href="./op_plans.php">Mening rejalarim</a></li>
      <li class="nav-item"><a class="nav-link active" href="./contracts.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="card shadow-sm">
    <div class="card-header bg-light">
      <ul class="nav nav-tabs card-header-tabs">
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#panePending" type="button">Kutilmoqda</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#paneSigned" type="button">Imzolangan</button></li>
      </ul>
    </div>
    <div class="card-body">
      <div class="row g-2 mb-2">
        <div class="col-md-8">
          <input id="q" class="form-control" placeholder="Qidirish: shartnoma / plan">
        </div>
        <div class="col-md-4 text-end">
          <button id="btnReload" class="btn btn-outline-primary">Yangilash</button>
        </div>
      </div>

      <div class="tab-content">
        <!-- Pending tab -->
        <div class="tab-pane fade show active" id="panePending">
          <div class="table-responsive">
            <table class="table table-sm align-middle table-sticky" id="tblPending">
              <thead class="table-light">
                <tr><th>Vaqt</th><th>Shartnoma</th><th>Plan</th><th class="text-center">Holat</th><th style="width:160px">Amal</th></tr>
              </thead><tbody></tbody>
            </table>
          </div>
          <div class="d-flex justify-content-between">
            <div class="text-muted small" id="pSum">Ko‘rsatilmoqda: 0–0 / Jami: 0</div>
            <ul class="pagination pagination-sm mb-0" id="pPager"></ul>
          </div>
        </div>

        <!-- Signed tab -->
        <div class="tab-pane fade" id="paneSigned">
          <div class="table-responsive">
            <table class="table table-sm align-middle table-sticky" id="tblSigned">
              <thead class="table-light">
                <tr><th>Vaqt</th><th>Shartnoma</th><th>Plan</th><th class="text-center">Holat</th><th style="width:120px">Amal</th></tr>
              </thead><tbody></tbody>
            </table>
          </div>
          <div class="d-flex justify-content-between">
            <div class="text-muted small" id="sSum">Ko‘rsatilmoqda: 0–0 / Jami: 0</div>
            <ul class="pagination pagination-sm mb-0" id="sPager"></ul>
          </div>
        </div>

      </div>
    </div>
  </div>
</div>

<!-- VIEW/SIGN MODAL -->
<div class="modal fade" id="signModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">Shartnoma</h5>
      <button class="btn-close" data-bs-dismiss="modal"></button>
    </div>
    <div class="modal-body">
      <div id="signAlert"></div>
      <div id="cInfo" class="mb-3"></div>
      <div id="cItems" class="mb-3"></div>
      <div id="cAtts" class="mb-3"></div>
      <div id="cNote" class="mb-3"></div>

      <!-- READ-ONLY (SIGNED) -->
      <div class="card d-none" id="sigReadonly">
        <div class="card-header bg-light">Imzo (ko‘rish)</div>
        <div class="card-body" id="cSigView">
          <div class="text-muted">Imzo ma’lumoti topilmadi.</div>
        </div>
      </div>

      <!-- SIGN UI (PENDING) -->
      <div class="card mt-3" id="signCard">
        <div class="card-header bg-light">Imzo qo‘yish</div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Typed ism-familya</label>
              <input id="typedName" class="form-control" placeholder="Masalan: Ali Valiyev">
            </div>
            <div class="col-md-6">
              <label class="form-label">Rozilik</label>
              <div class="form-check">
                <input class="form-check-input" type="checkbox" id="agree">
                <label class="form-check-label" for="agree">Men shartnoma shartlari bilan tanishdim va roziman</label>
              </div>
            </div>
            <div class="col-12">
              <label class="form-label mb-1">Chizib qo‘yiladigan imzo</label>
              <div class="sig-pad" id="sigPad"></div>
              <div class="sig-tools mt-2 d-flex gap-2">
                <button class="btn btn-sm btn-outline-secondary" id="btnClear" type="button">Tozalash</button>
                <button class="btn btn-sm btn-outline-secondary" id="btnUndo" type="button">Ortga qaytarish</button>
                <span class="text-muted small">Telefon/planwet/kompyuterda barmoq/stilus/sichqoncha bilan chizing</span>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" data-bs-dismiss="modal">Yopish</button>
      <button class="btn btn-primary" id="btnSign">Imzolash</button>
    </div>
  </div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
/* ==== helpers ==== */
function esc(s){ return (s||'').replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;'}[m])); }
function showAlert(boxId, msg, type='danger'){ const b=document.getElementById(boxId); b.innerHTML=`<div class="alert alert-${type} mb-2">${esc(msg)}</div>`; setTimeout(()=>b.innerHTML='',5000); }
function fmtRange(total,page,limit){ const start=total?((page-1)*limit+1):0; const end=total?Math.min(total,page*limit):0; const pages=Math.max(1,Math.ceil(total/limit)); return {start,end,pages}; }

/* ==== lists ==== */
let pageP=1, pageS=1, limit=10, curId=0, needSign=0;

async function loadList(status){
  const page = status==='pending'?pageP:pageS;
  const q = document.getElementById('q').value.trim();
  const url = `../api/contracts.php?action=list&status=${status}&mine=1&page=${page}&limit=${limit}${q?`&q=${encodeURIComponent(q)}`:''}`;
  const r = await fetch(url); const d = await r.json();
  const rows=d.rows||[], total=d.total||0;
  const {start,end,pages} = fmtRange(total,page,limit);

  const tb = document.querySelector(status==='pending' ? '#tblPending tbody' : '#tblSigned tbody');
  tb.innerHTML='';
  rows.forEach(x=>{
    const when=(x.created_at||'').replace('T',' ').slice(0,19);
    const badge = `<span class="badge badge-status ${status}">${status}</span>`;
    const tr=document.createElement('tr');
    tr.innerHTML=`
      <td class="code-mono">${esc(when)}</td>
      <td><div class="fw-semibold">${esc(x.title||'-')}</div><div class="text-muted small">${esc(x.ym||'')}</div></td>
      <td>${esc(x.plan_name||'-')}</td>
      <td class="text-center">${badge}</td>
      <td>
        ${status==='pending'
          ? `<button class="btn btn-sm btn-primary" data-view="${x.id}">Ko‘rish / Imzolash</button>`
          : `<button class="btn btn-sm btn-outline-secondary" data-view="${x.id}">Ko‘rish</button>`
        }
      </td>`;
    tb.appendChild(tr);
  });

  const sumEl = document.getElementById(status==='pending'?'pSum':'sSum');
  const pgEl  = document.getElementById(status==='pending'?'pPager':'sPager');
  sumEl.textContent = `Ko‘rsatilmoqda: ${start}–${end} / Jami: ${total}`;
  pgEl.innerHTML='';

  const liPrev=document.createElement('li');
  liPrev.className='page-item'+((page<=1)?' disabled':''); liPrev.innerHTML=`<a class="page-link" href="#" data-nav="prev">Orqaga</a>`;
  const liRange=document.createElement('li');
  liRange.className='page-item disabled'; liRange.innerHTML=`<span class="page-link">${start}–${end}</span>`;
  const liNext=document.createElement('li');
  liNext.className='page-item'+((page>=pages)?' disabled':''); liNext.innerHTML=`<a class="page-link" href="#" data-nav="next">Keyingi</a>`;
  pgEl.appendChild(liPrev); pgEl.appendChild(liRange); pgEl.appendChild(liNext);
  pgEl.querySelectorAll('.page-link').forEach(a=>{
    a.addEventListener('click', e=>{
      e.preventDefault();
      if(a.dataset.nav==='prev' && page>1){ if(status==='pending') pageP--; else pageS--; loadList(status); }
      if(a.dataset.nav==='next' && page<pages){ if(status==='pending') pageP++; else pageS++; loadList(status); }
    });
  });
}
async function refresh(){ await Promise.all([loadList('pending'), loadList('signed')]); }

/* ==== kontraktni ko‘rish / imzolash ==== */
async function openContract(id){
  const r=await fetch(`../api/contracts.php?action=detail&id=${id}`);
  if(!r.ok){ showAlert('alertBox','Detallar yuklanmadi'); return; }
  const d=await r.json();
  curId=id; needSign = (d.require_signature?1:0);

  document.querySelector('#signModal .modal-title').innerHTML = `Shartnoma #${d.id} — <span class="text-muted small">${esc(d.title||'')}</span>`;

  // info
  document.getElementById('cInfo').innerHTML = `
    <div><strong>Oy:</strong> ${esc(d.ym||'-')}</div>
    <div><strong>Plan:</strong> ${esc(d.plan_name||'-')}</div>
    <div><strong>Status:</strong> <span class="badge badge-status ${d.status}">${esc(d.status||'-')}</span></div>
    <div><strong>Imzo talabi:</strong> ${d.require_signature ? 'Majburiy' : 'Shart emas'}</div>`;

  // punktlar
  document.getElementById('cItems').innerHTML = `
    <div class="fw-semibold mb-1">Punktlar</div>
    <ul class="mb-0">
      ${(d.items||[]).map(it=>`<li>${esc(it.title)} — <span class="text-muted small">${esc(it.evidence_types||'-')}</span></li>`).join('')}
    </ul>`;

  // biriktirmalar
  document.getElementById('cAtts').innerHTML = (d.attachments||[]).length
    ? `<div class="fw-semibold mb-1">Biriktirmalar</div>
       <ul class="mb-0">${(d.attachments||[]).map(a=>`<li><a href="${esc(a.url)}" target="_blank">${esc(a.name||a.url)}</a> <span class="text-muted small">(${esc(a.mime||'file')})</span></li>`).join('')}</ul>`
    : '';

  // admin izoh
  document.getElementById('cNote').innerHTML = d.admin_note
    ? `<div class="fw-semibold mb-1">Admin izoh</div><div class="border rounded p-2 bg-light">${esc(d.admin_note)}</div>`
    : '';

  const signCard = document.getElementById('signCard');
  const sigReadonly = document.getElementById('sigReadonly');
  const btnSign = document.getElementById('btnSign');
  const isSigned = d.status==='signed';

  btnSign.classList.toggle('d-none', isSigned);
  signCard.classList.toggle('d-none', isSigned);
  sigReadonly.classList.toggle('d-none', !isSigned);

  if (isSigned) {
    const sv=document.getElementById('cSigView');
    const sig = d.signature || (d.signatures && d.signatures[0]) || null;
    if(sig){
      const typed = sig.typed_name || '';
      const img   = sig.image_path || sig.image || '';
      const when  = (sig.created_at||'').replace('T',' ').slice(0,19);
      sv.innerHTML = `
        ${typed? `<div class="mb-2"><strong>Typed ism:</strong> ${esc(typed)}</div>`:''}
        ${img? `<div class="mb-2"><strong>Imzo rasm:</strong><div class="mt-1"><img src="${esc(img)}" style="max-width:100%;height:auto;border:1px solid #dee2e6;border-radius:.5rem;"></div></div>` : `<div class="text-muted">Imzo rasm saqlanmagan</div>`}
        ${when? `<div class="text-muted small">${esc(when)}</div>`:''}`;
    } else {
      document.getElementById('cSigView').innerHTML = `<div class="text-muted">Imzo ma’lumoti topilmadi.</div>`;
    }
  } else {
    // pending => imzo padni yangilab, DPI to‘g‘rilaymiz
    sigReset();
    const m = document.getElementById('signModal');
    const inst = bootstrap.Modal.getOrCreateInstance(m);
    m.addEventListener('shown.bs.modal', sigResize, {once:true});
  }

  bootstrap.Modal.getOrCreateInstance(document.getElementById('signModal')).show();
}

/* ========= Signature Pad (kross qurilma, HiDPI) ========= */
let sigCanvas=null, sigCtx=null;
let sigStrokes=[], sigDrawing=false;

function sigReset(){ sigStrokes=[]; sigDrawing=false; if(sigCtx){ sigCtx.clearRect(0,0,sigCanvas.width,sigCanvas.height);} }

function sigResize(){
  const pad=document.getElementById('sigPad');
  const rect=pad.getBoundingClientRect();
  if(!sigCanvas){
    sigCanvas=document.createElement('canvas');
    pad.innerHTML=''; pad.appendChild(sigCanvas);
    sigBindEvents();
  }
  const dpr = window.devicePixelRatio || 1;
  sigCanvas.style.width  = rect.width+'px';
  sigCanvas.style.height = rect.height+'px';
  sigCanvas.width  = Math.max(1, Math.floor(rect.width  * dpr));
  sigCanvas.height = Math.max(1, Math.floor(rect.height * dpr));
  sigCtx = sigCanvas.getContext('2d');
  sigCtx.setTransform(dpr,0,0,dpr,0,0);
  sigCtx.lineWidth = 2; sigCtx.lineCap='round'; sigCtx.lineJoin='round'; sigCtx.strokeStyle='#000';
  sigRedraw();
}

function sigRedraw(){
  if(!sigCtx) return;
  sigCtx.clearRect(0,0,sigCanvas.width,sigCanvas.height);
  sigCtx.beginPath();
  sigStrokes.forEach(st=>{
    st.forEach((p,i)=>{ if(i===0) sigCtx.moveTo(p.x,p.y); else sigCtx.lineTo(p.x,p.y); });
  });
  sigCtx.stroke();
}

function getSigPoint(e){
  const r=sigCanvas.getBoundingClientRect();
  let cx,cy;
  if(e.touches && e.touches[0]){ cx=e.touches[0].clientX; cy=e.touches[0].clientY; }
  else if(e.changedTouches && e.changedTouches[0]){ cx=e.changedTouches[0].clientX; cy=e.changedTouches[0].clientY; }
  else { cx=e.clientX; cy=e.clientY; }
  return {x: cx - r.left, y: cy - r.top};
}

function sigBindEvents(){
  const down = (e)=>{ e.preventDefault(); sigDrawing=true; const p=getSigPoint(e); sigStrokes.push([p]); sigRedraw(); };
  const move = (e)=>{ if(!sigDrawing) return; e.preventDefault(); const p=getSigPoint(e); sigStrokes[sigStrokes.length-1].push(p); sigRedraw(); };
  const up   = (e)=>{ if(!sigDrawing) return; e.preventDefault(); sigDrawing=false; };

  // Pointer
  sigCanvas.addEventListener('pointerdown', down, {passive:false});
  sigCanvas.addEventListener('pointermove', move, {passive:false});
  sigCanvas.addEventListener('pointerup',   up,   {passive:false});
  sigCanvas.addEventListener('pointercancel', up, {passive:false});
  sigCanvas.addEventListener('pointerleave',  up, {passive:false});

  // Touch fallback
  sigCanvas.addEventListener('touchstart', down, {passive:false});
  sigCanvas.addEventListener('touchmove',  move, {passive:false});
  sigCanvas.addEventListener('touchend',   up,   {passive:false});
  sigCanvas.addEventListener('touchcancel',up,   {passive:false});

  // Mouse fallback
  sigCanvas.addEventListener('mousedown', down, {passive:false});
  window.addEventListener('mousemove', move, {passive:false});
  window.addEventListener('mouseup',   up,   {passive:false});

  // UI tools
  document.getElementById('btnClear').addEventListener('click', sigReset);
  document.getElementById('btnUndo').addEventListener('click', ()=>{ sigStrokes.pop(); sigRedraw(); });

  // Resize/orientation — rasmni yo‘qotmay qayta chizish
  const rescale=()=>{
    const img = new Image();
    img.onload=()=>{ sigCtx.clearRect(0,0,sigCanvas.width,sigCanvas.height); sigCtx.drawImage(img,0,0,sigCanvas.width,sigCanvas.height); };
    img.src = sigCanvas.toDataURL('image/png');
    sigResize(); // resize oldidan snapshot qilib, keyin qayta chizamiz
  };
  window.addEventListener('resize', rescale, {passive:true});
  window.addEventListener('orientationchange', rescale, {passive:true});
}

function sigHasStroke(){ return sigStrokes.length>0 && sigStrokes.some(s=>s.length>1); }
function sigBlob(){ return new Promise(res=> sigCanvas.toBlob(b=>res(b), 'image/png')); }

/* ==== yuborish ==== */
async function doSign(){
  if (!agree.checked){ showAlert('signAlert','Iltimos, rozilikni tasdiqlang'); return; }
  const must = needSign===1;
  const typed = typedName.value.trim();
  const hasStroke = sigHasStroke();
  if (must && !typed && !hasStroke){
    showAlert('signAlert','Imzo majburiy: typed ism yoki chizilgan imzo kiriting'); return;
  }

  const fd = new FormData();
  fd.append('id', String(curId));
  fd.append('typed_name', typed);
  fd.append('agree', '1');
  if (hasStroke){
    const blob = await sigBlob();
    if (blob && blob.size>0) fd.append('signature_png', blob, 'signature.png');
  }

  const r = await fetch('../api/contracts.php?action=sign', { method:'POST', body: fd });
  const d = await r.json();
  if(!r.ok || !d.ok){ showAlert('signAlert','Imzolashda xato: '+(d.error||r.statusText)); return; }

  showAlert('alertBox','Shartnoma imzolandi','success');
  bootstrap.Modal.getOrCreateInstance(document.getElementById('signModal')).hide();
  await refresh();
}

/* ==== boot ==== */
document.addEventListener('click', (e)=>{
  const btn = e.target.closest('button[data-view]');
  if(!btn) return;
  const id = parseInt(btn.getAttribute('data-view'),10);
  if(id>0) openContract(id);
});
document.getElementById('btnSign').addEventListener('click', doSign);
document.getElementById('btnReload').addEventListener('click', ()=>{ pageP=1; pageS=1; refresh(); });
document.getElementById('q').addEventListener('input', ()=>{ pageP=1; pageS=1; refresh(); });

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