<?php
// ============================================================
//  MediCore — Create Purchase Return
//  File: purchase/return.php
// ============================================================
$page  = 'purchase/return-list';
$title = 'Purchase Return';
require_once '../includes/header.php';
$cur = $settings['currency'];
$today = today();
$preInvoice = htmlspecialchars($_GET['invoice'] ?? '');
?>
<script>
document.getElementById('ph-actions').innerHTML =
  `<a class="btn btn-sm" href="return-list.php">📋 Return Records</a>`;
</script>

<!-- Search PO -->
<div class="card" style="padding:12px 16px;margin-bottom:12px">
  <div style="display:flex;gap:10px;align-items:flex-end">
    <div class="fg" style="flex:1;margin-bottom:0">
      <label>Search Original Purchase Order *</label>
      <input id="po-search" value="<?= $preInvoice ?>"
             placeholder="e.g. PO-2025-000001"
             style="font-family:'JetBrains Mono',monospace;font-weight:600">
    </div>
    <button class="btn btn-primary" onclick="loadPO()">🔍 Load PO</button>
  </div>
  <div id="search-err"
       style="display:none;color:var(--danger);font-size:11.5px;margin-top:6px"></div>
</div>

<!-- PO details -->
<div id="po-panel" style="display:none">

  <div class="card" style="padding:0;margin-bottom:12px">
    <div class="ch" style="padding:10px 14px;background:var(--brand-xlight)">
      <div class="ct" style="color:var(--brand)">📦 Original Purchase Order</div>
      <span id="po-status-badge" class="badge"></span>
    </div>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0;
                border-bottom:1px solid var(--border)">
      <div style="padding:10px 14px;border-right:1px solid var(--border)">
        <div style="font-size:10px;color:var(--text3)">PO Number</div>
        <div class="mono" id="po-no" style="font-weight:700;color:var(--brand)"></div>
      </div>
      <div style="padding:10px 14px;border-right:1px solid var(--border)">
        <div style="font-size:10px;color:var(--text3)">Supplier</div>
        <div id="po-supp" style="font-weight:600"></div>
      </div>
      <div style="padding:10px 14px;border-right:1px solid var(--border)">
        <div style="font-size:10px;color:var(--text3)">Date</div>
        <div id="po-date"></div>
      </div>
      <div style="padding:10px 14px">
        <div style="font-size:10px;color:var(--text3)">Total / Paid / Due</div>
        <div id="po-amounts" class="mono" style="font-size:11.5px"></div>
      </div>
    </div>
  </div>

  <div class="card" style="padding:0;margin-bottom:12px">
    <div class="ch" style="padding:10px 14px">
      <div class="ct">📦 Select Items to Return</div>
      <div style="display:flex;gap:8px">
        <button class="btn btn-sm" onclick="selectAllItems()">✓ All</button>
        <button class="btn btn-sm" onclick="clearAllItems()">✕ Clear</button>
      </div>
    </div>
    <div class="tw">
      <table>
        <thead>
          <tr>
            <th style="width:36px;text-align:center">
              <input type="checkbox" id="chk-all" onchange="toggleAllItems(this.checked)">
            </th>
            <th>Product</th>
            <th style="text-align:center">Orig Pcs</th>
            <th style="text-align:center">Already Returned</th>
            <th style="text-align:center">Max Returnable</th>
            <th style="text-align:right">Purchase Rate</th>
            <th style="text-align:center">Return Qty (pcs)</th>
            <th style="text-align:right">Return Amount</th>
          </tr>
        </thead>
        <tbody id="items-body">
          <tr><td colspan="8" class="empty-state">Load a PO above</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <div style="display:grid;grid-template-columns:1fr 340px;gap:12px">
    <div class="card">
      <div class="ch"><div class="ct">📝 Return Details</div></div>
      <div style="display:flex;flex-direction:column;gap:10px;padding-top:4px">
        <div class="fg">
          <label>Return Date</label>
          <input id="ret-date" type="date" value="<?= $today ?>">
        </div>
        <div class="fg">
          <label>Reason for Return *</label>
          <textarea id="ret-reason" rows="3"
            style="padding:7px 9px;border:1px solid var(--border);
                   border-radius:var(--rsm);font-family:inherit;font-size:12px;
                   resize:vertical;outline:none;background:var(--surface);color:var(--text)"
            placeholder="e.g. Damaged goods, Wrong item delivered, Near expiry…"></textarea>
        </div>
      </div>
    </div>

    <div style="display:flex;flex-direction:column;gap:10px">
      <div class="card">
        <div class="ch"><div class="ct">💳 Credit Method</div></div>
        <div id="credit-options"
             style="display:flex;flex-direction:column;gap:7px;padding-top:4px"></div>
      </div>

      <div class="card"
           style="background:var(--brand-xlight);border:1px solid var(--brand-light)">
        <div class="ch"><div class="ct" style="color:var(--brand)">📊 Return Summary</div></div>
        <div style="font-size:12.5px;display:flex;flex-direction:column;gap:6px">
          <div style="display:flex;justify-content:space-between">
            <span style="color:var(--text2)">Items Selected</span>
            <span id="sum-items" style="font-weight:700">0</span>
          </div>
          <div style="display:flex;justify-content:space-between">
            <span style="color:var(--text2)">Total Qty</span>
            <span id="sum-qty" style="font-weight:700">0</span>
          </div>
          <div style="display:flex;justify-content:space-between;
                      border-top:2px solid var(--brand-light);padding-top:8px;margin-top:4px">
            <span style="font-weight:700;color:var(--brand)">Return Amount</span>
            <span id="sum-amount" class="mono"
                  style="font-weight:800;font-size:16px;color:var(--brand)">
              <?= $cur ?>0.00
            </span>
          </div>
        </div>
      </div>

      <button id="save-btn" onclick="saveReturn()"
              class="btn btn-primary"
              style="width:100%;padding:11px;font-size:14px;font-weight:700">
        ↩ Create Purchase Return
      </button>
      <div id="save-err"
           style="display:none;background:#fde8e8;border:1px solid #f5a0a0;
                  color:var(--danger);padding:8px 12px;border-radius:var(--rsm);
                  font-size:12px"></div>
    </div>
  </div>
