<?php
// ============================================================
//  MediCore — Purchase Return Records
//  File: purchase/return-list.php
// ============================================================
$page  = 'purchase/return-list';
$title = 'Purchase Return Records';
require_once '../includes/header.php';
$cur  = $settings['currency'];
ensure_soft_delete('purchase_returns');
$total= (float) db_val("SELECT COALESCE(SUM(total_amount),0) FROM purchase_returns WHERE is_deleted = 0");
// Range comparison instead of DATE_FORMAT(date,'%Y-%m')=? so idx_date
// can actually be used (wrapping the column in a function disables it).
$month= (float) db_val(
    "SELECT COALESCE(SUM(total_amount),0) FROM purchase_returns
      WHERE is_deleted = 0 AND date >= ? AND date < ?",
    [date('Y-m-01'), date('Y-m-01', strtotime('+1 month'))]
);
$cnt  = (int)   db_val("SELECT COUNT(*) FROM purchase_returns WHERE is_deleted = 0");
?>
<script>
document.getElementById('ph-actions').innerHTML=`
  <input type="text" id="srch" placeholder="🔍 PRN# or supplier…"
    style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);font-family:inherit;font-size:12px;width:180px;outline:none">
  <input type="date" id="f-from" style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);font-family:inherit;font-size:12px;outline:none">
  <input type="date" id="f-to"   style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);font-family:inherit;font-size:12px;outline:none">
  <select id="f-status" onchange="load()"
    style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);font-family:inherit;font-size:12px;outline:none">
    <option value="">All Status</option>
    <option value="approved">Approved</option>
    <option value="pending">Pending</option>
    <option value="rejected">Rejected</option>
  </select>
  <a class="btn btn-primary btn-sm" href="return.php">↩ New Return</a>`;
</script>

<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:12px">
  <div class="sc" style="border-top:3px solid var(--warn)">
    <div class="slabel">Total Returns</div><div class="sval b"><?=$cnt?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Total Return Value</div>
    <div class="sval b" style="color:var(--danger)"><?=$cur.number_format($total,2)?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">This Month</div>
    <div class="sval b" style="color:var(--brand)"><?=$cur.number_format($month,2)?></div>
  </div>
</div>

<div class="card" style="padding:0">
  <div class="tw">
    <table>
      <thead>
        <tr>
          <th>#</th><th>PRN #</th><th>Orig. PO</th>
          <th>Supplier</th><th>Date</th>
          <th style="text-align:center">Items</th>
          <th style="text-align:right">Amount</th>
          <th style="text-align:center">Credit Type</th>
          <th style="text-align:center">Status</th>
          <th style="text-align:center;width:130px">Actions</th>
        </tr>
      </thead>
      <tbody id="ret-body">
        <tr><td colspan="10" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="ret-footer" style="padding:8px 14px;font-size:11px;color:var(--text3);border-top:1px solid var(--border)"></div>
</div>

<script>
const API='../api/purchase-returns.php';
const CUR='<?=addslashes($cur)?>';
const IS_ADMIN=<?=is_admin()?'true':'false'?>;
let timer=null;

