<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/init.php';
app_require_login();

app_module_assert_access('pos_orders');

$requestedCompanyId = (int) ($_REQUEST['company_id'] ?? 0);
$companyId = app_effective_company_id($requestedCompanyId > 0 ? $requestedCompanyId : null, true);
if ($companyId !== null && $companyId > 0) {
    app_set_context_company_id($companyId);
}
$company = $companyId ? app_company_by_id((int) $companyId) : null;

$selectedSessionId = (int) ($_REQUEST['session_id'] ?? 0);

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        app_verify_csrf();
        $action = app_normalize_whitespace((string) ($_POST['action'] ?? ''));
        if ($companyId === null || $companyId <= 0) {
            throw new RuntimeException(app_t('Company context is required for POS.'));
        }

        if ($action === 'open_session') {
            app_enforce_current_role_can('pos_sessions', 'create');
            $selectedSessionId = app_pos_open_session(
                (int) $companyId,
                app_integer($_POST['register_id'] ?? 0),
                app_number($_POST['opening_cash_counted'] ?? 0)
            );
            app_flash('success', app_t('POS session opened successfully.'));
        } elseif ($action === 'create_order') {
            app_enforce_current_role_can('pos_orders', 'create');
            app_enforce_current_role_can('pos_orders', 'post', app_t('You do not have permission to validate POS orders.'));
            $selectedSessionId = app_integer($_POST['session_id'] ?? 0);
            $orderId = app_pos_create_order((int) $companyId, $_POST);
            app_flash('success', app_t('POS order validated and posted successfully.'));
            app_redirect('pos.php?' . http_build_query(['company_id' => $companyId, 'session_id' => $selectedSessionId, 'last_order_id' => $orderId]));
        } elseif ($action === 'cash_movement') {
            app_enforce_current_role_can('pos_cash_movements', 'create');
            app_enforce_current_role_can('pos_cash_movements', 'post', app_t('You do not have permission to post POS cash movements.'));
            $selectedSessionId = app_integer($_POST['session_id'] ?? 0);
            app_pos_create_cash_movement((int) $companyId, $selectedSessionId, $_POST);
            app_flash('success', app_t('POS cash movement posted successfully.'));
        } elseif ($action === 'close_session') {
            app_enforce_current_role_can('pos_sessions', 'post', app_t('You do not have permission to close POS sessions.'));
            $selectedSessionId = app_integer($_POST['session_id'] ?? 0);
            app_pos_close_session(
                (int) $companyId,
                $selectedSessionId,
                app_number($_POST['closing_cash_counted'] ?? 0),
                (string) ($_POST['notes'] ?? '')
            );
            app_flash('success', app_t('POS session closed successfully.'));
            $selectedSessionId = 0;
        }
    } catch (Throwable $e) {
        app_flash('error', $e->getMessage());
    }

    $query = ['company_id' => $companyId];
    if ($selectedSessionId > 0) {
        $query['session_id'] = $selectedSessionId;
    }
    app_redirect('pos.php?' . http_build_query($query));
}