</div>

<script>
const API = '../api/purchase-returns.php';
const CUR = '<?= addslashes($cur) ?>';
let currentPO = null;
let returnedQtys = {};

async function loadPO() {
  const invoice = document.getElementById('po-search').value.trim();
  const errEl   = document.getElementById('search-err');
  errEl.style.display = 'none';
  if (!invoice) { errEl.textContent='⚠ Enter a PO number.'; errEl.style.display='block'; return; }

  const r = await apiPost('../api/purchases.php', { action:'list', q:invoice });
  if (!r.success || !r.data.length) {
    errEl.textContent=`⚠ PO "${invoice}" not found.`; errEl.style.display='block'; return;
  }
  const po = r.data.find(p => p.invoice === invoice);
  if (!po) { errEl.textContent=`⚠ No exact match for "${invoice}".`; errEl.style.display='block'; return; }

  const d = await apiPost('../api/purchases.php', { action:'detail', id:po.id });
  if (!d.success) { errEl.textContent='⚠ '+d.error; errEl.style.display='block'; return; }

  currentPO = d.data;
  renderPO(d.data, d.items||[]);
}

function renderPO(po, items) {
  document.getElementById('po-panel').style.display = 'block';
  document.getElementById('po-no').textContent    = po.invoice;
  document.getElementById('po-supp').textContent  = po.supplier_name;
  document.getElementById('po-date').textContent  = po.date;
  document.getElementById('po-amounts').textContent =
    `${CUR}${parseFloat(po.final_price).toFixed(2)} / Paid: ${CUR}${parseFloat(po.paid).toFixed(2)} / Due: ${CUR}${parseFloat(po.due).toFixed(2)}`;

  const isPaid = parseFloat(po.due) <= 0.001;
  const badge  = document.getElementById('po-status-badge');
  badge.textContent = isPaid ? 'Paid' : (parseFloat(po.paid)>0 ? 'Partial' : 'Due');
  badge.style.cssText = `background:${isPaid?'#d4f0e6':'#fff3dc'};color:${isPaid?'var(--accent)':'var(--warn)'};font-weight:700`;

  loadReturnedQtys(po.id, items, po);
}

async function loadReturnedQtys(poId, items, po) {
  const r = await apiPost(API, { action:'list', q:po.invoice });
  returnedQtys = {};
  if (r.success) {
    for (const ret of r.data) {
      if (parseInt(ret.purchase_id) !== parseInt(poId)) continue;
      const d = await apiPost(API, { action:'detail', id:ret.id });
      if (d.success) d.items.forEach(it => {
        returnedQtys[it.product_id] = (returnedQtys[it.product_id]||0) + it.qty;
      });
    }
  }
  renderItems(items, po);
}