async function load(){
  const tbody=document.getElementById('ret-body');
  tbody.innerHTML='<tr><td colspan="10" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>';
  const r=await apiPost(API,{
    action:'list',
    q:    document.getElementById('srch')?.value.trim()||'',
    from: document.getElementById('f-from')?.value||'',
    to:   document.getElementById('f-to')?.value||'',
    status:document.getElementById('f-status')?.value||'',
  });
  if(!r.success){
    tbody.innerHTML=`<tr><td colspan="10" class="empty-state" style="color:var(--danger)">Error: ${r.error}</td></tr>`;return;
  }
  const rows=r.data;
  const totAmt=rows.reduce((s,r)=>s+parseFloat(r.total_amount||0),0);
  document.getElementById('ret-footer').innerHTML=
    `<strong>${rows.length}</strong> record(s) &nbsp;·&nbsp; Total: <strong style="color:var(--danger)">${CUR}${totAmt.toFixed(2)}</strong>`;
  if(!rows.length){tbody.innerHTML='<tr><td colspan="10" class="empty-state">No return records found.</td></tr>';return;}
  const ctLabels={supplier_credit:'🏢 Supplier Credit',cash_recovery:'💵 Cash Recovery',adjustment:'📋 Adjustment'};
  const stStyle={approved:'#d4f0e6,var(--accent)',pending:'#fff3dc,var(--warn)',rejected:'#fde8e8,var(--danger)'};
  tbody.innerHTML=rows.map((r,i)=>{
    const[bg,cl]=(stStyle[r.status]||'var(--surface2),var(--text2)').split(',');
    return `<tr>
      <td style="color:var(--text3)">${i+1}</td>
      <td><span class="mono" style="font-weight:700;color:var(--brand);cursor:pointer"
               onclick="viewDetail(${r.id})">${esc(r.prn)}</span></td>
      <td class="mono" style="font-size:11px;color:var(--text2)">${esc(r.purchase_invoice)}</td>
      <td style="font-weight:500">${esc(r.supplier_name)}</td>
      <td style="color:var(--text2)">${r.date}</td>
      <td style="text-align:center"><span class="badge">${r.item_count}</span></td>
      <td class="mono" style="text-align:right;font-weight:700;color:var(--danger)">
        ${CUR}${parseFloat(r.total_amount||0).toFixed(2)}</td>
      <td style="text-align:center;font-size:11px">${ctLabels[r.credit_type]||r.credit_type}</td>
      <td style="text-align:center">
        <span class="badge" style="background:${bg};color:${cl};font-weight:700">${r.status}</span></td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn btn-sm btn-teal" onclick="viewDetail(${r.id})">🔍</button>
        <button class="btn btn-sm" style="background:#e8eaf6;color:var(--brand)"
                onclick="printReturn(${r.id})">🖨</button>
        ${IS_ADMIN&&r.status!=='rejected'
          ?`<button class="btn btn-sm btn-danger"
               onclick="delReturn(${r.id},'${esc(r.prn).replace(/'/g,"\\'")}')">🗑</button>`:''}
      </td>
    </tr>`;
  }).join('');
}

async function viewDetail(id){
  showModal('<div style="text-align:center;padding:20px">⏳ Loading…</div>','🔍 Return Detail','xl');
  const r=await apiPost(API,{action:'detail',id});
  if(!r.success){document.querySelector('.mbox').innerHTML=`<div style="padding:20px;color:var(--danger)">${r.error}</div>`;return;}
  const ret=r.data;const items=r.items||[];
  const[bg,cl]=({'approved':'#d4f0e6,var(--accent)','pending':'#fff3dc,var(--warn)','rejected':'#fde8e8,var(--danger)'}[ret.status]||'var(--surface2),var(--text2)').split(',');
  const iRows=items.map((it,i)=>`<tr>
    <td style="color:var(--text3)">${i+1}</td>
    <td><div style="font-weight:600;font-size:12px">${formIconName(it.form, it.product_name)}</div></td>
    <td class="mono" style="text-align:center">${it.qty}</td>
    <td class="mono" style="text-align:right">${CUR}${parseFloat(it.rate).toFixed(2)}</td>
    <td class="mono" style="text-align:right;font-weight:700;color:var(--danger)">
      ${CUR}${parseFloat(it.amount).toFixed(2)}</td>
  </tr>`).join('');
  document.querySelector('.mbox').innerHTML=`
    <div class="mtitle">↩ PRN: <span class="mono" style="color:var(--brand)">${esc(ret.prn)}</span>
      <button class="mclose" onclick="closeModal()">×</button></div>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;
                padding:10px 14px;border-bottom:1px solid var(--border)">
      <div><div style="font-size:10px;color:var(--text3)">PO Reference</div>
           <div class="mono" style="font-weight:700">${esc(ret.purchase_invoice)}</div></div>
      <div><div style="font-size:10px;color:var(--text3)">Supplier</div>
           <div style="font-weight:600">${esc(ret.supplier_name)}</div></div>
      <div><div style="font-size:10px;color:var(--text3)">Date</div><div>${ret.date}</div></div>
      <div><div style="font-size:10px;color:var(--text3)">Status</div>
           <span class="badge" style="background:${bg};color:${cl};font-weight:700">${ret.status}</span></div>
    </div>
    <div class="tw" style="max-height:300px;overflow-y:auto">
      <table>
        <thead><tr><th>#</th><th>Product</th>
          <th style="text-align:center">Qty</th>
          <th style="text-align:right">Rate</th>
          <th style="text-align:right">Amount</th></tr></thead>
        <tbody>${iRows}</tbody>
      </table>
    </div>
    <div style="display:grid;grid-template-columns:1fr auto;gap:16px;
                padding:10px 16px;background:var(--surface2);border-top:2px solid var(--border)">
      <div style="font-size:11.5px;color:var(--text2)">
        Credit: ${ret.credit_type} ${ret.reason?'· Reason: '+esc(ret.reason):''}
      </div>
      <div class="mono" style="font-weight:800;font-size:15px;color:var(--danger)">
        ${CUR}${parseFloat(ret.total_amount).toFixed(2)}</div>
    </div>
    <div style="padding:10px 14px;display:flex;gap:8px;justify-content:flex-end">
      <button class="btn btn-sm" onclick="printReturn(${ret.id})">🖨 Print</button>
      <button class="btn" onclick="closeModal()">Close</button>
    </div>`;
}

function printReturn(id){window.open(`../purchase/return-print.php?id=${id}`,'_blank','width=820,height=700,scrollbars=yes');}

async function delReturn(id,prn){
  if(!confirm(`Delete return "${prn}"?\nThis will reverse all stock and supplier ledger changes.`))return;
  const r=await apiPost(API,{action:'delete',id});
  if(r.success)load();
  else alert('⚠ '+(r.error||'Delete failed.'));
}

document.addEventListener('DOMContentLoaded',()=>{
  load();
  document.getElementById('srch').addEventListener('input',()=>{clearTimeout(timer);timer=setTimeout(load,300);});
  document.getElementById('f-from').addEventListener('change',load);
  document.getElementById('f-to').addEventListener('change',load);
});
function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
</script>
<?php require_once '../includes/footer.php'; ?>