$registers = app_pos_registers((int) $companyId);
$openSessions = app_pos_open_sessions((int) $companyId);
if ($selectedSessionId <= 0 && !empty($openSessions[0]['id'])) {
    $selectedSessionId = (int) $openSessions[0]['id'];
}
$activeSession = $selectedSessionId > 0 ? app_pos_session_by_id((int) $companyId, $selectedSessionId) : null;
if ($activeSession && strtolower(app_normalize_whitespace((string) ($activeSession['status'] ?? ''))) !== 'open') {
    $activeSession = null;
    $selectedSessionId = 0;
}
$sessionSummary = $activeSession ? app_pos_session_summary((int) $companyId, (int) $activeSession['id']) : null;
$products = app_pos_catalog_products((int) $companyId);
$customers = app_module_lookup_options('customer_contact_code', $companyId);
$paymentAccountLabels = app_module_lookup_options('payment_account_name', $companyId);
$paymentAccountCategories = app_payment_account_category_map((int) $companyId);
$paymentAccounts = [];
foreach ($paymentAccountLabels as $name => $label) {
    $paymentAccounts[] = [
        'name' => (string) $name,
        'label' => (string) $label,
        'category' => (string) ($paymentAccountCategories[(string) $name] ?? ''),
    ];
}
$chartAccounts = app_module_lookup_options('chart_account_code', $companyId);
$recentOrders = app_pos_recent_orders((int) $companyId, 14);
$defaultPaymentAccount = $activeSession ? app_normalize_whitespace((string) ($activeSession['cash_account_name'] ?? '')) : '';
$defaultBankAccount = $activeSession ? app_normalize_whitespace((string) ($activeSession['default_bank_account_name'] ?? '')) : '';
$defaultCustomer = $activeSession ? app_normalize_whitespace((string) ($activeSession['default_customer_code'] ?? '')) : '';
$priceIncludesTax = $activeSession && (int) ($activeSession['price_includes_tax'] ?? 0) === 1;
?>
<!doctype html>
<html <?= app_html_attrs() ?>>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= app_escape(app_t((string) app_config('app_name'))) ?> - <?= app_escape(app_t('POS Terminal')) ?></title>
  <link rel="icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="shortcut icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="stylesheet" href="assets/styles.css">
