<?php /* sales/return.php */ ?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-semibold mb-0">Sale Return – <?= e($sale['invoice_no']) ?></h5>
  <a href="<?= APP_URL ?>/sales/view/<?= $sale['id'] ?>" class="btn btn-sm btn-outline-secondary">Back</a>
</div>

<form method="POST"
      action="<?= APP_URL ?>/sales/return/<?= $sale['id'] ?>"
      id="return-form"
      onsubmit="return buildReturnJson(event)">
  <?= Auth::csrfField() ?>
  <input type="hidden" name="items_json" id="items-json" value="[]">

  <div class="card mb-3">
    <div class="card-header bg-transparent fw-semibold small">Select Items to Return</div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-sm mb-0">
          <thead class="table-light">
            <tr>
              <th>Product</th>
              <th>Sold Qty</th>
              <th>Already Returned</th>
              <th style="width:120px">Return Qty</th>
              <th>Unit Price</th>
              <th>Reason</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($items as $item):
              $alreadyRet = (float)($returnedMap[$item['product_id']] ?? 0);
              $maxReturn  = (float)$item['quantity'] - $alreadyRet;
            ?>
            <?php if ($maxReturn <= 0): continue; endif; ?>
            <tr>
              <td>
                <div class="fw-semibold small"><?= e($item['product_name']) ?></div>
                <small class="text-muted"><?= e($item['product_code']) ?></small>
              </td>
              <td><?= number_format((float)$item['quantity'], 2) ?></td>
              <td><?= $alreadyRet > 0 ? number_format($alreadyRet, 2) : '-' ?></td>
              <td>
                <input type="number"
                       class="form-control form-control-sm ret-qty"
                       data-id="<?= (int)$item['product_id'] ?>"
                       data-price="<?= (float)$item['selling_price'] ?>"
                       min="0"
                       max="<?= $maxReturn ?>"
                       step="0.01"
                       value="0"
                       oninput="calcTotal()">
              </td>
              <td><?= currency((float)$item['selling_price']) ?></td>
              <td>
                <input type="text" class="form-control form-control-sm ret-reason" placeholder="Reason">
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-md-4">
      <label class="form-label small fw-semibold">Refund Method</label>
      <select name="refund_method" class="form-select" id="refundMethodSel" onchange="updateAccountInfo()">
        <?php foreach([
          'cash'          => 'Cash',
          'card'          => 'Card',
          'bank_transfer' => 'Bank Transfer',
          'mobile'        => 'Mobile Pay',
        ] as $val => $lbl):
          // Get the linked account name for display
          $acctId = (int)(setting('pmt_account_'.$val,'') ?: 0);
          $acctName = '';
          if($acctId > 0){
            $acc = Database::fetchOne('SELECT account_name FROM finance_accounts WHERE id=?', [$acctId]);
            $acctName = $acc ? $acc['account_name'] : '';
          }
          // Auto-select the method that matches the original sale's first payment
          $pmts = Database::fetchAll('SELECT payment_method FROM sale_payments WHERE sale_id=? LIMIT 1',[(int)$sale['id']]);
          $origMethod = $pmts[0]['payment_method'] ?? 'cash';
        ?>
        <option value="<?=$val?>"
                data-account="<?=e($acctName)?>"
                data-account-id="<?=$acctId?>"
                <?=$val===$origMethod?'selected':''?>>
          <?=$lbl?><?=$acctName?' — '.$acctName:' (no account linked)'?>
        </option>
        <?php endforeach;?>
      </select>
      <div id="accountInfoBox" class="mt-1"></div>
    </div>
    <div class="col-md-3">
      <label class="form-label small">Return Total</label>
      <div class="input-group">
        <span class="input-group-text"><?= e(setting('currency_symbol','Rs.')) ?></span>
        <input type="text" id="return-total" class="form-control fw-bold" readonly value="0.00">
      </div>
    </div>
    <div class="col-md-4">
      <label class="form-label small">Note</label>
      <input type="text" name="note" class="form-control" placeholder="Optional note">
    </div>
    <div class="col-12">
      <button type="submit" class="btn btn-warning px-4">
        <i class="bi bi-arrow-return-left me-1"></i>Process Return & Update Stock
      </button>
      <a href="<?= APP_URL ?>/sales/view/<?= $sale['id'] ?>" class="btn btn-outline-secondary ms-2">Cancel</a>
    </div>
  </div>
</form>

<script>
function updateAccountInfo() {
  const sel   = document.getElementById('refundMethodSel');
  const opt   = sel.selectedOptions[0];
  const acct  = opt.dataset.account;
  const box   = document.getElementById('accountInfoBox');
  if (acct) {
    box.innerHTML = `<span style="font-size:.72rem;color:#16a34a">
      <i class="bi bi-bank2 me-1"></i>Will deduct from: <strong>${acct}</strong>
    </span>`;
  } else {
    box.innerHTML = `<span style="font-size:.72rem;color:#94a3b8">
      <i class="bi bi-info-circle me-1"></i>No account linked — link one in Settings → POS & Tax
    </span>`;
  }
}
// Run on load
document.addEventListener('DOMContentLoaded', updateAccountInfo);

function calcTotal() {
  let t = 0;
  document.querySelectorAll('.ret-qty').forEach(el => {
    t += (parseFloat(el.value) || 0) * parseFloat(el.dataset.price);
  });
  document.getElementById('return-total').value = t.toFixed(2);
}

function buildReturnJson(e) {
  const rows = [];
  document.querySelectorAll('.ret-qty').forEach((el, i) => {
    const qty = parseFloat(el.value) || 0;
    if (qty <= 0) return;
    const reason = document.querySelectorAll('.ret-reason')[i]?.value || '';
    rows.push({
      product_id:    parseInt(el.dataset.id, 10),
      quantity:      qty,
      selling_price: parseFloat(el.dataset.price),
      total:         parseFloat((qty * parseFloat(el.dataset.price)).toFixed(2)),
      reason:        reason
    });
  });

  if (rows.length === 0) {
    e.preventDefault();
    alert('Please enter a return quantity for at least one item.');
    return false;
  }

  document.getElementById('items-json').value = JSON.stringify(rows);
  return true;   // allow form to submit
}
</script>