<?php
// edit_sale.php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

// helpers
function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function json_out($arr){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($arr, JSON_UNESCAPED_UNICODE); exit; }

$lang = $_GET['lang'] ?? 'en';
$is_ar = $lang === 'ar';
$dir = $is_ar ? 'rtl' : 'ltr';
$is_admin = true;

// AJAX: search products
if (isset($_GET['action']) && $_GET['action'] === 'search_products') {
    $q = trim($_GET['q'] ?? '');
    if ($q === '') json_out(['success'=>true, 'results'=>[]]);
    try {
        $like = "%$q%";
        $sql = "SELECT id, sku,
                       COALESCE(NULLIF(name_en,''), name_ar, '') AS name,
                       COALESCE(price,0) AS price,
                       COALESCE(cost,0) AS cost,
                       COALESCE(stock,0) AS stock
                FROM products
                WHERE (name_en LIKE :q OR name_ar LIKE :q OR sku LIKE :q)
                  AND COALESCE(stock,0) > 0
                ORDER BY name ASC
                LIMIT 60";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':q'=>$like]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        json_out(['success'=>true,'results'=>$rows]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

// get sale id
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id <= 0) {
    die($is_ar ? 'معرف الفاتورة غير صالح.' : 'Invalid sale ID.');
}

// fetch sale
$stmt = $pdo->prepare("SELECT * FROM sales WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$sale) {
    die($is_ar ? 'الفاتورة غير موجودة.' : 'Sale not found.');
}

// fetch sale items
$stmt = $pdo->prepare("SELECT si.*, p.name_en, p.name_ar, p.sku, p.price as product_price, p.cost as product_cost
                       FROM sale_items si
                       LEFT JOIN products p ON p.id = si.product_id
                       WHERE si.sale_id = ?");
$stmt->execute([$id]); // ← تمت إضافة علامة $
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// customers and products (for selects / search)
$customers = $pdo->query("SELECT id, name, COALESCE(balance,0) AS balance FROM customers ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
$products_for_select = $pdo->query("SELECT id, COALESCE(NULLIF(name_en,''), name_ar, '') AS name, sku, price, cost, COALESCE(stock,0) AS stock FROM products WHERE COALESCE(stock,0) > 0 ORDER BY name ASC LIMIT 200")->fetchAll(PDO::FETCH_ASSOC);

// Handle POST (save edits)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $posted_products = $_POST['product_id'] ?? [];
    $posted_qty = $_POST['qty'] ?? [];
    $posted_price = $_POST['unit_price'] ?? [];
    $customer_id = !empty($_POST['customer_id']) ? intval($_POST['customer_id']) : null;
    $paid = isset($_POST['paid']) ? floatval($_POST['paid']) : 0.0;
    $payment_method = $_POST['payment_method'] ?? 'cash';
    $note = trim($_POST['note'] ?? '');

    if (!is_array($posted_products) || count($posted_products) === 0) {
        $error = $is_ar ? 'أضف منتجًا واحدًا على الأقل.' : 'Add at least one product.';
    } else {
        try {
            $pdo->beginTransaction();

            // old invoice number (to find & remove related transactions)
            $old_invoice_no = $sale['invoice_no'] ?? null;

            // --- REMOVE old cash/customer transactions related to this invoice ---
            if ($old_invoice_no) {
                // delete cash_transactions entries that mention the invoice (we use description LIKE ...)
                $delCash = $pdo->prepare("DELETE FROM cash_transactions WHERE description LIKE ?");
                $delCash->execute(["%{$old_invoice_no}%"]);

                // delete customer_transactions that mention the invoice in note (same logic)
                $delCt = $pdo->prepare("DELETE FROM customer_transactions WHERE note LIKE ?");
                $delCt->execute(["%{$old_invoice_no}%"]);
            }

            // 1) Restore previous stock (reverse previous sale quantities)
            $oldItemsStmt = $pdo->prepare("SELECT product_id, qty FROM sale_items WHERE sale_id = ?");
            $oldItemsStmt->execute([$id]);
            $oldItemsList = $oldItemsStmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($oldItemsList as $oi) {
                $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?")->execute([$oi['qty'], $oi['product_id']]);
            }

            // 2) Remove old sale items (already removed their stock)
            $pdo->prepare("DELETE FROM sale_items WHERE sale_id = ?")->execute([$id]);

            // 3) Insert new items, update stock, compute totals & profit
            $total = 0.0;
            $profit = 0.0;
            $validated_count = 0;

            foreach ($posted_products as $i => $pid_raw) {
                $pid = intval($pid_raw);
                $qty = isset($posted_qty[$i]) ? floatval($posted_qty[$i]) : 0;
                $price = isset($posted_price[$i]) ? floatval($posted_price[$i]) : 0;

                if ($pid <= 0 || $qty <= 0) continue;

                $pstmt = $pdo->prepare("SELECT id, COALESCE(price,0) AS db_price, COALESCE(cost,0) AS cost, COALESCE(stock,0) AS stock FROM products WHERE id = ? LIMIT 1");
                $pstmt->execute([$pid]);
                $prow = $pstmt->fetch(PDO::FETCH_ASSOC);
                if (!$prow) {
                    throw new Exception("Product #$pid not found");
                }
                if ($qty > floatval($prow['stock'])) {
                    throw new Exception("Insufficient stock for product #{$pid}");
                }

                $unit_price = $price > 0 ? $price : floatval($prow['db_price']);
                $subtotal = round($unit_price * $qty, 2);
                $total += $subtotal;
                $profit += ($unit_price - floatval($prow['cost'])) * $qty;

                $ins = $pdo->prepare("INSERT INTO sale_items (sale_id, product_id, qty, unit_price, subtotal) VALUES (?, ?, ?, ?, ?)");
                $ins->execute([$id, $pid, $qty, $unit_price, $subtotal]);

                $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?")->execute([$qty, $pid]);

                $validated_count++;
            }

            if ($validated_count === 0) {
                throw new Exception($is_ar ? "لا توجد عناصر صالحة للحفظ." : "No valid items to save.");
            }

            // 4) Update sales table (keep the same invoice_no)
            $upd = $pdo->prepare("UPDATE sales SET customer_id = ?, total = ?, paid = ?, payment_method = ?, profit = ?, created_at = NOW() WHERE id = ?");
            $upd->execute([$customer_id ? $customer_id : null, $total, $paid, $payment_method, $profit, $id]);

            // 5) Adjust customers.balance and record transactions:
            // Reverse old customer's balance effect (old_due)
            $old_total = floatval($sale['total'] ?? 0);
            $old_paid = floatval($sale['paid'] ?? 0);
            $old_customer_id = $sale['customer_id'] ? intval($sale['customer_id']) : null;
            $old_due = round(max(0, $old_total - $old_paid), 2);

            if ($old_customer_id) {
                // subtract old_due from old customer's balance
                $pdo->prepare("UPDATE customers SET balance = COALESCE(balance,0) - ? WHERE id = ?")->execute([$old_due, $old_customer_id]);

                // audit reversal transaction (we keep a record that we reversed)
                $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date) VALUES (?, ?, ?, ?, ?, NOW())")
                    ->execute([$old_customer_id, 'adjustment', -$old_due, null, "Reversal for edited invoice {$old_invoice_no}"]);
            }

            // Apply new effect to new customer OR cash-record
            $new_due = round(max(0, $total - $paid), 2);

            if ($customer_id) {
                // get current balance AFTER previous reversal above
                $curbalStmt = $pdo->prepare("SELECT COALESCE(balance,0) FROM customers WHERE id = ? LIMIT 1");
                $curbalStmt->execute([$customer_id]);
                $curbal_val = floatval($curbalStmt->fetchColumn() ?? 0);
                $new_balance = $curbal_val + $new_due;
                $pdo->prepare("UPDATE customers SET balance = ? WHERE id = ?")->execute([$new_balance, $customer_id]);

                // record payment (if any) and debt (if any) using invoice_no for note
                if ($paid > 0) {
                    $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date) VALUES (?, 'payment', ?, ?, ?, NOW())")
                        ->execute([$customer_id, $paid, $new_balance, "Payment for {$old_invoice_no}"]);
                }
                if ($new_due > 0) {
                    $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date) VALUES (?, 'debt', ?, ?, ?, NOW())")
                        ->execute([$customer_id, $new_due, $new_balance, "Invoice {$old_invoice_no} (due)"]);
                }
            } else {
                // cash / anonymous: create cash_transactions entry (with invoice_no in description for later identification)
                if ($paid > 0) {
                    $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, created_at) VALUES ('in', ?, ?, NOW())")
                        ->execute([$paid, "Payment for {$old_invoice_no}"]);
                }
            }

            $pdo->commit();

            header("Location: sales_list.php?msg=updated");
            exit;

        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $error = $e->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $dir ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $is_ar ? 'تعديل الفاتورة' : 'Edit Sale' ?> #<?= esc($sale['invoice_no']) ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
body{background:#f7f9fc;font-family:Inter,system-ui,Arial;padding:18px}
.card{border-radius:10px;box-shadow:0 6px 18px rgba(16,24,40,0.06)}
.table thead th{background:#fbfbfb}
.small-muted{font-size:0.85rem;color:#6b7280}
.cost-tiny{font-size:0.88rem;color:#6b7280}
.remove-btn{background:#e53e3e;border:none;color:#fff;border-radius:6px;padding:6px 10px}
.add-btn{background:#059669;border:none;color:#fff;border-radius:6px;padding:6px 10px}
.save-btn{background:#0ea5e9;border:none;color:#fff;border-radius:6px;padding:8px 14px}
</style>
</head>
<body>
<div class="container">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3><i class="fa fa-file-invoice"></i> <?= $is_ar ? 'تعديل الفاتورة' : 'Edit Invoice' ?> #<?= esc($sale['invoice_no']) ?></h3>
    <div class="d-flex gap-2">
      <a href="index.php" class="btn btn-outline-secondary btn-sm"><i class="fa fa-home"></i> <?= $is_ar ? 'الرئيسية' : 'Home' ?></a>
      <a href="sales_view.php?id=<?= $id ?>" class="btn btn-outline-primary btn-sm"><i class="fa fa-eye"></i> <?= $is_ar ? 'عرض/طباعة' : 'View/Print' ?></a>
    </div>
  </div>

  <?php if(!empty($error)): ?>
    <div class="alert alert-danger"><?= esc($error) ?></div>
  <?php endif; ?>

  <div class="card p-3 mb-3">
    <form method="post" id="editSaleForm">
      <div class="row g-3 mb-3">
        <div class="col-md-3">
          <label class="form-label"><?= $is_ar ? 'رقم الفاتورة' : 'Invoice #' ?></label>
          <input class="form-control" value="<?= esc($sale['invoice_no']) ?>" readonly>
        </div>
        <div class="col-md-3">
          <label class="form-label"><?= $is_ar ? 'التاريخ' : 'Date' ?></label>
          <input type="datetime-local" name="date" class="form-control" value="<?= date('Y-m-d\TH:i', strtotime($sale['created_at'])) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label"><?= $is_ar ? 'العميل' : 'Customer' ?></label>
          <select name="customer_id" id="customerSelect" class="form-select">
            <option value=""><?= $is_ar ? 'نقدي / بدون عميل' : 'Cash / No customer' ?></option>
            <?php foreach ($customers as $c): ?>
              <option value="<?= $c['id'] ?>" <?= $c['id']==$sale['customer_id'] ? 'selected' : '' ?>>
                <?= esc($c['name']) ?> (<?= number_format($c['balance'],2) ?>)
              </option>
            <?php endforeach; ?>
          </select>
          <div id="customerBalance" class="small-muted mt-1"><?= $is_ar ? 'رصيد العميل سيظهر هنا' : 'Customer balance will show here' ?></div>
        </div>
        <div class="col-md-3">
          <label class="form-label"><?= $is_ar ? 'طريقة الدفع' : 'Payment Method' ?></label>
          <select name="payment_method" class="form-select">
            <option value="cash" <?= $sale['payment_method']=='cash' ? 'selected' : '' ?>><?= $is_ar ? 'نقدي' : 'Cash' ?></option>
            <option value="debt" <?= $sale['payment_method']=='debt' ? 'selected' : '' ?>><?= $is_ar ? 'دين' : 'Debt' ?></option>
            <option value="card" <?= $sale['payment_method']=='card' ? 'selected' : '' ?>><?= $is_ar ? 'بطاقة' : 'Card' ?></option>
          </select>
        </div>
      </div>

      <div class="mb-3 position-relative">
        <label class="form-label"><?= $is_ar ? 'بحث منتج (SKU أو اسم)' : 'Search product (SKU or Name)' ?></label>
        <input id="productSearch" class="form-control" placeholder="<?= $is_ar ? 'اكتب SKU أو اسم المنتج ثم اختر' : 'Type SKU or name then pick from list' ?>" autocomplete="off">
        <div id="suggestBox" class="d-none" style="position:absolute;left:0;right:0;z-index:9999;background:#fff;border:1px solid #eee;border-radius:6px;max-height:260px;overflow:auto"></div>
      </div>

      <div class="table-responsive mb-2">
        <table class="table table-bordered align-middle" id="itemsTable">
          <thead>
            <tr>
              <th style="width:120px">SKU</th>
              <th><?= $is_ar ? 'المنتج' : 'Product' ?></th>
              <th style="width:120px"><?= $is_ar ? 'سعر الوحدة' : 'Unit Price' ?></th>
              <th style="width:100px"><?= $is_ar ? 'الكمية' : 'Qty' ?></th>
              <th style="width:120px"><?= $is_ar ? 'الاجمالي' : 'Subtotal' ?></th>
              <?php if($is_admin): ?><th style="width:120px"><?= $is_ar ? 'سعر الشراء' : 'Cost' ?></th><?php endif; ?>
              <th style="width:60px"></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($items as $it): ?>
              <tr data-prod-id="<?= intval($it['product_id']) ?>">
                <td class="sku"><?= esc($it['sku'] ?? '') ?></td>
                <td class="pname"><?= esc($it['name_en'] ?: $it['name_ar'] ?: '') ?></td>
                <td><input type="number" name="unit_price[]" class="form-control unit-price" step="0.01" value="<?= number_format($it['unit_price'],2,'.','') ?>"></td>
                <td><input type="number" name="qty[]" class="form-control qty" step="0.01" min="0" value="<?= number_format($it['qty'],2,'.','') ?>"></td>
                <td class="sub text-end"><?= number_format($it['subtotal'],2,'.','') ?></td>
                <?php if($is_admin): ?><td class="cost-cell text-end"><?= number_format($it['product_cost'] ?? 0,2,'.','') ?></td><?php endif; ?>
                <td class="text-center">
                  <input type="hidden" name="product_id[]" value="<?= intval($it['product_id']) ?>">
                  <button type="button" class="remove-btn" onclick="removeRow(this)"><i class="fa fa-trash"></i></button>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="d-flex gap-2 mb-3">
        <button type="button" class="add-btn" id="addEmptyRowBtn"><i class="fa fa-plus"></i> <?= $is_ar ? 'أضف صف' : 'Add Row' ?></button>
        <button type="button" class="add-btn" id="addFromListBtn"><i class="fa fa-list"></i> <?= $is_ar ? 'أضف من المنتجات' : 'Add From Products' ?></button>
      </div>

      <div class="row g-3 mb-3">
        <div class="col-md-4">
          <label class="form-label"><?= $is_ar ? 'المدفوع' : 'Amount Paid' ?></label>
          <input type="number" name="paid" step="0.01" class="form-control" value="<?= number_format($sale['paid'],2,'.','') ?>">
        </div>
        <div class="col-md-8">
          <label class="form-label"><?= $is_ar ? 'ملاحظة' : 'Note' ?></label>
          <input type="text" name="note" class="form-control" value="<?= esc($sale['note'] ?? '') ?>">
        </div>
      </div>

      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="small-muted"><?= $is_ar ? 'الإجمالي التقريبي سيظهر أثناء التعديل' : 'Totals will update while editing' ?></div>
          <div class="fw-bold"><?= $is_ar ? 'الإجمالي:' : 'Total:' ?> <span id="displayTotal">0.00</span></div>
        </div>
        <div>
          <button type="submit" class="save-btn"><?= $is_ar ? 'حفظ التعديلات' : 'Save Changes' ?></button>
        </div>
      </div>

    </form>
  </div>
</div>

<script>
/* (client-side JS unchanged — same as قبل) */
const productSearch = document.getElementById('productSearch');
const suggestBox = document.getElementById('suggestBox');
const itemsTableBody = document.querySelector('#itemsTable tbody');
const customerSelect = document.getElementById('customerSelect');
const customerBalanceEl = document.getElementById('customerBalance');
const displayTotalEl = document.getElementById('displayTotal');
let suggestTimer = null;

function escapeHtml(s){ return s ? s.toString().replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') : ''; }

productSearch.addEventListener('input', ()=>{
  const q = productSearch.value.trim();
  suggestBox.innerHTML = '';
  if (suggestTimer) clearTimeout(suggestTimer);
  if (q.length < 2) { suggestBox.classList.add('d-none'); return; }
  suggestTimer = setTimeout(async ()=>{
    try {
      const res = await fetch('?action=search_products&q=' + encodeURIComponent(q));
      const j = await res.json();
      if (j.success && j.results.length) {
        suggestBox.innerHTML = j.results.map(r=>`
          <div data-id="${r.id}" data-sku="${escapeHtml(r.sku||'')}" data-name="${escapeHtml(r.name||'')}" data-price="${r.price}" data-cost="${r.cost}" data-stock="${r.stock}" style="padding:8px;border-bottom:1px solid #f1f5f9;cursor:pointer">
            <div><strong>${escapeHtml(r.name)}</strong> <small class="small-muted">[${escapeHtml(r.sku||'')}]</small></div>
            <div class="small-muted">Price: ${parseFloat(r.price).toFixed(2)} · Stock: ${r.stock}</div>
          </div>
        `).join('');
      } else {
        suggestBox.innerHTML = '<div class="small-muted p-2">No results</div>';
      }
      suggestBox.classList.remove('d-none');
    } catch(e){
      suggestBox.classList.add('d-none');
      console.error(e);
    }
  }, 220);
});

suggestBox.addEventListener('click', e=>{
  const div = e.target.closest('div[data-id]');
  if (!div) return;
  const id = div.dataset.id;
  const sku = div.dataset.sku;
  const name = div.dataset.name;
  const price = parseFloat(div.dataset.price||0).toFixed(2);
  const cost = parseFloat(div.dataset.cost||0).toFixed(2);
  addRowWithProduct(id, sku, name, price, cost);
  productSearch.value = '';
  suggestBox.classList.add('d-none');
});

function addRowWithProduct(id, sku, name, price, cost){
  const tr = document.createElement('tr');
  tr.dataset.prodId = id;
  tr.innerHTML = `
    <td class="sku">${escapeHtml(sku)}</td>
    <td class="pname">${escapeHtml(name)}</td>
    <td><input type="number" name="unit_price[]" class="form-control unit-price" step="0.01" value="${parseFloat(price).toFixed(2)}"></td>
    <td><input type="number" name="qty[]" class="form-control qty" step="0.01" min="0" value="1"></td>
    <td class="sub text-end">0.00</td>
    <?php if($is_admin): ?> <td class="cost-cell text-end">${parseFloat(cost).toFixed(2)}</td> <?php endif; ?>
    <td class="text-center"><input type="hidden" name="product_id[]" value="${id}"><button type="button" class="remove-btn" onclick="removeRow(this)"><i class="fa fa-trash"></i></button></td>
  `;
  itemsTableBody.appendChild(tr);
  tr.querySelector('.unit-price').addEventListener('input', calcTotals);
  tr.querySelector('.qty').addEventListener('input', calcTotals);
  calcTotals();
}

function addEmptyRow(){
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td class="sku"></td>
    <td><input type="text" class="form-control pname-input" placeholder="Product name"></td>
    <td><input type="number" name="unit_price[]" class="form-control unit-price" step="0.01" value="0"></td>
    <td><input type="number" name="qty[]" class="form-control qty" step="0.01" min="0" value="1"></td>
    <td class="sub text-end">0.00</td>
    <?php if($is_admin): ?> <td class="cost-cell text-end">0.00</td> <?php endif; ?>
    <td class="text-center"><input type="hidden" name="product_id[]" value=""><button type="button" class="remove-btn" onclick="removeRow(this)"><i class="fa fa-trash"></i></button></td>
  `;
  itemsTableBody.appendChild(tr);
  tr.querySelector('.unit-price').addEventListener('input', calcTotals);
  tr.querySelector('.qty').addEventListener('input', calcTotals);
  calcTotals();
}

function removeRow(btn){ btn.closest('tr').remove(); calcTotals(); }

document.getElementById('addEmptyRowBtn').addEventListener('click', addEmptyRow);
document.getElementById('addFromListBtn').addEventListener('click', ()=>{ productSearch.focus(); });

function calcTotals(){
  let total = 0;
  document.querySelectorAll('#itemsTable tbody tr').forEach(tr=>{
    const qtyEl = tr.querySelector('.qty');
    const priceEl = tr.querySelector('.unit-price');
    const subEl = tr.querySelector('.sub');
    const qty = qtyEl ? parseFloat(qtyEl.value) || 0 : 0;
    const price = priceEl ? parseFloat(priceEl.value) || 0 : 0;
    const sub = parseFloat((qty * price).toFixed(2));
    if (subEl) subEl.textContent = sub.toFixed(2);
    total += sub;
  });
  displayTotalEl.textContent = total.toFixed(2);
  return total;
}

productSearch.addEventListener('keydown', e=>{
  if (e.key === 'Enter') e.preventDefault();
});

customerSelect.addEventListener('change', async ()=>{
  const id = customerSelect.value;
  if (!id) { customerBalanceEl.textContent = '<?= $is_ar ? 'رصيد العميل سيظهر هنا' : 'Customer balance will show here' ?>'; return; }
  customerBalanceEl.textContent = 'Loading...';
  try {
    const res = await fetch('?action=get_customer_balance&id=' + encodeURIComponent(id));
    const j = await res.json();
    if (j.success) customerBalanceEl.textContent = 'Balance: ' + parseFloat(j.balance).toFixed(2);
    else customerBalanceEl.textContent = 'Error';
  } catch(e){
    customerBalanceEl.textContent = 'Error';
  }
});

document.getElementById('editSaleForm').addEventListener('submit', function(){
  document.querySelectorAll('#itemsTable tbody tr').forEach(tr=>{
    if (!tr.querySelector('input[name="product_id[]"]')) {
      const hid = document.createElement('input');
      hid.type = 'hidden'; hid.name = 'product_id[]'; hid.value = '';
      tr.appendChild(hid);
    }
  });
});

calcTotals();
</script>
</body>
</html>