</head>
<body>
<div class="app-shell has-sidebar">
  <?= app_sidebar_nav_html('pos', null, $companyId) ?>

  <header class="header">
    <div class="header-side right">
      <div class="header-title"><?= app_escape(app_t('POS Terminal')) ?></div>
      <div class="header-subtitle"><?= app_escape(app_t('Sessions, orders, refunds, split payments, and GL posting')) ?></div>
    </div>
    <div class="header-center">
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Logo" class="school-logo">
    </div>
    <div class="header-side left">
      <div class="header-title"><?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
      <div class="header-subtitle"><a href="index.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>"><?= app_escape(app_t('Dashboard')) ?></a> &bull; <a href="logout.php"><?= app_escape(app_t('Logout')) ?></a></div>
    </div>
  </header>

  <div class="date-bar">
    <div class="date-item"><?= app_escape(app_t('Date :')) ?> <span><?= app_escape(date('Y-m-d')) ?></span></div>
    <div class="date-item"><?= app_escape(app_t('Module :')) ?> <span><?= app_escape(app_t('Point of Sale')) ?></span></div>
    <div class="date-author"><?= app_escape(app_t('Prepared by :')) ?> <?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
  </div>

  <?= app_back_button_html('Back') ?>

  <main class="container pos-terminal">
    <div class="flash-stack">
      <?php if ($success = app_flash('success')): ?>
        <div class="alert success"><?= app_escape($success) ?></div>
      <?php endif; ?>
      <?php if ($error = app_flash('error')): ?>
        <div class="alert error"><?= app_escape($error) ?></div>
      <?php endif; ?>
    </div>

    <section class="pos-session-strip">
      <div class="pos-session-strip__main">
        <strong><?= $activeSession ? app_escape((string) ($activeSession['session_number'] ?? 'Open Session')) : 'No Open Session' ?></strong>
        <span><?= $activeSession ? app_escape((string) ($activeSession['register_name'] ?? 'Register')) : 'Open a register session to start selling.' ?></span>
      </div>
      <?php if ($activeSession && $sessionSummary): ?>
        <div class="pos-kpis">
          <span>Orders <b><?= (int) ($sessionSummary['orders_count'] ?? 0) ?></b></span>
          <span>Net <b><?= app_money_format($sessionSummary['net_total'] ?? 0) ?></b></span>
          <span>Expected Cash <b><?= app_money_format($sessionSummary['expected_cash'] ?? 0) ?></b></span>
        </div>
      <?php endif; ?>
      <div class="pos-session-strip__actions">
        <a class="btn btn-secondary" href="module.php?module=pos_registers&company_id=<?= (int) $companyId ?>">Registers</a>
        <a class="btn btn-secondary" href="module.php?module=pos_orders&company_id=<?= (int) $companyId ?>">Orders</a>
      </div>
    </section>

    <?php if (!$activeSession): ?>
      <section class="card pos-open-card">
        <h2>Open POS Session</h2>
        <?php if (!$registers): ?>
          <p>Create at least one active POS register linked to a cash drawer and cost center.</p>
          <a class="btn btn-primary" href="module.php?module=pos_registers&company_id=<?= (int) $companyId ?>">Create POS Register</a>
        <?php else: ?>
          <form method="post" class="grid two">
            <?= app_csrf_field() ?>
            <input type="hidden" name="action" value="open_session">
            <div class="field">
              <label>Register</label>
              <select name="register_id" required>
                <?php foreach ($registers as $register): ?>
                  <option value="<?= (int) $register['id'] ?>"><?= app_escape((string) ($register['register_code'] ?? '')) ?> - <?= app_escape((string) ($register['register_name'] ?? '')) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field">
              <label>Opening Cash Counted</label>
              <input type="number" step="0.01" name="opening_cash_counted" value="0">
            </div>
            <div class="form-actions">
              <button class="btn btn-primary" type="submit">Open Session</button>
            </div>
          </form>
        <?php endif; ?>
      </section>
    <?php else: ?>
      <section class="pos-layout">
        <div class="pos-products-panel">
          <div class="pos-toolbar">
            <input id="posProductSearch" type="search" placeholder="Search products, SKU, barcode">
            <select id="posCategoryFilter">
              <option value="">All Categories</option>
            </select>
          </div>
          <div id="posProductGrid" class="pos-product-grid"></div>
        </div>

        <aside class="pos-cart-panel">
          <form id="posOrderForm" method="post">
            <?= app_csrf_field() ?>
            <input type="hidden" name="action" value="create_order">
            <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
            <input type="hidden" name="session_id" value="<?= (int) $activeSession['id'] ?>">
            <input id="posCartJson" type="hidden" name="cart_json">
            <input id="posPaymentsJson" type="hidden" name="payments_json">

            <div class="pos-cart-head">
              <div>
                <strong>Current Order</strong>
                <span><?= app_escape((string) ($activeSession['register_name'] ?? '')) ?></span>
              </div>
              <select id="posOrderType" name="order_type">
                <option value="sale">Sale</option>
                <option value="refund">Refund</option>
              </select>
            </div>

            <div class="grid two compact">
              <div class="field">
                <label>Customer</label>
                <select name="customer_code" id="posCustomer">
                  <option value="">Walk-in Customer</option>
                  <?php foreach ($customers as $code => $label): ?>
                    <option value="<?= app_escape((string) $code) ?>" <?= $defaultCustomer === (string) $code ? 'selected' : '' ?>><?= app_escape((string) $label) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="field">
                <label>Original Order</label>
                <input type="text" name="original_order_number" placeholder="For refunds">
              </div>
            </div>

            <div id="posCartLines" class="pos-cart-lines"></div>

            <div class="field">
              <label>Notes</label>
              <textarea name="notes" rows="2" placeholder="Receipt / customer note"></textarea>
            </div>

            <div class="pos-totals">
              <div><span>Subtotal</span><b id="posSubtotal">0.00</b></div>
              <div><span>Discount</span><b id="posDiscount">0.00</b></div>
              <div><span>Tax</span><b id="posTax">0.00</b></div>
              <div class="grand"><span>Total</span><b id="posGrandTotal">0.00</b></div>
            </div>

            <div class="pos-payments">
              <div class="pos-section-title">
                <strong>Payments</strong>
                <button class="btn btn-secondary btn-sm" type="button" id="posAddPayment">Add Split</button>
              </div>
              <div id="posPaymentLines"></div>
            </div>

            <label class="check-row">
              <input type="checkbox" name="invoice_requested" value="1">
              <span>Invoice requested</span>
            </label>

            <div class="form-actions pos-actions">
              <button class="btn btn-ghost" type="button" id="posClearOrder">Clear</button>
              <button class="btn btn-primary" type="submit">Validate Payment</button>
            </div>
          </form>
        </aside>
      </section>

      <section class="pos-ops-grid">
        <div class="card">
          <h2>Cash In / Out</h2>
          <form method="post" class="grid two compact">
            <?= app_csrf_field() ?>
            <input type="hidden" name="action" value="cash_movement">
            <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
            <input type="hidden" name="session_id" value="<?= (int) $activeSession['id'] ?>">
            <div class="field">
              <label>Type</label>
              <select name="movement_type">
                <option value="cash_in">Cash In</option>
                <option value="cash_out">Cash Out</option>
              </select>
            </div>
            <div class="field">
              <label>Amount</label>
              <input type="number" step="0.01" name="amount" required>
            </div>
            <div class="field">
              <label>Offset Account</label>
              <select name="offset_account_code" required>
                <option value="">Select account</option>
                <?php foreach ($chartAccounts as $code => $label): ?>
                  <option value="<?= app_escape((string) $code) ?>"><?= app_escape((string) $label) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field">
              <label>Reason</label>
              <input type="text" name="reason">
            </div>
            <div class="form-actions">
              <button class="btn btn-secondary" type="submit">Post Cash Movement</button>
            </div>
          </form>
        </div>

        <div class="card">
          <h2>Close Session</h2>
          <form method="post" class="grid two compact">
            <?= app_csrf_field() ?>
            <input type="hidden" name="action" value="close_session">
            <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
            <input type="hidden" name="session_id" value="<?= (int) $activeSession['id'] ?>">
            <div class="field">
              <label>Expected Cash</label>
              <input type="number" step="0.01" value="<?= app_escape((string) ($sessionSummary['expected_cash'] ?? 0)) ?>" readonly>
            </div>
            <div class="field">
              <label>Closing Cash Counted</label>
              <input type="number" step="0.01" name="closing_cash_counted" value="<?= app_escape((string) ($sessionSummary['expected_cash'] ?? 0)) ?>" required>
            </div>
            <div class="field field-wide">
              <label>Closing Notes</label>
              <textarea name="notes" rows="2"></textarea>
            </div>
            <div class="form-actions">
              <button class="btn btn-primary" type="submit">Close Session</button>
            </div>
          </form>
        </div>
      </section>
    <?php endif; ?>

    <section class="card">
      <h2>Recent POS Orders</h2>
      <div class="table-wrap">
        <table class="data-table">
          <thead>
            <tr>
              <th>Order</th>
              <th>Date</th>
              <th>Register</th>
              <th>Type</th>
              <th>Customer</th>
              <th>Total</th>
              <th>Status</th>
              <th>Journal</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($recentOrders as $order): ?>
            <?php $journal = app_journal_entry_for_source((int) $companyId, 'pos_orders', (int) ($order['id'] ?? 0)); ?>
            <tr>
              <td><a href="module.php?module=pos_orders&company_id=<?= (int) $companyId ?>&edit=<?= (int) $order['id'] ?>"><?= app_escape((string) ($order['order_number'] ?? '')) ?></a></td>
              <td><?= app_escape((string) ($order['order_date'] ?? '')) ?></td>
              <td><?= app_escape((string) ($order['register_name'] ?? '')) ?></td>
              <td><?= app_escape((string) ($order['order_type'] ?? '')) ?></td>
              <td><?= app_escape((string) ($order['customer_code'] ?? '')) ?></td>
              <td><?= app_money_format($order['grand_total'] ?? 0) ?></td>
              <td><?= app_escape((string) ($order['status'] ?? '')) ?></td>
              <td>
                <?php if ($journal): ?>
                  <a href="module.php?module=journal_entries&company_id=<?= (int) $companyId ?>&edit=<?= (int) $journal['id'] ?>"><?= app_escape((string) ($journal['entry_number'] ?? 'JE')) ?></a>
                <?php else: ?>
                  -
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$recentOrders): ?>
            <tr><td colspan="8" class="empty-cell">No POS orders yet.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </section>
  </main>
