<?php /* purchases/return.php */ ?>

<style>
#ret-wrapper { display:grid; grid-template-columns:1fr 320px; gap:16px; align-items:start; }
#ret-sticky  { position:sticky; top:70px; }
</style>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-semibold mb-0">
    <i class="bi bi-arrow-return-left me-2 text-warning"></i>
    Purchase Return — <span class="text-primary"><?= e($purchase['invoice_no']) ?></span>
  </h5>
  <a href="<?= APP_URL ?>/purchases/view/<?= $purchase['id'] ?>"
     class="btn btn-sm btn-outline-secondary">
    <i class="bi bi-arrow-left me-1"></i>Back to Purchase
  </a>
</div>

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

  <div id="ret-wrapper">

    <!-- LEFT: Purchase info + Items -->
    <div>

      <!-- Purchase Info -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-receipt me-1"></i>Original Purchase
        </div>
        <div class="card-body">
          <div class="row g-2 small">
            <div class="col-6 col-md-3">
              <div class="text-muted">Invoice</div>
              <div class="fw-semibold"><?= e($purchase['invoice_no']) ?></div>
            </div>
            <div class="col-6 col-md-3">
              <div class="text-muted">Supplier</div>
              <div class="fw-semibold"><?= e($purchase['supplier_name']) ?></div>
            </div>
            <div class="col-6 col-md-3">
              <div class="text-muted">Purchase Date</div>
              <div><?= fDate($purchase['purchase_date']) ?></div>
            </div>
            <div class="col-6 col-md-3">
              <div class="text-muted">Purchase Total</div>
              <div class="fw-bold text-primary"><?= currency($purchase['total']) ?></div>
            </div>
          </div>
        </div>
      </div>

      <!-- Items Table -->
      <div class="card mb-3">
        <div class="card-header bg-transparent d-flex justify-content-between align-items-center py-2">
          <span class="fw-semibold small">
            <i class="bi bi-box-seam me-1"></i>Select Items to Return
          </span>
          <div class="d-flex gap-2">
            <button type="button" class="btn btn-sm btn-outline-secondary py-0 px-2"
                    onclick="setAll(0)">Clear All</button>
            <button type="button" class="btn btn-sm btn-outline-warning py-0 px-2"
                    onclick="setAll()">Return All</button>
          </div>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-sm mb-0">
              <thead class="table-dark">
                <tr>
                  <th>#</th>
                  <th>Product</th>
                  <th class="text-end">Purchased</th>
                  <th class="text-end">Already Returned</th>
                  <th class="text-end">Returnable</th>
                  <th style="width:115px">Return Qty</th>
                  <th class="text-end">Cost Price</th>
                  <th class="text-end">Line Total</th>
                  <th>Reason</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($items as $i => $item):
                  $alreadyReturned = (float) Database::fetchColumn(
                      'SELECT COALESCE(SUM(pri.quantity),0)
                       FROM purchase_return_items pri
                       JOIN purchase_returns pr ON pr.id = pri.purchase_return_id
                       WHERE pr.purchase_id = ? AND pri.product_id = ?',
                      [(int)$purchase['id'], (int)$item['product_id']]
                  );
                  $returnable = max(0, (float)$item['quantity'] - $alreadyReturned);
                ?>
                <tr id="row-<?= $i ?>">
                  <td class="text-muted small"><?= $i + 1 ?></td>
                  <td>
                    <div class="fw-semibold small"><?= e($item['product_name']) ?></div>
                    <small class="text-muted"><?= e($item['product_code']) ?></small>
                  </td>
                  <td class="text-end"><?= number_format((float)$item['quantity'], 2) ?></td>
                  <td class="text-end <?= $alreadyReturned > 0 ? 'text-warning' : 'text-muted' ?>">
                    <?= $alreadyReturned > 0 ? number_format($alreadyReturned, 2) : '—' ?>
                  </td>
                  <td class="text-end fw-semibold <?= $returnable <= 0 ? 'text-muted' : '' ?>">
                    <?= number_format($returnable, 2) ?>
                  </td>
                  <td>
                    <?php if ($returnable > 0): ?>
                    <input type="number"
                           class="form-control form-control-sm ret-qty"
                           id="qty-<?= $i ?>"
                           data-id="<?= (int)$item['product_id'] ?>"
                           data-cost="<?= (float)$item['cost_price'] ?>"
                           data-max="<?= $returnable ?>"
                           data-name="<?= e($item['product_name']) ?>"
                           data-row="<?= $i ?>"
                           min="0"
                           max="<?= $returnable ?>"
                           step="0.01"
                           value="0"
                           oninput="calcRow(<?= $i ?>); calcTotal()">
                    <?php else: ?>
                    <span class="badge bg-secondary">Fully Returned</span>
                    <?php endif; ?>
                  </td>
                  <td class="text-end"><?= currency((float)$item['cost_price']) ?></td>
                  <td class="text-end fw-semibold" id="line-<?= $i ?>">—</td>
                  <td>
                    <?php if ($returnable > 0): ?>
                    <input type="text" class="form-control form-control-sm ret-reason"
                           data-row="<?= $i ?>"
                           placeholder="e.g. Damaged">
                    <?php endif; ?>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Note -->
      <div class="card mb-3">
        <div class="card-body">
          <label class="form-label small fw-semibold">
            <i class="bi bi-chat-text me-1"></i>Return Note
          </label>
          <textarea name="note" class="form-control" rows="2"
                    placeholder="Optional note about this return…"></textarea>
        </div>
      </div>

    </div><!-- /left -->

    <!-- RIGHT: Sticky Summary -->
    <div id="ret-sticky">
      <div class="card mb-3 border-warning">
        <div class="card-header bg-warning bg-opacity-10 fw-semibold small text-warning">
          <i class="bi bi-calculator me-1"></i>Return Summary
        </div>
        <div class="card-body">

          <!-- Return Total -->
          <div class="text-center py-2 mb-3 rounded" style="background:#fff8e1">
            <div class="text-muted small">Return Total</div>
            <div class="fw-bold fs-4 text-warning" id="return-total-display">
              <?= e(setting('currency_symbol','Rs.')) ?> 0.00
            </div>
            <input type="hidden" id="return-total" value="0">
          </div>

          <!-- Refund Method -->
          <div class="mb-3">
            <label class="form-label small fw-semibold">Refund / Adjustment Method</label>
            <select name="refund_method" class="form-select form-select-sm">
              <option value="cash">Cash Refund</option>
              <option value="bank_transfer">Bank Transfer</option>
              <option value="deduct">Deduct from Next Invoice</option>
              <option value="credit_note">Credit Note</option>
            </select>
          </div>

          <!-- Items selected -->
          <div id="selected-summary" class="mb-3 small text-muted">
            No items selected.
          </div>

          <button type="submit" class="btn btn-warning w-100 fw-semibold">
            <i class="bi bi-arrow-return-left me-1"></i>Process Return
          </button>
          <a href="<?= APP_URL ?>/purchases/view/<?= $purchase['id'] ?>"
             class="btn btn-outline-secondary w-100 mt-2">
            Cancel
          </a>
        </div>
      </div>
    </div><!-- /right -->

  </div><!-- /wrapper -->
