<?php
// ============================================================
//  MediCore — Create Sales Return
//  File: sale/return.php
// ============================================================
$page  = 'sale/return-list';
$title = 'Sales Return';
require_once '../includes/header.php';
$today = date('Y-m-d');

$cur     = $settings['currency'];
$today   = today();
$cfg     = $settings;
$srnPfx  = $cfg['srn_prefix'] ?? 'SRN';

// Pre-load invoice if passed via URL
$preInvoice = htmlspecialchars($_GET['invoice'] ?? '');
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <a class="btn btn-sm" href="return-list.php">📋 Return Records</a>`;
</script>

<!-- ── Search invoice ─────────────────────────────── -->
<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 Invoice *</label>
      <input id="inv-search"
             value="<?= $preInvoice ?>"
             placeholder="Type invoice number e.g. INV-2025-000001"
             style="font-family:'JetBrains Mono',monospace;font-weight:600">
    </div>
    <button class="btn btn-primary" onclick="loadInvoice()">
      🔍 Load Invoice
    </button>
  </div>
  <div id="search-err"
       style="display:none;color:var(--danger);font-size:11.5px;margin-top:6px"></div>
</div>

<!-- ── Invoice details (shown after load) ─────────── -->
<div id="invoice-panel" style="display:none">

  <!-- Original invoice info -->
  <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 Invoice</div>
      <span id="inv-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)">Invoice #</div>
        <div class="mono" id="inv-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)">Customer</div>
        <div id="inv-cust" 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="inv-date"></div>
      </div>
      <div style="padding:10px 14px">
        <div style="font-size:10px;color:var(--text3)">Amount / Paid / Due</div>
        <div id="inv-amounts" class="mono" style="font-size:11.5px"></div>
      </div>
    </div>
  </div>

  <!-- Items to return -->
  <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">Original Qty</th>
            <th style="text-align:center">Already Returned</th>
            <th style="text-align:center">Max Returnable</th>
            <th style="text-align:right">Rate</th>
            <th style="text-align:center">Return Qty</th>
            <th style="text-align:right">Return Amount</th>
          </tr>
        </thead>
        <tbody id="items-body">
          <tr><td colspan="8" class="empty-state">Load an invoice above</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Return details -->
  <div style="display:grid;grid-template-columns:1fr 340px;gap:12px">

    <!-- Left — reason -->
    <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 product, Wrong item, Expired, Quality issue…">
          </textarea>
        </div>
      </div>
    </div>

    <!-- Right — refund type + summary -->
    <div style="display:flex;flex-direction:column;gap:10px">

      <!-- Refund type (changes based on invoice payment status) -->
      <div class="card" id="refund-panel">
        <div class="ch"><div class="ct">💳 Refund Method</div></div>
        <div id="refund-options"
             style="display:flex;flex-direction:column;gap:7px;padding-top:4px">
          <!-- Filled by JS based on invoice status -->
        </div>
      </div>

      <!-- Return summary -->
      <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 Sales 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><!-- /invoice-panel -->

<script>
const API    = '../api/sale-returns.php';
const CUR    = '<?= addslashes($cur) ?>';
let currentSale   = null;
let returnedQtys  = {};  // { product_id: already_returned }

// ── Load invoice ──────────────────────────────────────────────
async function loadInvoice() {
  const invoice = document.getElementById('inv-search').value.trim();
  const errEl   = document.getElementById('search-err');
  errEl.style.display = 'none';

  if (!invoice) {
    errEl.textContent   = '⚠ Enter an invoice number.';
    errEl.style.display = 'block'; return;
  }

  // Fetch sale by invoice number
  const r = await apiPost('../api/sales.php', {
    action: 'list', q: invoice
  });

  if (!r.success || !r.data.length) {
    errEl.textContent   = `⚠ Invoice "${invoice}" not found.`;
    errEl.style.display = 'block'; return;
  }

  // Find exact match
  const sale = r.data.find(s => s.invoice === invoice);
  if (!sale) {
    errEl.textContent   = `⚠ No exact match for "${invoice}".`;
    errEl.style.display = 'block'; return;
  }

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

  currentSale = d.data;
  renderInvoice(d.data, d.items || []);
}

function renderInvoice(sale, items) {
  document.getElementById('invoice-panel').style.display = 'block';

  // Header info
  document.getElementById('inv-no').textContent   = sale.invoice;
  document.getElementById('inv-cust').textContent = sale.customer_name;
  document.getElementById('inv-date').textContent = sale.date;
  document.getElementById('inv-amounts').textContent =
    `${CUR}${parseFloat(sale.final_price).toFixed(2)} / ` +
    `Paid: ${CUR}${parseFloat(sale.paid).toFixed(2)} / ` +
    `Due: ${CUR}${parseFloat(sale.due).toFixed(2)}`;

  const statusBadge = document.getElementById('inv-status-badge');
  const stBg = sale.status==='Paid' ? '#d4f0e6' : sale.status==='Partial' ? '#fff3dc' : '#fde8e8';
  const stCl = sale.status==='Paid' ? 'var(--accent)' : sale.status==='Partial' ? 'var(--warn)' : 'var(--danger)';
  statusBadge.textContent = sale.status;
  statusBadge.style.cssText = `background:${stBg};color:${stCl};font-weight:700`;

  // Load already-returned quantities
  loadReturnedQtys(sale.id, items, sale);
}

async function loadReturnedQtys(saleId, items, sale) {
  // Get all existing returns for this sale
  const r = await apiPost(API, { action: 'list', q: sale.invoice });
  returnedQtys = {};

  if (r.success) {
    for (const ret of r.data) {
      if (ret.sale_id !== parseInt(saleId)) 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, sale);
}

function renderItems(items, sale) {
  const tbody = document.getElementById('items-body');
  tbody.innerHTML = items.map((it, i) => {
    const alreadyRet = returnedQtys[it.product_id] || 0;
    const maxRet     = Math.max(0, it.qty - 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.price}"
               data-max="${maxRet}"
               ${!canReturn ? 'disabled' : ''}
               onchange="updateSummary()">
      </td>
      <td>
        <div style="font-weight:600;font-size:12px">${formIconName(it.form, it.product_name)}</div>
        <div style="font-size:10px;color:var(--text3)">
          ${it.strength||''} ${it.form ? '· '+it.form : ''}
        </div>
      </td>
      <td class="mono" style="text-align:center">${it.qty}</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.price||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">
        ${CUR}0.00
      </td>
    </tr>`;
  }).join('');

  buildRefundOptions(sale);
  updateSummary();
}

