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

<style>
#pur-wrapper { display: grid; grid-template-columns: 1fr 340px; gap: 16px; align-items: start; }
#prod-results { position:absolute;top:100%;left:0;right:0;z-index:500;background:#fff;
  border:1px solid #dee2e6;border-radius:0 0 8px 8px;max-height:260px;overflow-y:auto;box-shadow:0 4px 12px rgba(0,0,0,.1) }
.prod-res-item { padding:10px 14px;cursor:pointer;border-bottom:1px solid #f0f0f0;display:flex;justify-content:space-between }
.prod-res-item:hover { background:#f0f7ff }
#sticky-panel { 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-cart3 me-2 text-primary"></i>New Purchase</h5>
  <a href="<?= APP_URL ?>/purchases" class="btn btn-sm btn-outline-secondary">
    <i class="bi bi-arrow-left me-1"></i>Back
  </a>
</div>

<form method="POST" action="<?= APP_URL ?>/purchases/create"
      id="purchase-form" onsubmit="return submitPurchase(event)">
  <?= Auth::csrfField() ?>
  <input type="hidden" name="items_json" id="items-json">

  <div id="pur-wrapper">

    <!-- ── LEFT: Details + Items ─────────────────────────── -->
    <div>

      <!-- Purchase Info Card -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-info-circle me-1"></i>Purchase Information
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label small fw-semibold">Supplier *</label>
              <select name="supplier_id" class="form-select" required id="supplier-select">
                <option value="">— Select Supplier —</option>
                <?php foreach ($suppliers as $s): ?>
                <option value="<?= $s['id'] ?>"
                  <?= (isset($_GET['supplier_id']) && (int)$_GET['supplier_id'] === (int)$s['id']) ? 'selected' : '' ?>>
                  <?= e($s['supplier_name']) ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label small fw-semibold">Purchase Date *</label>
              <input type="date" name="purchase_date" class="form-control"
                     value="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="col-md-3">
              <label class="form-label small fw-semibold">Reference / Bill No.</label>
              <input type="text" name="note" class="form-control"
                     placeholder="Supplier bill / ref no.">
            </div>
          </div>
        </div>
      </div>

      <!-- Product Search + Items -->
      <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>Items</span>
          <span class="badge bg-secondary" id="item-count-badge">0 items</span>
        </div>
        <div class="card-body pb-2">

          <!-- Supplier-not-selected notice -->
          <div id="no-supplier-notice" class="alert alert-warning d-flex align-items-center gap-2 py-2 mb-3">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <span class="small">Please select a supplier above first, then you can search and add products.</span>
          </div>

          <!-- Search (full catalog — enabled only after supplier is selected) -->
          <div class="position-relative mb-3" id="search-wrap" style="display:none">
            <div class="input-group">
              <span class="input-group-text bg-primary text-white">
                <i class="bi bi-upc-scan"></i>
              </span>
              <input type="text" id="prod-search" class="form-control"
                     placeholder="Scan barcode or search product name / code…"
                     autocomplete="off">
              <button class="btn btn-outline-secondary" type="button" id="clear-search"
                      style="display:none" onclick="clearSearch()">
                <i class="bi bi-x"></i>
              </button>
            </div>
            <div id="prod-results" style="display:none"></div>
          </div>

          <!-- Items Table -->
          <div class="table-responsive">
            <table class="table table-sm mb-0" id="items-table">
              <thead class="table-light">
                <tr>
                  <th style="width:32px">#</th>
                  <th>Product</th>
                  <th style="width:95px">Qty</th>
                  <th style="width:115px">Cost Price</th>
                  <th style="width:95px">Discount</th>
                  <th style="width:70px">Tax %</th>
                  <th style="width:105px" class="text-end">Line Total</th>
                  <th style="width:32px"></th>
                </tr>
              </thead>
              <tbody id="items-body">
                <tr id="empty-row">
                  <td colspan="8" class="text-center text-muted py-4">
                    <i class="bi bi-box-seam fs-2 d-block mb-1 opacity-25"></i>
                    Search or scan a product above to add it
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

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

    <!-- ── RIGHT: Sticky Summary + Payment ───────────────── -->
    <div id="sticky-panel">

      <!-- Totals -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-calculator me-1"></i>Order Summary
        </div>
        <div class="card-body p-0">
          <table class="table table-sm mb-0">
            <tr>
              <td class="ps-3 text-muted">Subtotal</td>
              <td class="text-end pe-3 fw-semibold" id="t-subtotal">
                <?= e(setting('currency_symbol','Rs.')) ?> 0.00
              </td>
            </tr>
            <tr>
              <td class="ps-3 text-muted">
                Bill Discount
                <input type="number" name="discount" class="form-control form-control-sm mt-1"
                       value="0" min="0" step="0.01" style="width:100px"
                       oninput="calcTotals()" placeholder="0.00">
              </td>
              <td class="text-end pe-3 text-danger" id="t-discount">
                − <?= e(setting('currency_symbol','Rs.')) ?> 0.00
              </td>
            </tr>
            <tr>
              <td class="ps-3 text-muted">Tax</td>
              <td class="text-end pe-3" id="t-tax">
                <?= e(setting('currency_symbol','Rs.')) ?> 0.00
              </td>
            </tr>
            <tr class="table-primary">
              <td class="ps-3 fw-bold">Grand Total</td>
              <td class="text-end pe-3 fw-bold fs-5 text-primary" id="t-total">
                <?= e(setting('currency_symbol','Rs.')) ?> 0.00
              </td>
            </tr>
          </table>
        </div>
      </div>

      <!-- Payment -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-cash-coin me-1"></i>Payment
        </div>
        <div class="card-body">
          <div class="mb-2">
            <label class="form-label small fw-semibold">Payment Method</label>
            <select name="payment_method_type" id="pmt-method-sel"
                    class="form-select form-select-sm"
                    onchange="toggleChequeFields(this.value)">
              <option value="cash">Cash</option>
              <option value="bank_transfer">Bank Transfer</option>
              <option value="cheque">Cheque</option>
              <option value="card">Card</option>
              <option value="mobile">Mobile Pay</option>
              <option value="due">Due / No Payment Yet</option>
            </select>
          </div>

          <!-- Cheque Details -->
          <div id="cheque-fields" class="p-2 rounded mb-2"
               style="display:none;background:#f0fff4;border:1px solid #6fcf97">
            <div class="row g-2">
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Cheque No. *</label>
                <input type="text" name="cheque_no" class="form-control form-control-sm"
                       placeholder="Cheque number">
              </div>
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Cheque Date</label>
                <input type="date" name="cheque_date" class="form-control form-control-sm"
                       value="<?= date('Y-m-d') ?>">
              </div>
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Bank</label>
                <input type="text" name="cheque_bank" class="form-control form-control-sm"
                       placeholder="Bank name">
              </div>
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Branch</label>
                <input type="text" name="cheque_branch" class="form-control form-control-sm"
                       placeholder="Branch">
              </div>
              <div class="col-12">
                <label class="form-label small mb-1 fw-semibold text-success">Drawer</label>
                <input type="text" name="cheque_drawer" class="form-control form-control-sm"
                       placeholder="Account holder name">
              </div>
            </div>
            <small class="text-success d-block mt-1">
              <i class="bi bi-info-circle me-1"></i>Tracked in Cheque Management until cleared.
            </small>
          </div>

          <!-- Amount Paid -->
          <div class="mb-2">
            <label class="form-label small fw-semibold" id="paid-label">Amount Paid</label>
            <div class="input-group input-group-sm">
              <span class="input-group-text"><?= e(setting('currency_symbol','Rs.')) ?></span>
              <input type="number" name="paid" id="paid-input" class="form-control fw-bold"
                     value="0" min="0" step="0.01" oninput="calcTotals()">
              <button class="btn btn-outline-secondary" type="button"
                      onclick="setFullPay()" title="Pay full amount">
                Full
              </button>
            </div>
          </div>

          <!-- Balance display -->
          <table class="table table-sm mb-0 mt-2">
            <tr>
              <td class="text-muted small">Amount Paid</td>
              <td class="text-end text-success fw-semibold" id="t-paid">0.00</td>
            </tr>
            <tr id="balance-row" class="<?= '' ?>">
              <td class="fw-bold small">Balance Due</td>
              <td class="text-end fw-bold text-danger" id="t-balance">0.00</td>
            </tr>
          </table>
        </div>
      </div>

      <!-- Save Button -->
      <button type="submit" class="btn btn-primary w-100 fw-semibold btn-lg">
        <i class="bi bi-check-circle me-2"></i>Save Purchase
      </button>
      <a href="<?= APP_URL ?>/purchases" class="btn btn-outline-secondary w-100 mt-2">
        Cancel
      </a>

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

<script>
const APP_URL = '<?= APP_URL ?>';
const SYM     = '<?= e(setting("currency_symbol","Rs.")) ?>';
let items     = [];
let searchTimer;

// ── Supplier-first gate ──────────────────────────────────────
// Search is hidden until a supplier is picked. Once picked, the
// FULL product catalog is searchable (no per-supplier filtering).
const supplierSelect   = document.getElementById('supplier-select');
const noSupplierNotice = document.getElementById('no-supplier-notice');
const searchWrap       = document.getElementById('search-wrap');

function applySupplierGate() {
  if (supplierSelect.value) {
    noSupplierNotice.style.display = 'none';
    searchWrap.style.display       = 'block';
  } else {
    noSupplierNotice.style.display = 'flex';
    searchWrap.style.display       = 'none';
  }
}
supplierSelect.addEventListener('change', applySupplierGate);
applySupplierGate(); // run on load too (handles ?supplier_id= pre-selection)

// ── Product Search (full catalog — no supplier restriction) ──
const searchInput   = document.getElementById('prod-search');
const searchResults = document.getElementById('prod-results');
const clearBtn      = document.getElementById('clear-search');

searchInput.addEventListener('input', function () {
  clearTimeout(searchTimer);
  const q = this.value.trim();
  clearBtn.style.display = q ? 'block' : 'none';
  if (!q) { searchResults.style.display = 'none'; return; }
  searchTimer = setTimeout(() => searchProducts(q), 220);
});

document.addEventListener('click', e => {
  if (!e.target.closest('#prod-search') && !e.target.closest('#prod-results')) {
    searchResults.style.display = 'none';
  }
});

searchInput.addEventListener('keydown', e => {
  if (e.key === 'Escape') clearSearch();
});

function clearSearch() {
  searchInput.value = '';
  searchResults.style.display = 'none';
  clearBtn.style.display = 'none';
  searchInput.focus();
}

async function searchProducts(q) {
  const res  = await fetch(APP_URL + '/products/search?q=' + encodeURIComponent(q));
  const data = await res.json();

  if (!data.length) {
    searchResults.innerHTML = `<div class="p-3 text-center text-muted small">No products found.</div>`;
    searchResults.style.display = 'block';
    return;
  }
  searchResults.innerHTML = data.map(p => `
    <div class="prod-res-item" onclick='addItem(${JSON.stringify(p).replace(/'/g, "&#39;")})'>
      <div>
        <div class="fw-semibold small">${esc(p.product_name)}</div>
        <div class="text-muted" style="font-size:.72rem">${esc(p.product_code)}
          ${p.barcode ? ' &middot; ' + esc(p.barcode) : ''}</div>
      </div>
      <div class="text-end">
        <div class="text-primary fw-semibold small">Cost: ${SYM} ${parseFloat(p.cost_price).toFixed(2)}</div>
        <div class="text-muted" style="font-size:.7rem">Stock: ${p.current_stock} ${p.unit || ''}</div>
      </div>
    </div>`).join('');
  searchResults.style.display = 'block';
}

// ── Cart ───────────────────────────────────────────────────
function addItem(p) {
  clearSearch();
  const ex = items.find(i => i.id == p.id);
  if (ex) { ex.qty++; renderItems(); return; }
  items.push({
    id:      p.id,
    name:    p.product_name,
    code:    p.product_code,
    qty:     1,
    cost:    parseFloat(p.cost_price) || 0,
    disc:    0,
    tax_pct: parseFloat(p.tax_percent) || 0,
  });
  renderItems();
}

function renderItems() {
  const tb = document.getElementById('items-body');
  document.getElementById('item-count-badge').textContent =
    items.length + ' item' + (items.length !== 1 ? 's' : '');

  if (!items.length) {
    tb.innerHTML = `<tr id="empty-row"><td colspan="8" class="text-center text-muted py-4">
      <i class="bi bi-box-seam fs-2 d-block mb-1 opacity-25"></i>
      Search or scan a product above to add it</td></tr>`;
    calcTotals(); return;
  }

  tb.innerHTML = items.map((item, i) => {
    const lineTotal = ((item.qty * item.cost) - item.disc).toFixed(2);
    return `<tr>
      <td class="text-muted small">${i + 1}</td>
      <td>
        <div class="fw-semibold small">${esc(item.name)}</div>
        <small class="text-muted">${esc(item.code)}</small>
      </td>
      <td>
        <input type="number" class="form-control form-control-sm"
               value="${item.qty}" min="0.01" step="0.01"
               onchange="items[${i}].qty = parseFloat(this.value)||1; renderItems()">
      </td>
      <td>
        <div class="input-group input-group-sm">
          <span class="input-group-text" style="font-size:.7rem">${SYM}</span>
          <input type="number" class="form-control"
                 value="${item.cost}" min="0" step="0.01"
                 onchange="items[${i}].cost = parseFloat(this.value)||0; renderItems()">
        </div>
      </td>
      <td>
        <input type="number" class="form-control form-control-sm"
               value="${item.disc}" min="0" step="0.01"
               onchange="items[${i}].disc = parseFloat(this.value)||0; renderItems()">
      </td>
      <td>
        <input type="number" class="form-control form-control-sm"
               value="${item.tax_pct}" min="0" step="0.01"
               onchange="items[${i}].tax_pct = parseFloat(this.value)||0; renderItems()">
      </td>
      <td class="text-end fw-semibold small">${SYM} ${lineTotal}</td>
      <td>
        <button class="btn btn-sm btn-outline-danger py-0 px-1"
                onclick="items.splice(${i},1); renderItems()">
          <i class="bi bi-trash3"></i>
        </button>
      </td>
    </tr>`;
  }).join('');
  calcTotals();
}

// ── Totals ─────────────────────────────────────────────────
function calcTotals() {
  let sub = 0, tax = 0;
  items.forEach(i => {
    const lt = (i.qty * i.cost) - i.disc;
    sub += lt;
    tax += lt * (i.tax_pct / 100);
  });
  const disc  = parseFloat(document.querySelector('[name=discount]').value) || 0;
  const paid  = parseFloat(document.getElementById('paid-input').value) || 0;
  const total = sub - disc + tax;
  const bal   = total - paid;

  document.getElementById('t-subtotal').textContent = SYM + ' ' + sub.toFixed(2);
  document.getElementById('t-discount').textContent = '− ' + SYM + ' ' + disc.toFixed(2);
  document.getElementById('t-tax').textContent      = SYM + ' ' + tax.toFixed(2);
  document.getElementById('t-total').textContent    = SYM + ' ' + total.toFixed(2);
  document.getElementById('t-paid').textContent     = SYM + ' ' + paid.toFixed(2);
  document.getElementById('t-balance').textContent  = SYM + ' ' + Math.max(0, bal).toFixed(2);

  // Highlight balance row
  const balRow = document.getElementById('balance-row');
  balRow.className = bal > 0 ? 'table-warning' : '';
}

function setFullPay() {
  const total = items.reduce((s, i) => s + (i.qty * i.cost) - i.disc, 0);
  const disc  = parseFloat(document.querySelector('[name=discount]').value) || 0;
  const tax   = items.reduce((s, i) => {
    const lt = (i.qty * i.cost) - i.disc; return s + lt * (i.tax_pct / 100);
  }, 0);
  document.getElementById('paid-input').value = Math.max(0, total - disc + tax).toFixed(2);
  calcTotals();
}

// ── Cheque fields ──────────────────────────────────────────
function toggleChequeFields(method) {
  const cf  = document.getElementById('cheque-fields');
  const lbl = document.getElementById('paid-label');
  const pi  = document.getElementById('paid-input');
  cf.style.display = method === 'cheque' ? 'block' : 'none';
  if (method === 'due') {
    lbl.textContent = 'Amount Paid (Due — pay later)';
    pi.value = '0';
    pi.readOnly = true;
  } else {
    lbl.textContent = method === 'cheque' ? 'Cheque Amount' : 'Amount Paid';
    pi.readOnly = false;
  }
  calcTotals();
}

// ── Submit ─────────────────────────────────────────────────
function submitPurchase(e) {
  if (!items.length) {
    e.preventDefault();
    alert('Please add at least one product.');
    return false;
  }
  const method = document.getElementById('pmt-method-sel').value;
  if (method === 'cheque') {
    const chqNo = document.querySelector('[name=cheque_no]').value.trim();
    if (!chqNo) {
      e.preventDefault();
      alert('Please enter the cheque number.');
      document.querySelector('[name=cheque_no]').focus();
      return false;
    }
  }
  document.getElementById('items-json').value = JSON.stringify(items);
  return true;
}

// ── Helpers ────────────────────────────────────────────────
function esc(s) {
  return String(s)
    .replace(/&/g,'&amp;').replace(/</g,'&lt;')
    .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>