</form>

<script>
const SYM = '<?= e(setting("currency_symbol","Rs.")) ?>';

function calcRow(i) {
  const qtyEl = document.getElementById('qty-' + i);
  const lineEl = document.getElementById('line-' + i);
  if (!qtyEl) return;
  const qty  = parseFloat(qtyEl.value) || 0;
  const cost = parseFloat(qtyEl.dataset.cost) || 0;
  const max  = parseFloat(qtyEl.dataset.max) || 0;

  // Clamp to max
  if (qty > max) { qtyEl.value = max; }

  const line = (Math.min(qty, max) * cost).toFixed(2);
  lineEl.textContent = qty > 0 ? SYM + ' ' + line : '—';
}

function calcTotal() {
  let total = 0;
  let count = 0;
  let summary = [];

  document.querySelectorAll('.ret-qty').forEach(el => {
    const qty  = parseFloat(el.value) || 0;
    const cost = parseFloat(el.dataset.cost) || 0;
    if (qty > 0) {
      total += qty * cost;
      count++;
      summary.push(el.dataset.name + ' ×' + qty);
    }
  });

  document.getElementById('return-total').value = total.toFixed(2);
  document.getElementById('return-total-display').textContent = SYM + ' ' + total.toFixed(2);
  document.getElementById('selected-summary').textContent =
    count > 0 ? count + ' item' + (count > 1 ? 's' : '') + ' selected' : 'No items selected.';
}

function setAll(val) {
  document.querySelectorAll('.ret-qty').forEach((el, i) => {
    el.value = (val === undefined) ? el.dataset.max : val;
    calcRow(i);
  });
  calcTotal();
}

function buildReturnJson(e) {
  const rows = [];
  document.querySelectorAll('.ret-qty').forEach((el, i) => {
    const qty = parseFloat(el.value) || 0;
    if (qty <= 0) return;
    const max = parseFloat(el.dataset.max) || 0;
    if (qty > max) { el.value = max; }
    const reason = document.querySelectorAll('.ret-reason')[i]?.value.trim() || '';
    rows.push({
      product_id: parseInt(el.dataset.id, 10),
      quantity:   Math.min(qty, max),
      cost_price: parseFloat(el.dataset.cost),
      total:      parseFloat((Math.min(qty, max) * parseFloat(el.dataset.cost)).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;
}
</script>