function buildRefundOptions(sale) {
  const due    = parseFloat(sale.due || 0);
  const isDue  = due > 0.001;
  const panel  = document.getElementById('refund-options');

  if (isDue) {
    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">
          📉 Invoice Has Outstanding Due
        </div>
        <div style="color:var(--text2)">
          Return amount will automatically reduce the
          customer's outstanding due of
          <strong style="color:var(--danger)">${CUR}${due.toFixed(2)}</strong>
        </div>
        <input type="hidden" id="refund-type" value="adjustment">
        <input type="hidden" id="refund-acct" value="Cash">
      </div>`;
  } else {
    panel.innerHTML = `
      <div style="font-size:11.5px;color:var(--text2);margin-bottom:6px">
        Invoice was fully paid. Choose refund method:
      </div>
      ${[
        ['cash',       '💵 Cash Refund',               'Pay back to customer in cash'],
        ['advance',    '💳 Add to Customer Advance',    'Credit against future purchases'],
        ['adjustment', '📋 Adjustment (No cash out)',   '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="rl-${val}">
          <input type="radio" name="refund-type" value="${val}"
                 ${idx === 0 ? 'checked' : ''}
                 onchange="hlRefund()">
          <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>Refund Account</label>
        <select id="refund-acct" style="width:100%">
          <option>Cash</option><option>Bank</option>
          <option>MFS</option><option>Card</option>
        </select>
      </div>`;
    hlRefund();
  }
}

function hlRefund() {
  ['cash','advance','adjustment'].forEach(v => {
    const lbl = document.getElementById(`rl-${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';
    }
  });
  // Show/hide account selector
  const acctRow = document.getElementById('acct-row');
  const selVal  = document.querySelector('input[name="refund-type"]:checked')?.value;
  if (acctRow) acctRow.style.display = selVal === 'cash' ? 'block' : 'none';
}

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

function updateSummary() {
  let totalAmt = 0, totalQty = 0, itemCount = 0;

  document.querySelectorAll('.item-chk:checked').forEach(chk => {
    const pid  = chk.dataset.id;
    const rate = parseFloat(chk.dataset.rate) || 0;
    const qtyEl= document.querySelector(`.ret-qty[data-id="${pid}"]`);
    const qty  = Math.min(
      Math.max(1, parseInt(qtyEl?.value) || 1),
      parseInt(chk.dataset.max)
    );
    const amt  = qty * rate;
    totalAmt  += amt;
    totalQty  += qty;
    itemCount++;

    const lineEl = document.getElementById(`line-amt-${pid}`);
    if (lineEl) lineEl.textContent = CUR + amt.toFixed(2);
  });

  document.getElementById('sum-items').textContent  = itemCount;
  document.getElementById('sum-qty').textContent    = totalQty;
  document.getElementById('sum-amount').textContent = CUR + totalAmt.toFixed(2);
}

// ── Save Return ───────────────────────────────────────────────
async function saveReturn() {
  const errEl   = document.getElementById('save-err');
  const saveBtn = document.getElementById('save-btn');
  errEl.style.display = 'none';

  if (!currentSale) {
    errEl.textContent   = '⚠ Load an invoice first.';
    errEl.style.display = 'block'; return;
  }

  const reason = document.getElementById('ret-reason').value.trim();
  if (!reason) {
    errEl.textContent   = '⚠ Reason for return is required.';
    errEl.style.display = 'block'; return;
  }

  // Collect checked items
  const items = [];
  document.querySelectorAll('.item-chk:checked').forEach(chk => {
    const pid  = parseInt(chk.dataset.id);
    const name = chk.dataset.name;
    const rate = parseFloat(chk.dataset.rate) || 0;
    const qtyEl= document.querySelector(`.ret-qty[data-id="${chk.dataset.id}"]`);
    const qty  = Math.min(parseInt(qtyEl?.value)||1, parseInt(chk.dataset.max));
    items.push({ product_id: pid, product_name: name, qty, rate });
  });

  if (!items.length) {
    errEl.textContent   = '⚠ Select at least one item to return.';
    errEl.style.display = 'block'; return;
  }

  // Refund type
  const refundType = document.getElementById('refund-type')?.value
    || document.querySelector('input[name="refund-type"]:checked')?.value
    || 'adjustment';
  const refundAcct = document.getElementById('refund-acct')?.value || 'Cash';

  saveBtn.disabled    = true;
  saveBtn.textContent = '⏳ Processing…';

  const r = await apiPost(API, {
    action:         'save',
    sale_id:        currentSale.id,
    date:           document.getElementById('ret-date').value,
    refund_type:    refundType,
    refund_account: refundAcct,
    reason,
    items,
  });

  saveBtn.disabled    = false;
  saveBtn.textContent = '↩ Create Sales Return';

  if (!r.success) {
    errEl.textContent   = '⚠ ' + (r.error || 'Save failed.');
    errEl.style.display = 'block'; return;
  }

  // Success modal
  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">
      Sales Return Created!
    </div>
    <div class="mono" style="font-size:18px;font-weight:800;color:var(--brand);
                              margin-bottom:14px">
      ${r.srn}
    </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;');
}

// Auto-load if invoice pre-set
document.addEventListener('DOMContentLoaded', () => {
  if (document.getElementById('inv-search').value)
    loadInvoice();
});
</script>

<?php require_once '../includes/footer.php'; ?>