function renderItems(items, po) {
  const tbody = document.getElementById('items-body');
  tbody.innerHTML = items.map(it => {
    const alreadyRet = returnedQtys[it.product_id] || 0;
    const maxRet     = Math.max(0, it.qty_pcs - alreadyRet);
    const canReturn  = maxRet > 0;
    return `<tr ${!canReturn?'style="opacity:.5"':''}>
      <td style="text-align:center">
        <input type="checkbox" class="item-chk"
               data-id="${it.product_id}" data-name="${esc(it.product_name)}"
               data-rate="${it.btp_vat}" data-max="${maxRet}"
               ${!canReturn?'disabled':''}
               onchange="updateSummary()">
      </td>
      <td>
        <div style="font-weight:600;font-size:12px">${formIconName(it.form, it.product_name)}</div>
        ${it.rack?`<div style="font-size:10px;color:var(--text3)">Rack: ${esc(it.rack)}</div>`:''}
      </td>
      <td class="mono" style="text-align:center">${it.qty_pcs}</td>
      <td class="mono" style="text-align:center;color:${alreadyRet>0?'var(--warn)':'var(--text3)'}">
        ${alreadyRet>0?alreadyRet:'—'}
      </td>
      <td class="mono" style="text-align:center;font-weight:700;
                               color:${maxRet>0?'var(--accent)':'var(--danger)'}">
        ${maxRet}
      </td>
      <td class="mono" style="text-align:right">
        ${CUR}${parseFloat(it.btp_vat||0).toFixed(2)}
      </td>
      <td style="text-align:center">
        <input type="number" class="ret-qty" data-id="${it.product_id}"
               value="${maxRet>0?1:0}" min="1" max="${maxRet}"
               ${!canReturn?'disabled':''}
               style="width:60px;text-align:center"
               oninput="updateSummary()">
      </td>
      <td class="mono" id="line-amt-${it.product_id}"
          style="text-align:right;font-weight:700;color:var(--danger)">
        ${CUR}0.00
      </td>
    </tr>`;
  }).join('');
  buildCreditOptions(po);
  updateSummary();
}

function buildCreditOptions(po) {
  const due   = parseFloat(po.due||0);
  const hasDue= due > 0.001;
  const panel = document.getElementById('credit-options');
  if (hasDue) {
    panel.innerHTML = `
      <div style="padding:10px 12px;background:#e8f4fd;border-radius:var(--rsm);font-size:12px">
        <div style="font-weight:700;color:var(--brand);margin-bottom:4px">📉 PO Has Outstanding Due</div>
        <div style="color:var(--text2)">Return amount will reduce outstanding due of
          <strong style="color:var(--danger)">${CUR}${due.toFixed(2)}</strong></div>
        <input type="hidden" id="credit-type" value="adjustment">
        <input type="hidden" id="credit-acct" value="Cash">
      </div>`;
  } else {
    panel.innerHTML = `
      <div style="font-size:11.5px;color:var(--text2);margin-bottom:6px">
        PO was fully paid. Choose credit method:
      </div>
      ${[
        ['supplier_credit','🏢 Supplier Credit','Reduce amount owed to supplier'],
        ['cash_recovery',  '💵 Cash Recovery', 'Receive cash back from supplier'],
        ['adjustment',     '📋 Adjustment',    'Internal adjustment only'],
      ].map(([val,label,hint],idx) => `
        <label style="display:flex;align-items:flex-start;gap:8px;padding:8px 10px;
                       border:1px solid var(--border);border-radius:var(--rsm);
                       cursor:pointer;font-size:12px" id="cl-${val}">
          <input type="radio" name="credit-type" value="${val}"
                 ${idx===0?'checked':''} onchange="hlCredit()">
          <div>
            <div style="font-weight:700">${label}</div>
            <div style="font-size:10px;color:var(--text3)">${hint}</div>
          </div>
        </label>`).join('')}
      <div id="acct-row" class="fg" style="margin-top:4px">
        <label>Recovery Account</label>
        <select id="credit-acct" style="width:100%">
          <option>Cash</option><option>Bank</option>
          <option>MFS</option><option>Card</option>
        </select>
      </div>`;
    hlCredit();
  }
}