</div>

<?php if ($activeSession): ?>
<script>
const POS_PRODUCTS = <?= json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const POS_PAYMENT_ACCOUNTS = <?= json_encode($paymentAccounts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const POS_DEFAULT_CASH = <?= json_encode($defaultPaymentAccount, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const POS_DEFAULT_BANK = <?= json_encode($defaultBankAccount, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const POS_PRICE_INCLUDES_TAX = <?= $priceIncludesTax ? 'true' : 'false' ?>;
const POS_STORAGE_KEY = 'orion-pos-cart-<?= (int) $companyId ?>-<?= (int) $activeSession['id'] ?>';
const POS_CLEAR_AFTER_SUCCESS = <?= (int) ($_GET['last_order_id'] ?? 0) > 0 ? 'true' : 'false' ?>;
const POS_TEXT = <?= json_encode([
    'stock' => app_t('Stock'),
    'no_products' => app_t('No products found.'),
    'all_categories' => app_t('All Categories'),
    'remove' => app_t('Remove'),
    'qty' => app_t('Qty'),
    'price' => app_t('Price'),
    'discount_percent' => app_t('Disc %'),
    'tax_percent' => app_t('Tax %'),
    'customer_note' => app_t('Customer note'),
    'cart_empty' => app_t('Cart is empty.'),
    'cash' => app_t('Cash'),
    'card' => app_t('Card'),
    'bank' => app_t('Bank'),
    'transfer' => app_t('Transfer'),
    'reference' => app_t('Ref'),
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?: '{}' ?>;

let cart = [];
let payments = [];

function posText(key) {
  return POS_TEXT[key] || key;
}

function money(value) {
  const locale = document.documentElement.lang === 'ar' ? 'ar-EG' : 'en-US';
  return (Math.round((Number(value) || 0) * 100) / 100).toLocaleString(locale, {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

function activeSign() {
  return document.getElementById('posOrderType').value === 'refund' ? -1 : 1;
}

function accountOptions(category, selected) {
  return POS_PAYMENT_ACCOUNTS
    .filter((account) => !category || account.category === category || (category === 'bank' && account.category === 'bank'))
    .map((account) => `<option value="${escapeHtml(account.name)}" ${account.name === selected ? 'selected' : ''}>${escapeHtml(account.label)}</option>`)
    .join('');
}

function escapeHtml(value) {
  return String(value ?? '').replace(/[&<>"']/g, (ch) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[ch]));
}

function loadCart() {
  if (POS_CLEAR_AFTER_SUCCESS) {
    localStorage.removeItem(POS_STORAGE_KEY);
  }
  try {
    cart = JSON.parse(localStorage.getItem(POS_STORAGE_KEY) || '[]');
  } catch (error) {
    cart = [];
  }
  if (!Array.isArray(cart)) cart = [];
  payments = [{payment_method: 'cash', payment_account_name: POS_DEFAULT_CASH, amount: 0, reference: ''}];
}

function saveCart() {
  localStorage.setItem(POS_STORAGE_KEY, JSON.stringify(cart));
}

function productBySku(sku) {
  return POS_PRODUCTS.find((product) => String(product.sku) === String(sku));
}

function addProduct(sku) {
  const product = productBySku(sku);
  if (!product) return;
  const existing = cart.find((line) => line.sku === sku);
  if (existing) {
    existing.quantity = Number(existing.quantity || 0) + 1;
  } else {
    cart.push({
      sku: product.sku,
      product_name: product.product_name,
      quantity: 1,
      unit_price: Number(product.sale_price || 0),
      discount_percent: 0,
      tax_rate_percent: Number(product.tax_rate_percent || 0),
      customer_note: ''
    });
  }
  saveCart();
  renderCart();
}

function removeLine(index) {
  cart.splice(index, 1);
  saveCart();
  renderCart();
}

function updateLine(index, field, value) {
  if (!cart[index]) return;
  cart[index][field] = ['quantity', 'unit_price', 'discount_percent', 'tax_rate_percent'].includes(field) ? Number(value || 0) : value;
  if (field === 'quantity' && cart[index][field] < 0) cart[index][field] = 0;
  if (field === 'discount_percent') cart[index][field] = Math.min(100, Math.max(0, cart[index][field]));
  saveCart();
  renderCart();
}

function lineTotals(line) {
  const qty = Math.abs(Number(line.quantity || 0));
  const price = Math.max(0, Number(line.unit_price || 0));
  const rate = Math.max(0, Number(line.tax_rate_percent || 0));
  const discountPercent = Math.min(100, Math.max(0, Number(line.discount_percent || 0)));
  const gross = qty * price;
  const discount = gross * discountPercent / 100;
  const afterDiscount = gross - discount;
  let base = afterDiscount;
  let tax = base * rate / 100;
  if (POS_PRICE_INCLUDES_TAX && rate > 0) {
    base = afterDiscount / (1 + (rate / 100));
    tax = afterDiscount - base;
  }
  return {base, discount, tax, total: base + tax};
}

function orderTotals() {
  const sign = activeSign();
  return cart.reduce((acc, line) => {
    const totals = lineTotals(line);
    acc.subtotal += totals.base * sign;
    acc.discount += totals.discount * sign;
    acc.tax += totals.tax * sign;
    acc.total += totals.total * sign;
    return acc;
  }, {subtotal: 0, discount: 0, tax: 0, total: 0});
}

function renderProducts() {
  const grid = document.getElementById('posProductGrid');
  const search = document.getElementById('posProductSearch').value.trim().toLowerCase();
  const category = document.getElementById('posCategoryFilter').value;
  const filtered = POS_PRODUCTS.filter((product) => {
    const text = `${product.sku} ${product.product_name} ${product.category}`.toLowerCase();
    return (!search || text.includes(search)) && (!category || product.category === category);
  });
  grid.innerHTML = filtered.map((product) => `
    <button class="pos-product" type="button" data-sku="${escapeHtml(product.sku)}">
      <span>${escapeHtml(product.product_name)}</span>
      <small>${escapeHtml(product.sku)} · ${escapeHtml(posText('stock'))} ${money(product.qty_on_hand || 0)}</small>
      <b>${money(product.sale_price || 0)}</b>
    </button>
  `).join('') || `<div class="empty-cell">${escapeHtml(posText('no_products'))}</div>`;
  grid.querySelectorAll('.pos-product').forEach((button) => {
    button.addEventListener('click', () => addProduct(button.dataset.sku));
  });
}

function renderCategories() {
  const select = document.getElementById('posCategoryFilter');
  const categories = [...new Set(POS_PRODUCTS.map((product) => product.category).filter(Boolean))].sort();
  select.innerHTML = `<option value="">${escapeHtml(posText('all_categories'))}</option>` + categories.map((category) => `<option value="${escapeHtml(category)}">${escapeHtml(category)}</option>`).join('');
}

function renderCart() {
  const container = document.getElementById('posCartLines');
  container.innerHTML = cart.map((line, index) => {
    const totals = lineTotals(line);
    return `
      <div class="pos-cart-line">
        <div class="pos-cart-line__title">
          <strong>${escapeHtml(line.product_name || line.sku)}</strong>
          <button type="button" class="btn btn-ghost btn-xs" data-remove="${index}">${escapeHtml(posText('remove'))}</button>
        </div>
        <div class="pos-cart-line__grid">
          <label>${escapeHtml(posText('qty'))}<input type="number" min="0" step="0.001" value="${Number(line.quantity || 0)}" data-index="${index}" data-field="quantity"></label>
          <label>${escapeHtml(posText('price'))}<input type="number" min="0" step="0.01" value="${Number(line.unit_price || 0)}" data-index="${index}" data-field="unit_price"></label>
          <label>${escapeHtml(posText('discount_percent'))}<input type="number" min="0" max="100" step="0.01" value="${Number(line.discount_percent || 0)}" data-index="${index}" data-field="discount_percent"></label>
          <label>${escapeHtml(posText('tax_percent'))}<input type="number" min="0" step="0.01" value="${Number(line.tax_rate_percent || 0)}" data-index="${index}" data-field="tax_rate_percent"></label>
        </div>
        <input class="pos-note-input" type="text" placeholder="${escapeHtml(posText('customer_note'))}" value="${escapeHtml(line.customer_note || '')}" data-index="${index}" data-field="customer_note">
        <div class="pos-line-total">${money(totals.total * activeSign())}</div>
      </div>
    `;
  }).join('') || `<div class="empty-cell">${escapeHtml(posText('cart_empty'))}</div>`;

  container.querySelectorAll('input[data-index]').forEach((input) => {
    input.addEventListener('change', () => updateLine(Number(input.dataset.index), input.dataset.field, input.value));
  });
  container.querySelectorAll('[data-remove]').forEach((button) => {
    button.addEventListener('click', () => removeLine(Number(button.dataset.remove)));
  });

  const totals = orderTotals();
  document.getElementById('posSubtotal').textContent = money(totals.subtotal);
  document.getElementById('posDiscount').textContent = money(totals.discount);
  document.getElementById('posTax').textContent = money(totals.tax);
  document.getElementById('posGrandTotal').textContent = money(totals.total);
  renderPayments(totals.total);
}

function renderPayments(total) {
  const container = document.getElementById('posPaymentLines');
  if (!payments.length) {
    payments.push({payment_method: 'cash', payment_account_name: POS_DEFAULT_CASH, amount: Math.abs(total), reference: ''});
  }
  if (payments.length === 1) {
    payments[0].amount = Math.abs(total);
  }
  container.innerHTML = payments.map((payment, index) => {
    const method = payment.payment_method || 'cash';
    const category = method === 'cash' ? 'cash' : 'bank';
    const fallback = method === 'cash' ? POS_DEFAULT_CASH : POS_DEFAULT_BANK;
    const selected = payment.payment_account_name || fallback;
    return `
      <div class="pos-payment-line">
        <select data-payment-index="${index}" data-payment-field="payment_method">
          <option value="cash" ${method === 'cash' ? 'selected' : ''}>${escapeHtml(posText('cash'))}</option>
          <option value="card" ${method === 'card' ? 'selected' : ''}>${escapeHtml(posText('card'))}</option>
          <option value="bank" ${method === 'bank' ? 'selected' : ''}>${escapeHtml(posText('bank'))}</option>
          <option value="transfer" ${method === 'transfer' ? 'selected' : ''}>${escapeHtml(posText('transfer'))}</option>
        </select>
        <select data-payment-index="${index}" data-payment-field="payment_account_name">${accountOptions(category, selected)}</select>
        <input type="number" min="0" step="0.01" value="${Number(payment.amount || 0)}" data-payment-index="${index}" data-payment-field="amount">
        <input type="text" placeholder="${escapeHtml(posText('reference'))}" value="${escapeHtml(payment.reference || '')}" data-payment-index="${index}" data-payment-field="reference">
        <button class="btn btn-ghost btn-xs" type="button" data-remove-payment="${index}">${escapeHtml(posText('remove'))}</button>
      </div>
    `;
  }).join('');

  container.querySelectorAll('[data-payment-index]').forEach((input) => {
    input.addEventListener('change', () => {
      const index = Number(input.dataset.paymentIndex);
      const field = input.dataset.paymentField;
      payments[index][field] = field === 'amount' ? Number(input.value || 0) : input.value;
      if (field === 'payment_method') {
        payments[index].payment_account_name = input.value === 'cash' ? POS_DEFAULT_CASH : POS_DEFAULT_BANK;
        renderPayments(total);
      }
    });
  });
  container.querySelectorAll('[data-remove-payment]').forEach((button) => {
    button.addEventListener('click', () => {
      payments.splice(Number(button.dataset.removePayment), 1);
      renderPayments(total);
    });
  });
}

document.getElementById('posProductSearch').addEventListener('input', renderProducts);
document.getElementById('posCategoryFilter').addEventListener('change', renderProducts);
document.getElementById('posOrderType').addEventListener('change', renderCart);
document.getElementById('posAddPayment').addEventListener('click', () => {
  payments.push({payment_method: 'card', payment_account_name: POS_DEFAULT_BANK, amount: 0, reference: ''});
  renderPayments(orderTotals().total);
});
document.getElementById('posClearOrder').addEventListener('click', () => {
  cart = [];
  payments = [{payment_method: 'cash', payment_account_name: POS_DEFAULT_CASH, amount: 0, reference: ''}];
  saveCart();
  renderCart();
});
document.getElementById('posOrderForm').addEventListener('submit', () => {
  document.getElementById('posCartJson').value = JSON.stringify(cart);
  document.getElementById('posPaymentsJson').value = JSON.stringify(payments);
});

loadCart();
renderCategories();
renderProducts();
renderCart();
</script>
<?php endif; ?>
</body>
</html>