function hlCredit() {
  ['supplier_credit','cash_recovery','adjustment'].forEach(v => {
    const lbl = document.getElementById(`cl-${v}`);
    const chk = lbl?.querySelector('input');
    if (lbl) {
      lbl.style.borderColor = chk?.checked?'var(--brand)':'var(--border)';
      lbl.style.background  = chk?.checked?'var(--brand-xlight)':'transparent';
    }
  });
  const sel = document.querySelector('input[name="credit-type"]:checked')?.value;
  const ar  = document.getElementById('acct-row');
  if (ar) ar.style.display = sel==='cash_recovery'?'block':'none';
}

function toggleAllItems(c) {
  document.querySelectorAll('.item-chk:not(:disabled)').forEach(chk=>{chk.checked=c;});
  updateSummary();
}
function selectAllItems(){toggleAllItems(true);}
function clearAllItems(){toggleAllItems(false);}

function updateSummary() {
  let total=0, qty=0, count=0;
  document.querySelectorAll('.item-chk:checked').forEach(chk=>{
    const pid = chk.dataset.id;
    const rate= parseFloat(chk.dataset.rate)||0;
    const qEl = document.querySelector(`.ret-qty[data-id="${pid}"]`);
    const q   = Math.min(Math.max(1,parseInt(qEl?.value)||1),parseInt(chk.dataset.max));
    const amt = q*rate;
    total+=amt; qty+=q; count++;
    const le=document.getElementById(`line-amt-${pid}`);
    if(le) le.textContent=CUR+amt.toFixed(2);
  });
  document.getElementById('sum-items').textContent = count;
  document.getElementById('sum-qty').textContent   = qty;
  document.getElementById('sum-amount').textContent= CUR+total.toFixed(2);
}

async function saveReturn() {
  const errEl   = document.getElementById('save-err');
  const saveBtn = document.getElementById('save-btn');
  errEl.style.display='none';
  if (!currentPO){errEl.textContent='⚠ Load a PO first.';errEl.style.display='block';return;}
  const reason = document.getElementById('ret-reason').value.trim();
  if (!reason){errEl.textContent='⚠ Reason is required.';errEl.style.display='block';return;}
  const items=[];
  document.querySelectorAll('.item-chk:checked').forEach(chk=>{
    const pid=parseInt(chk.dataset.id);
    const qEl=document.querySelector(`.ret-qty[data-id="${chk.dataset.id}"]`);
    const qty=Math.min(parseInt(qEl?.value)||1,parseInt(chk.dataset.max));
    items.push({product_id:pid,product_name:chk.dataset.name,qty,rate:parseFloat(chk.dataset.rate)||0});
  });
  if(!items.length){errEl.textContent='⚠ Select at least one item.';errEl.style.display='block';return;}
  const creditType=document.getElementById('credit-type')?.value||
    document.querySelector('input[name="credit-type"]:checked')?.value||'adjustment';
  const creditAcct=document.getElementById('credit-acct')?.value||'Cash';
  saveBtn.disabled=true; saveBtn.textContent='⏳ Processing…';
  const r=await apiPost(API,{
    action:'save',purchase_id:currentPO.id,
    date:document.getElementById('ret-date').value,
    credit_type:creditType,credit_account:creditAcct,reason,items,
  });
  saveBtn.disabled=false; saveBtn.textContent='↩ Create Purchase Return';
  if(!r.success){errEl.textContent='⚠ '+(r.error||'Save failed.');errEl.style.display='block';return;}
  showModal(`
  <div style="text-align:center;padding:10px 0">
    <div style="font-size:34px;margin-bottom:8px">✅</div>
    <div style="font-size:15px;font-weight:700;color:var(--accent);margin-bottom:4px">Purchase Return Created!</div>
    <div class="mono" style="font-size:18px;font-weight:800;color:var(--brand);margin-bottom:14px">${r.prn}</div>
    <div style="font-size:12px;color:var(--text2);margin-bottom:16px">
      Return Amount: <strong>${CUR}${parseFloat(r.total).toFixed(2)}</strong>
    </div>
    <div style="display:flex;gap:8px;justify-content:center">
      <button class="btn btn-teal"
        onclick="closeModal();window.open('return-print.php?id=${r.return_id}','_blank','width=820,height=700')">
        🖨 Print Voucher
      </button>
      <button class="btn btn-primary" onclick="closeModal();location.reload()">↩ New Return</button>
      <a class="btn" href="return-list.php">📋 View All</a>
    </div>
  </div>`,'Return Saved');
}
function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
document.addEventListener('DOMContentLoaded',()=>{if(document.getElementById('po-search').value)loadPO();});
</script>
<?php require_once '../includes/footer.php'; ?>
