<?php
$routeContext = $routeContext ?? [
  'dashboard' => url('/admin/dashboard'),
  'sales_home' => url('/sales/invoices'),
  'pos' => url('/pos'),
  'suspended' => url('/pos/suspended'),
  'invoice_view' => static fn(int $id): string => url('/sales/invoices/view?id=' . $id),
];
?>
<?php
$items = $items ?? [];
$units = $units ?? [];
$warehouses = $warehouses ?? [];
$cashboxes = $cashboxes ?? [];
$cart_lines = $cart_lines ?? [];
$cart_total = (float)($cart_total ?? 0);
$cart_count = (float)($cart_count ?? 0);
$form = $form ?? [];
$customer = $customer ?? null;
$userCashbox = $userCashbox ?? null;
$quickItems = array_slice($items, 0, 36);
?>

<style>
  .pos-shell{display:grid;grid-template-columns:minmax(0,1.55fr) minmax(360px,.9fr);gap:1rem;font-size:.95rem}
  .pos-card{border:1px solid #e9ecef;border-radius:1rem;box-shadow:0 .3rem 1rem rgba(15,23,42,.05);background:#fff}
  .pos-page-head{display:flex;justify-content:space-between;align-items:flex-start;gap:.75rem;flex-wrap:wrap;margin-bottom:.75rem}
  .pos-page-head h4{margin:0;font-size:1.8rem}
  .pos-page-head .text-muted{font-size:.9rem}
  .pos-head-actions{display:flex;gap:.5rem;flex-wrap:wrap}
  .pos-summary-compact{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.6rem;margin-bottom:.9rem}
  .pos-summary-pill{border:1px solid #e9ecef;border-radius:.9rem;background:#fff;padding:.65rem .8rem}
  .pos-summary-pill .label{font-size:.72rem;color:#6c757d;line-height:1.1;margin-bottom:.18rem}
  .pos-summary-pill .value{font-size:1.03rem;font-weight:800;line-height:1.2}
  .pos-card-header{padding:.9rem 1rem;border-bottom:1px solid #eef1f4;display:flex;justify-content:space-between;align-items:center;gap:.6rem}
  .pos-card-body{padding:1rem}
  .pos-search-layout{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(260px,.7fr);gap:.85rem;align-items:start}
  .pos-search-panel{border:1px solid #e9eef5;border-radius:.95rem;padding:.9rem;background:linear-gradient(180deg,#ffffff 0%,#f8fbff 100%)}
  .pos-search-panel--barcode{background:linear-gradient(180deg,#ffffff 0%,#f8fafc 100%)}
  .pos-search-input-wrap,.pos-party-search-wrap{position:relative}
  .pos-search-input{height:52px;padding-inline:1rem;font-size:1rem;border-radius:.9rem}
  .pos-selected-item{display:flex;justify-content:space-between;align-items:center;gap:.6rem;border:1px dashed #cbd5e1;border-radius:.85rem;background:#f8fafc;padding:.65rem .75rem;min-height:56px}
  .pos-selected-item .name{font-weight:800;font-size:.96rem;line-height:1.25}
  .pos-selected-item .meta{font-size:.8rem;color:#64748b}
  .pos-selected-item.empty .name{font-weight:600;color:#64748b}
  .pos-search-results{position:absolute;top:calc(100% + .4rem);right:0;left:0;z-index:80;display:none;max-height:340px;overflow:auto;border:1px solid #dbe4ef;border-radius:.95rem;background:#fff;box-shadow:0 1rem 2rem rgba(15,23,42,.16);padding:.35rem}
  .pos-search-result{display:flex;justify-content:space-between;gap:.75rem;align-items:flex-start;width:100%;padding:.7rem .8rem;border:none;background:#fff;text-align:right;border-radius:.75rem}
  .pos-search-result:hover,.pos-search-result.active{background:#eff6ff}
  .pos-search-result .title{font-weight:800;line-height:1.25}
  .pos-search-result .meta{font-size:.78rem;color:#64748b;margin-top:.15rem}
  .pos-search-result .price{font-weight:800;color:#0d6efd;white-space:nowrap}
  .pos-toolbar-actions{display:flex;gap:.55rem;flex-wrap:wrap;align-items:center}
  .pos-qty-chooser{display:flex;align-items:center;gap:.4rem}
  .pos-qty-chooser .btn{min-width:42px;border-radius:.8rem}
  .pos-qty-chooser input{max-width:90px;text-align:center;height:46px;border-radius:.8rem}
  .pos-products{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:.6rem;max-height:280px;overflow:auto;align-content:start;padding-left:.1rem}
  .pos-products-toolbar{display:flex;justify-content:space-between;gap:.75rem;align-items:center;margin-bottom:.7rem;flex-wrap:wrap}
  .pos-products-filter{max-width:260px}
  .pos-product-btn{width:100%;text-align:right;border:1px solid #e5e7eb;border-radius:.9rem;background:#fff;padding:.7rem .75rem;transition:.15s ease;min-height:88px;font-size:.9rem}
  .pos-product-btn:hover{transform:translateY(-1px);border-color:#cfd8e3;box-shadow:0 .35rem .9rem rgba(0,0,0,.06)}
  .pos-product-btn .name{font-weight:700;display:block;margin-bottom:.25rem;line-height:1.25;font-size:.92rem}
  .pos-product-btn .meta{font-size:.72rem;color:#6c757d}
  .pos-product-btn .price{font-weight:800;color:#0d6efd;margin-top:.25rem;font-size:.88rem}
  .pos-cart-table td,.pos-cart-table th{vertical-align:middle;font-size:.91rem;padding:.6rem .48rem}
  .pos-cart-item{display:flex;flex-direction:column;gap:.2rem}
  .pos-cart-actions{display:flex;justify-content:center;align-items:center;gap:.35rem;flex-wrap:wrap}
  .pos-sticky{position:sticky;top:1rem}
  .pos-total-box{border:1px dashed #d6dbe1;border-radius:.95rem;padding:.9rem;background:#f8fafc}
  .pos-total-box .amount{font-size:1.75rem;font-weight:900;line-height:1}
  .pos-inline-note{font-size:.78rem;color:#6c757d}
  .pos-customer-results{z-index:70;max-height:260px;overflow:auto;font-size:.9rem;border-radius:.9rem;padding:.3rem}
  .pos-muted{color:#6c757d}
  .pos-compact-input{font-size:.95rem;padding:.55rem .75rem}
  .pos-cart-empty{padding:2.3rem .5rem !important}
  .pos-icon-btn{min-width:34px;padding:.3rem .45rem}
  .pos-row-total{font-weight:700}
  .pos-suspend-list{max-height:220px;overflow:auto}
  .pos-suspend-item{display:flex;justify-content:space-between;gap:.5rem;align-items:flex-start;padding:.55rem .65rem;border:1px solid #edf0f3;border-radius:.7rem;background:#fff}
  .pos-mini{font-size:.78rem;color:#6c757d}
  .pos-discount-grid{display:grid;grid-template-columns:130px 1fr;gap:.5rem}
  .pos-unit-select{appearance:none;-webkit-appearance:none;-moz-appearance:none;background-image:none !important;padding-left:.75rem;padding-right:.75rem}
  .pos-checkout-grid .form-label,.pos-checkout-grid-secondary .form-label{font-size:.84rem;line-height:1.2;min-height:2.1em;display:flex;align-items:flex-end;margin-bottom:.3rem}
  .pos-checkout-grid .form-control,.pos-checkout-grid .form-select,.pos-checkout-grid-secondary .form-control,.pos-checkout-grid-secondary .form-select{font-size:.93rem}
  .pos-qty-stack{display:flex;align-items:center;gap:.25rem;flex-wrap:wrap;justify-content:center}
  .pos-qty-btn,.pos-touch-btn{min-height:42px;border-radius:.7rem;font-weight:700}
  .pos-qty-btn{min-width:44px;padding:.35rem .55rem}
  .pos-toast-wrap{position:fixed;top:1rem;left:1rem;z-index:1085;display:flex;flex-direction:column;gap:.5rem}
  .pos-toast{background:#111827;color:#fff;padding:.7rem .9rem;border-radius:.8rem;box-shadow:0 .7rem 1.5rem rgba(0,0,0,.18);font-size:.88rem;min-width:220px;opacity:.98}
  .pos-toast.error{background:#991b1b}
  .pos-toast.success{background:#166534}
  .pos-main-btn{min-height:48px;font-weight:800}
  .pos-cart-table tbody tr:hover{background:#fafcff}
  .pos-cart-headline{display:flex;justify-content:space-between;gap:.6rem;align-items:center;flex-wrap:wrap;margin-bottom:.8rem}
  .pos-cart-headline .headline{font-size:1.05rem;font-weight:800}
  .pos-checkout-callout{border:1px solid #dbeafe;background:#eff6ff;border-radius:.85rem;padding:.75rem .8rem;margin-bottom:.85rem}
  .pos-checkout-callout .label{font-size:.8rem;color:#475569}
  .pos-checkout-callout .value{font-size:1.65rem;font-weight:900;line-height:1;color:#0f172a}
  .pos-payment-modal{position:fixed;inset:0;z-index:1090;display:none;align-items:center;justify-content:center;padding:1rem;background:rgba(15,23,42,.45)}
  .pos-payment-modal.show{display:flex}
  .pos-payment-dialog{width:min(760px,100%);background:#fff;border-radius:1.1rem;box-shadow:0 1.2rem 3rem rgba(15,23,42,.24);overflow:hidden}
  .pos-payment-head{display:flex;justify-content:space-between;align-items:center;gap:.75rem;padding:1rem 1.15rem;border-bottom:1px solid #edf2f7;background:#f8fafc}
  .pos-payment-head h5{margin:0;font-size:1.3rem;font-weight:900}
  .pos-payment-body{padding:1rem 1.15rem}
  .pos-payment-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.75rem;margin-bottom:.9rem}
  .pos-payment-stat{border:1px solid #e5e7eb;border-radius:.9rem;background:#fff;padding:.85rem}
  .pos-payment-stat .label{font-size:.8rem;color:#64748b;margin-bottom:.2rem}
  .pos-payment-stat .value{font-size:1.45rem;font-weight:900;line-height:1.15}
  .pos-payment-received{margin-bottom:1rem}
  .pos-payment-received input{height:64px;font-size:1.55rem;font-weight:900;text-align:center;border-radius:1rem}
  .pos-payment-quick{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.55rem;margin-bottom:1rem}
  .pos-payment-quick .btn{min-height:48px;font-weight:800;border-radius:.85rem}
  .pos-payment-note{font-size:.82rem;color:#64748b}
  .pos-payment-actions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.65rem;margin-top:1rem}
  .pos-payment-actions .btn{min-height:52px;font-weight:800;border-radius:.9rem}
  @media (max-width: 767px){
    .pos-payment-grid{grid-template-columns:1fr}
    .pos-payment-quick{grid-template-columns:repeat(2,minmax(0,1fr))}
    .pos-payment-actions{grid-template-columns:1fr}
  }
  @media (pointer: coarse){
    .pos-products{max-height:300px}
    .pos-product-btn{min-height:94px}
    .pos-qty-btn,.pos-touch-btn,.btn{min-height:46px}
    .form-control,.form-select{min-height:44px}
  }
  @media (max-width: 1199px){
    .pos-shell{grid-template-columns:1fr}
    .pos-sticky{position:static}
  }
  @media (max-width: 900px){
    .pos-search-layout{grid-template-columns:1fr}
  }
  @media (max-width: 767px){
    .pos-summary-compact{grid-template-columns:repeat(2,minmax(0,1fr))}
    .pos-page-head h4{font-size:1.35rem}
    .pos-products-toolbar,.pos-cart-headline{align-items:flex-start}
  }
</style>

<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-sm btn-outline-primary" href="<?= e($routeContext['suspended']) ?>">السلال المعلقة</a>
    <a class="btn btn-sm btn-outline-secondary" href="<?= e($routeContext['sales_home']) ?>">فواتير المبيعات</a>
    <a class="btn btn-sm btn-outline-dark" href="<?= e($routeContext['dashboard']) ?>">رجوع</a>
  </div>
  <div class="small text-muted">POS</div>
</div>
<div class="pos-toast-wrap" id="posToastWrap"></div>

<div class="pos-shell">
  <div>
    <div class="pos-card mb-3">
      <div class="pos-card-header">
        <div>
          <div class="fw-bold">إضافة صنف سريع</div>
          <div class="small text-muted">ابحث، اختر، واضغط إضافة. أو استخدم بطاقات الأصناف السريعة.</div>
        </div>
        <div class="d-flex gap-3 small text-muted flex-wrap">
          <span>الأصناف: <strong id="summaryCartSize"><?= (int)count($cart_lines) ?></strong></span>
          <span>الكمية: <strong id="summaryCartCount"><?= e((string)$cart_count) ?></strong></span>
          <span>الإجمالي: <strong id="summaryCartTotal"><?= format_money($cart_total) ?></strong></span>
          <span>السداد: <strong id="summaryPaymentMode">نقدي</strong></span>
        </div>
      </div>
      <div class="pos-card-body">
        <div class="pos-search-layout mb-3">
          <form method="post" class="vstack gap-3 pos-search-panel" id="quickAddForm" data-async-cart="1">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="item_id" id="itemIdInput" value="">
            <select id="itemSelect" class="d-none" tabindex="-1" aria-hidden="true">
              <option value="">اختر صنف...</option>
              <?php foreach ($items as $it): ?>
                <option value="<?= (int)$it['id'] ?>" data-name="<?= e((string)$it['name']) ?>" data-barcode="<?= e((string)($it['barcode'] ?? '')) ?>" data-price="<?= e((string)round((float)$it['price'],2)) ?>">
                  <?= e((string)$it['name']) ?><?= !empty($it['barcode']) ? ' - '.e((string)$it['barcode']) : '' ?> (<?= format_money((float)$it['price']) ?>)
                </option>
              <?php endforeach; ?>
            </select>
            <div class="pos-search-input-wrap">
              <label class="form-label">بحث سريع عن الصنف</label>
              <input id="itemSearch" class="form-control pos-search-input" type="text" placeholder="ابحث بالاسم أو الكود أو الباركود ثم Enter" autocomplete="off">
              <div class="pos-search-results" id="itemSearchResults"></div>
            </div>
            <div class="pos-selected-item empty" id="selectedItemCard">
              <div>
                <div class="name" id="selectedItemName">لم يتم اختيار صنف بعد</div>
                <div class="meta" id="selectedItemMeta">اختر من النتائج أو استخدم الباركود للإضافة المباشرة.</div>
              </div>
              <button type="button" class="btn btn-sm btn-outline-secondary" id="clearSelectedItemBtn">مسح</button>
            </div>
            <div class="d-flex gap-3 flex-wrap align-items-end">
              <div>
                <label class="form-label">الكمية</label>
                <div class="pos-qty-chooser">
                  <button type="button" class="btn btn-outline-secondary" id="quickQtyDec">-</button>
                  <input id="quickQty" class="form-control pos-compact-input" type="number" step="1" min="1" name="qty" value="1" required>
                  <button type="button" class="btn btn-outline-secondary" id="quickQtyInc">+</button>
                </div>
              </div>
              <div>
                <label class="form-label">الوحدة</label>
                <select class="form-select pos-compact-input pos-unit-select" name="unit_id">
                  <option value="0">افتراضي</option>
                  <?php foreach ($units as $u): ?>
                    <option value="<?= (int)$u['id'] ?>"><?= e((string)$u['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="pos-toolbar-actions ms-auto">
                <button class="btn btn-primary px-4">إضافة للسلة</button>
                <button type="button" class="btn btn-outline-secondary" id="focusBarcodeBtn">مسح باركود</button>
              </div>
            </div>
          </form>

          <form method="post" class="vstack gap-3 pos-search-panel pos-search-panel--barcode" id="barcodeForm" data-async-cart="1">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="barcode">
            <div>
              <label class="form-label">إضافة بالباركود</label>
              <input id="barcodeInput" class="form-control pos-search-input" name="barcode" placeholder="امسح أو اكتب الباركود ثم Enter" autocomplete="off">
              <div class="form-text">عند تطابق الباركود سيتم إضافة الصنف مباشرة بدون فتح قائمة نتائج.</div>
            </div>
            <div class="d-flex gap-3 flex-wrap align-items-end">
              <div>
                <label class="form-label">الكمية</label>
                <div class="pos-qty-chooser">
                  <button type="button" class="btn btn-outline-secondary" id="barcodeQtyDec">-</button>
                  <input id="barcodeQty" class="form-control pos-compact-input" type="number" step="1" min="1" name="qty" value="1" required>
                  <button type="button" class="btn btn-outline-secondary" id="barcodeQtyInc">+</button>
                </div>
              </div>
              <div class="pos-toolbar-actions ms-auto">
                <button class="btn btn-outline-primary px-4">إضافة بالباركود</button>
              </div>
            </div>
            <div class="pos-inline-note">اختصارات مفيدة: <strong>F2</strong> للبحث عن الصنف، <strong>F4</strong> للترحيل، <strong>F6</strong> للعميل، <strong>F8</strong> للباركود.</div>
          </form>
        </div>
      </div>
    </div>


    <div class="pos-card">
      <div class="pos-card-header">
        <div>
          <div class="fw-bold">السلة الحالية</div>
          <div class="small text-muted">تحكم سريع في الكمية داخل السلة. <span id="cartHeaderStats"><?= count($cart_lines) ?> صنف / <?= e((string)$cart_count) ?> كمية</span></div>
        </div>
        <div class="d-flex gap-2">
          <button type="button" class="btn btn-sm btn-outline-warning" id="suspendCartBtn">تعليق السلة</button>
          <button type="button" class="btn btn-sm btn-outline-danger" id="clearCartBtn">تفريغ السلة</button>
        </div>
      </div>
      <div class="table-responsive">
        <table class="table table-hover align-middle mb-0 pos-cart-table">
          <thead class="table-light">
            <tr>
              <th>الصنف</th>
              <th class="text-center" style="width:220px">الكمية</th>
              <th class="text-end" style="width:110px">السعر</th>
              <th class="text-end" style="width:130px">الإجمالي</th>
              <th class="text-center" style="width:80px">حذف</th>
            </tr>
          </thead>
          <tbody id="cartTableBody">
            <?php if (!$cart_lines): ?>
              <tr><td colspan="5" class="text-center text-muted pos-cart-empty">السلة فارغة. أضف صنفًا من الأعلى أو من بطاقات الأصناف السريعة.</td></tr>
            <?php else: ?>
              <?php foreach ($cart_lines as $ln): ?>
                <tr>
                  <td>
                    <div class="pos-cart-item">
                      <span class="fw-semibold"><?= e($ln['name']) ?></span>
                      <span class="small text-muted"><?= e((string)($ln['barcode'] ?? '')) ?></span>
                    </div>
                  </td>
                  <td>
                    <div class="pos-cart-actions">
                      <div class="pos-qty-stack">
                        <button type="button" class="btn btn-sm btn-outline-secondary pos-qty-btn js-cart-dec" data-item-id="<?= (int)$ln['id'] ?>" data-step="1">-</button>
                        <form method="post" class="d-flex align-items-center gap-2 m-0 flex-wrap justify-content-center js-cart-update-form" data-async-cart="1">
                          <?= csrf_field() ?>
                          <input type="hidden" name="action" value="update">
                          <input type="hidden" name="item_id" value="<?= (int)$ln['id'] ?>">
                          <input class="form-control form-control-sm text-center" style="max-width:88px" type="number" step="1" min="0" name="qty" value="<?= e((string)round((float)$ln['qty'])) ?>">
                        </form>
                        <button type="button" class="btn btn-sm btn-outline-secondary pos-qty-btn js-cart-inc" data-item-id="<?= (int)$ln['id'] ?>" data-step="1">+</button>
                      </div>
                    </div>
                  </td>
                  <td class="text-end">
                    <div><?= format_money($ln['price']) ?></div>
                    </td>
                  <td class="text-end fw-bold">
                    <div><?= format_money($ln['line_total']) ?></div>
                    
                  </td>
                  <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger pos-qty-btn js-cart-remove" data-item-id="<?= (int)$ln['id'] ?>">×</button></td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    </div>


  <div>
    <div class="pos-sticky">
      <div class="pos-card mb-3">
        <div class="pos-card-header">
          <div>
            <div class="fw-bold">أصناف سريعة</div>
            <div class="small text-muted">فوق بيانات البيع مباشرة لسرعة الإضافة دون إنزال السلة.</div>
          </div>
        </div>
        <div class="pos-card-body">
          <div class="pos-products-toolbar">
            <div class="small text-muted">أكثر الأصناف استخدامًا للوصول السريع. يمكن فلترتها من مربع البحث أعلاه.</div>
            <input type="text" class="form-control form-control-sm pos-products-filter" id="quickProductsFilter" placeholder="فلترة الأصناف السريعة">
          </div>
          <div class="pos-products" id="quickProducts">
            <?php foreach ($quickItems as $it): ?>
              <form method="post" class="m-0 quick-product-form" data-async-cart="1" data-name="<?= e(mb_strtolower((string)$it['name'])) ?>" data-barcode="<?= e(mb_strtolower((string)($it['barcode'] ?? ''))) ?>">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="add">
                <input type="hidden" name="item_id" value="<?= (int)$it['id'] ?>">
                <input type="hidden" name="qty" value="1">
                <input type="hidden" name="unit_id" value="0">
                <button class="pos-product-btn" type="submit">
                  <span class="name"><?= e((string)$it['name']) ?></span>
                  <span class="meta"><?= !empty($it['barcode']) ? e((string)$it['barcode']) : 'بدون باركود' ?></span>
                  <div class="price"><?= format_money((float)$it['price']) ?></div>
                </button>
              </form>
            <?php endforeach; ?>
          </div>
        </div>
      </div>

      <div class="pos-card">
        <div class="pos-card-header">
          <div>
            <div class="fw-bold">بيانات البيع والتحصيل</div>
            <div class="small text-muted">بيع نقدي سريع مربوط بخزنة المستخدم الحالية.</div>
          </div>
        </div>
        <div class="pos-card-body">
          <div class="pos-checkout-callout">
            <div class="label">إجمالي البيع الحالي</div>
            <div class="value" id="checkoutGrandCallout"><?= format_money($cart_total) ?></div>
          </div>
          <form method="post" id="posCheckoutForm" class="vstack gap-3">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="checkout">

            <div class="row g-2 pos-checkout-grid">
              <div class="col-md-4">
                <label class="form-label">التاريخ الفعلي</label>
                <input type="text" class="form-control pos-readonly" value="<?= e(date('Y-m-d')) ?>" readonly>
                <input type="hidden" name="invoice_date" value="<?= e(date('Y-m-d')) ?>">
              </div>
              <div class="col-md-4">
                <label class="form-label">المخزن</label>
                <select class="form-select" name="warehouse_id">
                  <?php foreach ($warehouses as $w): ?>
                    <option value="<?= (int)$w['id'] ?>" <?= ((int)($form['warehouse_id'] ?? 0)===(int)$w['id'])?'selected':'' ?>><?= e((string)$w['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">الخزنة</label>
                <input type="text" class="form-control pos-readonly" value="<?= e((string)($userCashbox['name'] ?? 'غير مربوطة بالمستخدم')) ?>" readonly>
                <input type="hidden" name="cashbox_id" id="cashbox_id" value="<?= (int)($form['cashbox_id'] ?? 0) ?>">
              </div>
            </div>

            <?php if (empty($userCashbox)): ?>
              <div class="alert alert-warning py-2">هذا المستخدم غير مربوط بخزنة. اربطه بخزنة من شاشة المستخدمين قبل استخدام نقطة البيع.</div>
            <?php endif; ?>

            <div class="position-relative">
              <label class="form-label">الطرف</label>
              <input type="hidden" name="party_id" id="party_id" value="<?= (int)($form['customer_id'] ?? 0) ?>">
              <input type="hidden" name="party_label" id="party_label" value="<?= e((string)($form['customer_label'] ?? ($customer ? ($customer['name'].' ('.$customer['code'].')') : ''))) ?>">
              <input type="text" class="form-control pos-compact-input" id="party_search" placeholder="ابحث بالاسم/الكود/الموبايل — في النقدي يمكن تركه فارغًا" value="<?= e((string)($form['customer_label'] ?? ($customer ? ($customer['name'].' ('.$customer['code'].')') : ''))) ?>" autocomplete="off">
              <div class="list-group position-absolute w-100 shadow-sm pos-customer-results" id="party_results" style="display:none;"></div>
              <div class="form-text">عند البيع النقدي وترك العميل فارغًا، سيستخدم النظام عميلًا نقديًا افتراضيًا.</div>
            </div>

            <input type="hidden" name="payment_mode" value="cash">
            <input type="hidden" name="paid_amount" id="paid_amount" value="<?= e((string)($cart_total ?: 0)) ?>">
            <input type="hidden" name="received_amount" id="received_amount" value="<?= e((string)($form['received_amount'] ?? $cart_total ?? 0)) ?>">
            <input type="hidden" name="change_amount" id="change_amount" value="0">
            <input type="hidden" name="collection_note" value="<?= e((string)($form['collection_note'] ?? '')) ?>">

            <div class="row g-2">
              <div class="col-md-8">
                <label class="form-label">خصم سريع</label>
                <div class="pos-discount-grid">
                  <select class="form-select" name="discount_type" id="discount_type">
                    <option value="VALUE" <?= strtoupper((string)($form['discount_type'] ?? 'VALUE')) === 'VALUE' ? 'selected' : '' ?>>قيمة</option>
                    <option value="PERCENT" <?= strtoupper((string)($form['discount_type'] ?? 'VALUE')) === 'PERCENT' ? 'selected' : '' ?>>نسبة %</option>
                  </select>
                  <input type="number" step="0.01" min="0" class="form-control" name="discount_value" id="discount_value" value="<?= e((string)($form['discount_value'] ?? 0)) ?>" placeholder="0.00">
                </div>
                <div class="form-text">يخصم من إجمالي السلة مباشرة قبل الترحيل.</div>
              </div>
              <div class="col-md-4">
                <label class="form-label">الطباعة بعد الترحيل</label>
                <div class="form-check form-switch mt-2">
                  <input class="form-check-input" type="checkbox" role="switch" id="print_now" name="print_now" value="1" <?= !empty($form['print_now']) ? 'checked' : '' ?>>
                  <label class="form-check-label" for="print_now">افتح نسخة الطباعة مباشرة</label>
                </div>
              </div>
            </div>

            <div>
              <label class="form-label">ملاحظات الفاتورة</label>
              <input type="text" class="form-control" name="notes" value="<?= e((string)($form['notes'] ?? '')) ?>">
            </div>

            <div class="pos-total-box mb-2">
              <div class="d-flex justify-content-between align-items-center mb-2">
                <div>
                  <div class="small text-muted">صافي الفاتورة</div>
                  <div class="amount" id="grand_total_text"><?= format_money($cart_total) ?></div>
                </div>
                <div class="text-end">
                  <div class="small text-muted">عدد الأصناف</div>
                  <div class="fw-bold fs-5"><?= (int)count($cart_lines) ?></div>
                </div>
              </div>
              <div class="row g-2 mb-2">
                <div class="col-4">
                  <div class="border rounded p-2 bg-white h-100">
                    <div class="small text-muted">الإجمالي قبل الخصم</div>
                    <div class="fw-bold fs-6" id="subtotal_preview"><?= format_money($cart_total) ?></div>
                  </div>
                </div>
                <div class="col-4">
                  <div class="border rounded p-2 bg-white h-100">
                    <div class="small text-muted">قيمة الخصم</div>
                    <div class="fw-bold fs-6 text-success" id="discount_preview">0.00</div>
                  </div>
                </div>
                <div class="col-4">
                  <div class="border rounded p-2 bg-white h-100">
                    <div class="small text-muted">المبلغ المستحق نقدًا</div>
                    <div class="fw-bold fs-6" id="paid_preview">0.00</div>
                  </div>
                </div>
              </div>
              <div class="border rounded p-2 bg-white h-100">
                <div class="small text-muted">الباقي للطرف</div>
                <div class="fw-bold fs-5 text-danger" id="change_preview">0.00</div>
              </div>
            </div>

            <div id="posStatus" class="alert d-none py-2 px-3 small mb-2"></div>
            <div class="d-grid gap-2">
              <button type="button" id="posCheckoutBtn" class="btn btn-success pos-main-btn" <?= $cart_lines ? '' : 'disabled' ?>>ترحيل فاتورة POS</button>
              <button type="button" id="suspendCurrentCartBtn" class="btn btn-outline-warning pos-main-btn" <?= $cart_lines ? '' : 'disabled' ?>>تعليق السلة الحالية</button>
              <div class="small text-muted text-center">سيستخدم النظام طرفًا نقديًا افتراضيًا إذا تُرك الطرف فارغًا. عند الضغط على الترحيل ستظهر شاشة السداد النقدي.</div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="pos-payment-modal" id="posPaymentModal" aria-hidden="true">
  <div class="pos-payment-dialog" role="dialog" aria-modal="true" aria-labelledby="posPaymentTitle">
    <div class="pos-payment-head">
      <div>
        <h5 id="posPaymentTitle">إتمام البيع النقدي</h5>
        <div class="small text-muted">أدخل المبلغ المستلم من العميل، وسيحسب البرنامج الباقي المردود تلقائيًا.</div>
      </div>
      <button type="button" class="btn btn-sm btn-outline-secondary" id="closeCheckoutModalBtn">إغلاق</button>
    </div>
    <div class="pos-payment-body">
      <div class="pos-payment-grid">
        <div class="pos-payment-stat">
          <div class="label">إجمالي الفاتورة</div>
          <div class="value" id="modalGrandTotalText">0.00</div>
        </div>
        <div class="pos-payment-stat">
          <div class="label">المبلغ المستلم</div>
          <div class="value" id="modalReceivedPreview">0.00</div>
        </div>
        <div class="pos-payment-stat">
          <div class="label">الباقي للعميل</div>
          <div class="value text-danger" id="modalChangePreview">0.00</div>
        </div>
      </div>

      <div class="pos-payment-received">
        <label class="form-label fw-bold">المبلغ النقدي المستلم من العميل</label>
        <input type="number" step="0.01" min="0" class="form-control" id="modalReceivedAmount" inputmode="decimal">
      </div>

      <div class="pos-payment-quick" id="posQuickCashButtons"></div>
      <div class="pos-payment-note">اضغط Enter للتأكيد السريع. إذا كان المستلم أقل من المطلوب فلن يسمح النظام بالترحيل النقدي.</div>

      <div class="pos-payment-actions">
        <button type="button" class="btn btn-success" id="confirmCheckoutPrintBtn">ترحيل وطباعة</button>
        <button type="button" class="btn btn-primary" id="confirmCheckoutBtn">ترحيل فقط</button>
        <button type="button" class="btn btn-outline-secondary" id="backToCartBtn">رجوع للسلة</button>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const posUrl = '<?= e($routeContext['pos']) ?>';
  const csrfToken = <?= json_encode(csrf_token()) ?>;
  const paidInput = document.getElementById('paid_amount');
  const receivedInput = document.getElementById('received_amount');
  const paidPreview = document.getElementById('paid_preview');
  const changePreview = document.getElementById('change_preview');
  const subtotalPreview = document.getElementById('subtotal_preview');
  const discountPreview = document.getElementById('discount_preview');
  const discountType = document.getElementById('discount_type');
  const discountValue = document.getElementById('discount_value');
  const barcodeInput = document.getElementById('barcodeInput');
  const partySearch = document.getElementById('party_search');
  const checkoutBtn = document.getElementById('posCheckoutBtn');
  const statusBox = document.getElementById('posStatus');
  const search = document.getElementById('itemSearch');
  const select = document.getElementById('itemSelect');
  const itemIdInput = document.getElementById('itemIdInput');
  const selectedItemCard = document.getElementById('selectedItemCard');
  const selectedItemName = document.getElementById('selectedItemName');
  const selectedItemMeta = document.getElementById('selectedItemMeta');
  const quickQty = document.getElementById('quickQty');
  const barcodeQty = document.getElementById('barcodeQty');
  const checkoutGrandCallout = document.getElementById('checkoutGrandCallout');
  const paymentModal = document.getElementById('posPaymentModal');
  const modalReceivedAmount = document.getElementById('modalReceivedAmount');
  const modalGrandTotalText = document.getElementById('modalGrandTotalText');
  const modalReceivedPreview = document.getElementById('modalReceivedPreview');
  const modalChangePreview = document.getElementById('modalChangePreview');
  const confirmCheckoutBtn = document.getElementById('confirmCheckoutBtn');
  const confirmCheckoutPrintBtn = document.getElementById('confirmCheckoutPrintBtn');
  const openCheckoutModalBtn = document.getElementById('openCheckoutModalBtn');
  const closeCheckoutModalBtn = document.getElementById('closeCheckoutModalBtn');
  const backToCartBtn = document.getElementById('backToCartBtn');
  const quickCashButtonsWrap = document.getElementById('posQuickCashButtons');
  const quickProducts = Array.from(document.querySelectorAll('.quick-product-form'));
  const cartBody = document.getElementById('cartTableBody');
  const clearCartBtn = document.getElementById('clearCartBtn');
  const suspendCartBtn = document.getElementById('suspendCartBtn');
  const suspendCurrentCartBtn = document.getElementById('suspendCurrentCartBtn');
  const summaryCartSize = document.getElementById('summaryCartSize');
  const summaryCartCount = document.getElementById('summaryCartCount');
  const summaryCartTotal = document.getElementById('summaryCartTotal');
  const summaryPaymentMode = document.getElementById('summaryPaymentMode');
  const grandTotalText = document.getElementById('grand_total_text');
  const cartHeaderStats = document.getElementById('cartHeaderStats');

  function formatMoney(v){ return Number(v || 0).toFixed(2); }
  function setMoneyInputValue(input, value){
    if (!input) return;
    const num = Math.max(0, Number(value || 0));
    input.value = Number.isFinite(num) ? num.toFixed(2).replace(/\.00$/, '') : '0';
  }
  function quickCashAmounts(total){
    const numericTotal = Math.max(0, Number(total || 0));
    const base = Math.ceil(numericTotal);
    const set = new Set([numericTotal]);
    [5,10,20,50,100,200,500,1000].forEach(function(step){
      if (base <= step) set.add(step);
      else set.add(Math.ceil(base / step) * step);
    });
    return Array.from(set).filter(function(v){ return v > 0; }).sort(function(a,b){ return a-b; }).slice(0, 8);
  }
  function renderQuickCashButtons(total){
    if (!quickCashButtonsWrap) return;
    const numericTotal = Math.max(0, Number(total || 0));
    quickCashButtonsWrap.innerHTML = quickCashAmounts(numericTotal).map(function(amount){
      const isExact = Math.abs(amount - numericTotal) < 0.009;
      const label = isExact ? 'استلام نفس المبلغ' : formatMoney(amount);
      return '<button type="button" class="btn btn-outline-dark" data-quick-cash="' + amount + '">' + label + '</button>';
    }).join('');
  }
  function syncPaymentModal(){
    const money = discountedTotal();
    const received = Math.max(0, Number(modalReceivedAmount?.value || receivedInput?.value || money.net || 0));
    if (receivedInput) receivedInput.value = formatMoney(received);
    if (paidInput) paidInput.value = formatMoney(money.net);
    const change = received - Number(money.net || 0);
    const positiveChange = Math.max(0, change);
    const changeInput = document.getElementById('change_amount');
    if (changeInput) changeInput.value = formatMoney(positiveChange);
    if (modalGrandTotalText) modalGrandTotalText.textContent = formatMoney(money.net);
    if (modalReceivedPreview) modalReceivedPreview.textContent = formatMoney(received);
    if (modalChangePreview) modalChangePreview.textContent = formatMoney(positiveChange);
    return {totals: money, received, change};
  }
  function openPaymentModal(){
    if (!paymentModal || !checkoutBtn || checkoutBtn.disabled) {
      showStatus('السلة فارغة، لا يمكن الترحيل.', false);
      return;
    }
    const money = discountedTotal();
    const defaultReceived = Math.max(Number(receivedInput?.value || 0), Number(money.net || 0));
    setMoneyInputValue(modalReceivedAmount, defaultReceived);
    renderQuickCashButtons(money.net);
    syncPaymentModal();
    paymentModal.classList.add('show');
    paymentModal.setAttribute('aria-hidden', 'false');
    document.body.classList.add('modal-open');
    setTimeout(function(){ modalReceivedAmount?.focus(); modalReceivedAmount?.select(); }, 25);
  }
  function closePaymentModal(){
    if (!paymentModal) return;
    paymentModal.classList.remove('show');
    paymentModal.setAttribute('aria-hidden', 'true');
    document.body.classList.remove('modal-open');
  }
  function submitCheckout(printNow){
    const form = document.getElementById('posCheckoutForm');
    if (!form) return;
    const state = syncPaymentModal();
    if (state.received + 0.0001 < Number(state.totals.net || 0)) {
      showStatus('المبلغ المستلم أقل من صافي الفاتورة. أكمل السداد قبل الترحيل.', false);
      modalReceivedAmount?.focus();
      modalReceivedAmount?.select();
      return;
    }
    const printSwitch = document.getElementById('print_now');
    if (printSwitch) printSwitch.checked = !!printNow;
    closePaymentModal();
    if (checkoutBtn) {
      checkoutBtn.disabled = true;
      checkoutBtn.textContent = printNow ? 'جارٍ الترحيل والطباعة...' : 'جارٍ الترحيل...';
    }
    form.submit();
  }
  function playTone(ok=true){
    try {
      const Ctx = window.AudioContext || window.webkitAudioContext;
      if (!Ctx) return;
      const ctx = new Ctx();
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.type = 'sine';
      osc.frequency.value = ok ? 880 : 320;
      gain.gain.value = 0.03;
      osc.connect(gain); gain.connect(ctx.destination); osc.start();
      setTimeout(()=>{ osc.stop(); ctx.close(); }, ok ? 90 : 140);
    } catch(e) {}
  }
  function pushToast(message, ok=true){
    const wrap = document.getElementById('posToastWrap');
    if (!wrap || !message) return;
    const el = document.createElement('div');
    el.className = 'pos-toast ' + (ok ? 'success' : 'error');
    el.textContent = message;
    wrap.appendChild(el);
    setTimeout(()=>{ el.remove(); }, 2200);
  }
  function showStatus(message, ok=true){
    if (!statusBox) return;
    if (!message) { statusBox.className = 'alert d-none py-2 px-3 small mb-2'; statusBox.textContent=''; return; }
    statusBox.className = 'alert py-2 px-3 small mb-2 ' + (ok ? 'alert-success' : 'alert-danger');
    statusBox.textContent = message;
    pushToast(message, ok);
    playTone(ok);
  }

  function setIntegerInputValue(input, value){
    if (!input) return;
    let num = parseInt(String(value ?? '').replace(/[^0-9-]/g, ''), 10);
    if (!Number.isFinite(num) || num <= 0) num = 1;
    input.value = String(num);
  }

  function adjustIntegerInput(input, delta){
    if (!input) return;
    let num = parseInt(input.value || '1', 10);
    if (!Number.isFinite(num) || num <= 0) num = 1;
    num += delta;
    if (num <= 0) num = 1;
    input.value = String(num);
  }

  function discountedTotal(){
    const subtotal = Number(window.posGrandTotal || 0);
    const type = (discountType?.value || 'VALUE').toUpperCase();
    let value = Number(discountValue?.value || 0);
    if (value < 0) value = 0;
    let discount = 0;
    if (type === 'PERCENT') {
      if (value > 100) value = 100;
      discount = subtotal * (value / 100);
    } else {
      if (value > subtotal) value = subtotal;
      discount = value;
    }
    const net = Math.max(0, subtotal - discount);
    return {subtotal, discount, net};
  }

  function setMoneyPreview(total, received){
    const totalNum = Number(total || 0);
    let receivedNum = Number(received || 0);
    if (receivedNum < 0) receivedNum = 0;
    if (subtotalPreview) subtotalPreview.textContent = formatMoney(window.posGrandTotal || 0);
    if (discountPreview) discountPreview.textContent = formatMoney((window.posDiscount || 0));
    if (paidPreview) paidPreview.textContent = formatMoney(totalNum);
    if (changePreview) changePreview.textContent = formatMoney(Math.max(0, receivedNum - totalNum));
    if (paidInput) paidInput.value = formatMoney(totalNum);
    if (grandTotalText) grandTotalText.textContent = formatMoney(totalNum);
    if (checkoutGrandCallout) checkoutGrandCallout.textContent = formatMoney(totalNum);
    renderQuickCashButtons(totalNum);
    if (paymentModal?.classList.contains('show')) syncPaymentModal();
  }

  function recalcPayment(){
    const money = discountedTotal();
    window.posDiscount = money.discount;
    if (receivedInput && (receivedInput.value === '' || Number(receivedInput.value || 0) <= 0)) {
      receivedInput.value = formatMoney(money.net);
    }
    if (summaryPaymentMode) summaryPaymentMode.textContent = 'نقدي';
    setMoneyPreview(money.net, receivedInput?.value || money.net);
  }

  recalcPayment();
  discountType?.addEventListener('change', recalcPayment);
  discountValue?.addEventListener('input', recalcPayment);
  receivedInput?.addEventListener('input', function(){
    const raw = this.value;
    if (raw === '') return setMoneyPreview(discountedTotal().net, 0);
    let val = Number(raw || 0);
    if (val < 0) val = 0;
    setMoneyPreview(discountedTotal().net, val);
  });
  receivedInput?.addEventListener('blur', recalcPayment);

  function refreshCartUI(data){
    window.posGrandTotal = Number(data.cart_total || 0);
    if (summaryCartSize) summaryCartSize.textContent = String(data.cart_size || 0);
    if (summaryCartCount) summaryCartCount.textContent = String(data.cart_count || 0);
    if (summaryCartTotal) summaryCartTotal.textContent = formatMoney(data.cart_total || 0);
    if (cartHeaderStats) cartHeaderStats.textContent = `${data.cart_size || 0} صنف / ${data.cart_count || 0} كمية`;
    if (checkoutBtn) checkoutBtn.disabled = !(data.cart_size > 0);
    if (openCheckoutModalBtn) openCheckoutModalBtn.disabled = !(data.cart_size > 0);

    if (!cartBody) return;
    if (!Array.isArray(data.cart_lines) || !data.cart_lines.length) {
      cartBody.innerHTML = '<tr><td colspan="5" class="text-center text-muted pos-cart-empty">السلة فارغة. أضف صنفًا من الأعلى أو من بطاقات الأصناف السريعة.</td></tr>';
      recalcPayment();
      return;
    }
    cartBody.innerHTML = data.cart_lines.map(function(ln){
      const barcode = ln.barcode ? ln.barcode : 'بدون باركود';
      return `
<tr data-item-id="${ln.id}">
  <td><div class="pos-cart-item"><div class="fw-bold">${escapeHtml(ln.name)}</div><div class="small text-muted">${escapeHtml(barcode)}</div></div></td>
  <td><div class="pos-cart-actions"><div class="pos-qty-stack">
    <button type="button" class="btn btn-sm btn-outline-secondary pos-qty-btn js-cart-dec" data-item-id="${ln.id}" data-step="1">-</button>
    <form method="post" class="d-flex align-items-center gap-2 m-0 js-cart-update-form" data-async-cart="1">
      <input type="hidden" name="_csrf" value="${escapeHtml(csrfToken)}">
      <input type="hidden" name="ajax" value="1">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="item_id" value="${ln.id}">
      <input type="number" step="1" min="0" name="qty" value="${Math.round(Number(ln.qty || 0))}" class="form-control form-control-sm text-center" style="max-width:78px">
    </form>
    <button type="button" class="btn btn-sm btn-outline-secondary pos-qty-btn js-cart-inc" data-item-id="${ln.id}" data-step="1">+</button>
  </div></div></td>
  <td class="text-end"><div>${formatMoney(ln.price)}</div></td>
  <td class="text-end pos-row-total"><div>${formatMoney(ln.line_total)}</div></td>
  <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger pos-qty-btn js-cart-remove" data-item-id="${ln.id}">×</button></td>
</tr>`;
    }).join('');
    recalcPayment();
  }

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

  async function postCart(formData){
    formData.set('ajax', '1');
    if (!formData.get('_csrf')) formData.set('_csrf', csrfToken);
    const res = await fetch(posUrl, { method:'POST', body: formData, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const data = await res.json();
    refreshCartUI(data);
    showStatus(data.message || '', !!data.ok);
    if (!data.ok) throw new Error(data.message || 'تعذر تنفيذ العملية.');
    return data;
  }

  document.querySelectorAll('form[data-async-cart="1"]').forEach(form => {
    form.addEventListener('submit', async function(e){
      e.preventDefault();
      try {
        const data = await postCart(new FormData(form));
        if (form.id === 'quickAddForm') {
          if (quickQty) quickQty.value = '1';
          if (itemIdInput) itemIdInput.value = '';
          document.getElementById('clearSelectedItemBtn')?.click();
          search?.focus();
          search?.select();
        }
        if (form.id === 'barcodeForm') {
          barcodeInput.value = '';
          barcodeInput.focus();
        }
      } catch (_) {}
    });
  });

  document.addEventListener('click', async function(e){
    const btn = e.target.closest('.js-cart-inc, .js-cart-dec, .js-cart-remove');
    if (btn) {
      e.preventDefault();
      const itemId = btn.getAttribute('data-item-id');
      const formData = new FormData();
      formData.set('_csrf', csrfToken);
      formData.set('action', btn.classList.contains('js-cart-remove') ? 'remove' : (btn.classList.contains('js-cart-inc') ? 'inc' : 'dec'));
      formData.set('item_id', itemId);
      formData.set('step', btn.getAttribute('data-step') || '1');
      try { await postCart(formData); } catch (_) {}
      return;
    }
    if (e.target.closest('#clearCartBtn')) {
      e.preventDefault();
      if (!confirm('تفريغ السلة؟')) return;
      const formData = new FormData();
      formData.set('_csrf', csrfToken);
      formData.set('action', 'clear');
      try { await postCart(formData); } catch (_) {}
    }
  });

  document.addEventListener('submit', async function(e){
    const form = e.target.closest('.js-cart-update-form');
    if (!form) return;
    e.preventDefault();
    try { await postCart(new FormData(form)); } catch (_) {}
  });


  document.addEventListener('change', async function(e){
    const typeEl = e.target.closest('.js-line-discount-type');
    if (!typeEl) return;
    const itemId = typeEl.getAttribute('data-item-id');
    const valueEl = document.querySelector('.js-line-discount-value[data-item-id="' + itemId + '"]');
    const formData = new FormData();
    formData.set('_csrf', csrfToken);
    formData.set('action', 'line_discount');
    formData.set('item_id', itemId);
    formData.set('discount_type', typeEl.value || 'VALUE');
    formData.set('discount_value', valueEl?.value || '0');
    try { await postCart(formData); } catch (_) {}
  });
  document.addEventListener('blur', async function(e){
    const valueEl = e.target.closest('.js-line-discount-value');
    if (!valueEl) return;
    const itemId = valueEl.getAttribute('data-item-id');
    const typeEl = document.querySelector('.js-line-discount-type[data-item-id="' + itemId + '"]');
    const formData = new FormData();
    formData.set('_csrf', csrfToken);
    formData.set('action', 'line_discount');
    formData.set('item_id', itemId);
    formData.set('discount_type', typeEl?.value || 'VALUE');
    formData.set('discount_value', valueEl.value || '0');
    try { await postCart(formData); } catch (_) {}
  }, true);

  function norm(v){ return (v || '').toLowerCase().replace(/[%\s\-_]+/g, ''); }
  function tokens(v){ return (v || '').toLowerCase().split(/[%\s\-_]+/).map(s => s.trim()).filter(Boolean); }
  function orderedContains(haystack, queryTokens){
    if (!queryTokens.length) return true;
    haystack = norm(haystack);
    let offset = 0;
    for (const t of queryTokens) {
      const token = norm(t);
      const idx = haystack.indexOf(token, offset);
      if (idx === -1) return false;
      offset = idx + token.length;
    }
    return true;
  }
  function localMatch(name, barcode, query){
    if (!query) return true;
    const qNorm = norm(query);
    const tks = tokens(query);
    const n = norm(name);
    const b = norm(barcode);
    return n.includes(qNorm) || b.includes(qNorm) || orderedContains(n, tks) || orderedContains(b, tks);
  }

  if(search && select){
    const opts = Array.from(select.options);
    const resultsBox = document.getElementById('itemSearchResults');
    const quickProductsFilter = document.getElementById('quickProductsFilter');
    let searchTimer = null;
    let remoteRows = [];
    let activeResultIndex = -1;

    function hideItemResults(){
      activeResultIndex = -1;
      remoteRows = [];
      if(resultsBox){ resultsBox.style.display='none'; resultsBox.innerHTML=''; }
    }

    function setSelectedItem(id, label, meta){
      if (itemIdInput) itemIdInput.value = id ? String(id) : '';
      if (select) select.value = id ? String(id) : '';
      if (!selectedItemCard || !selectedItemName || !selectedItemMeta) return;
      if (!id) {
        selectedItemCard.classList.add('empty');
        selectedItemName.textContent = 'لم يتم اختيار صنف بعد';
        selectedItemMeta.textContent = 'اختر من النتائج أو استخدم الباركود للإضافة المباشرة.';
        return;
      }
      selectedItemCard.classList.remove('empty');
      selectedItemName.textContent = label || 'صنف مختار';
      selectedItemMeta.textContent = meta || 'جاهز للإضافة إلى السلة';
    }

    function renderResults(rows){
      if (!resultsBox || !Array.isArray(rows) || !rows.length) { hideItemResults(); return; }
      remoteRows = rows.slice(0, 12);
      activeResultIndex = 0;
      resultsBox.innerHTML = remoteRows.map(function(r, idx){
        const barcode = r.barcode ? ('باركود: ' + r.barcode) : 'بدون باركود';
        const price = formatMoney(r.price || 0);
        return '<button type="button" class="pos-search-result' + (idx===0 ? ' active' : '') + '" data-index="' + idx + '">' +
          '<div><div class="title">' + escapeHtml(r.name || r.text || '') + '</div><div class="meta">' + escapeHtml(barcode) + '</div></div>' +
          '<div class="price">' + price + '</div>' +
        '</button>';
      }).join('');
      resultsBox.style.display = 'block';
    }

    function highlightActiveResult(){
      if (!resultsBox) return;
      resultsBox.querySelectorAll('.pos-search-result').forEach(function(btn, idx){
        btn.classList.toggle('active', idx === activeResultIndex);
      });
    }

    function pickSearchRow(row){
      if (!row) return;
      const meta = (row.barcode ? ('باركود: ' + row.barcode + ' • ') : '') + 'السعر: ' + formatMoney(row.price || 0);
      setSelectedItem(row.id, row.name || row.text || '', meta);
      search.value = row.name || row.text || '';
      hideItemResults();
      setIntegerInputValue(quickQty, quickQty?.value || 1);
      quickQty?.focus();
      quickQty?.select();
    }

    function applyQuickProductFilter(query){
      const q = (query || '').trim();
      quickProducts.forEach(form => {
        const ok = !q || localMatch(form.dataset.name || '', form.dataset.barcode || '', q);
        form.style.display = ok ? '' : 'none';
      });
      if (quickProductsFilter && document.activeElement !== quickProductsFilter) quickProductsFilter.value = q;
    }

    async function runRemoteSearch(force=false){
      const q = (search.value || '').trim();
      applyQuickProductFilter(q);
      if (!q || (!force && q.length < 1) || !resultsBox) { hideItemResults(); return; }
      try {
        const res = await fetch('<?= e(url('/ajax/items/search')) ?>?q=' + encodeURIComponent(q), {headers:{'X-Requested-With':'XMLHttpRequest'}});
        const rows = await res.json();
        if (!Array.isArray(rows) || !rows.length) { hideItemResults(); return; }
        renderResults(rows);
      } catch(_) { hideItemResults(); }
    }

    search.addEventListener('input', function(){
      setSelectedItem('', '', '');
      clearTimeout(searchTimer);
      searchTimer = setTimeout(runRemoteSearch, 140);
    });

    search.addEventListener('keydown', function(e){
      if (e.key === 'ArrowDown') {
        if (resultsBox?.style.display !== 'block') { e.preventDefault(); runRemoteSearch(true); return; }
        e.preventDefault();
        activeResultIndex = Math.min(remoteRows.length - 1, activeResultIndex + 1);
        highlightActiveResult();
        return;
      }
      if (e.key === 'ArrowUp') {
        if (resultsBox?.style.display !== 'block') return;
        e.preventDefault();
        activeResultIndex = Math.max(0, activeResultIndex - 1);
        highlightActiveResult();
        return;
      }
      if (e.key === 'Escape') {
        hideItemResults();
        return;
      }
      if (e.key === 'Enter') {
        e.preventDefault();
        if (resultsBox?.style.display === 'block' && remoteRows[activeResultIndex]) {
          pickSearchRow(remoteRows[activeResultIndex]);
          return;
        }
        if (itemIdInput?.value) {
          document.getElementById('quickAddForm')?.requestSubmit();
          return;
        }
        runRemoteSearch(true);
      }
    });

    resultsBox?.addEventListener('click', function(e){
      const btn = e.target.closest('.pos-search-result');
      if (!btn) return;
      const idx = Number(btn.getAttribute('data-index') || -1);
      if (idx >= 0 && remoteRows[idx]) pickSearchRow(remoteRows[idx]);
    });

    document.addEventListener('click', function(e){
      if (resultsBox && !resultsBox.contains(e.target) && e.target !== search) hideItemResults();
    });

    quickProductsFilter?.addEventListener('input', function(){
      const q = (this.value || '').trim();
      applyQuickProductFilter(q);
    });

    document.getElementById('clearSelectedItemBtn')?.addEventListener('click', function(){
      search.value = '';
      setSelectedItem('', '', '');
      hideItemResults();
      search.focus();
    });

    document.getElementById('quickAddForm')?.addEventListener('submit', function(e){
      if (!itemIdInput?.value) {
        e.preventDefault();
        showStatus('اختر صنفًا من نتائج البحث أولًا.', false);
        search.focus();
        return;
      }
      setIntegerInputValue(quickQty, quickQty?.value || 1);
    });

    setSelectedItem('', '', '');
    applyQuickProductFilter('');
  }

  document.getElementById('quickQtyInc')?.addEventListener('click', function(){ adjustIntegerInput(quickQty, 1); });
  document.getElementById('quickQtyDec')?.addEventListener('click', function(){ adjustIntegerInput(quickQty, -1); });
  document.getElementById('barcodeQtyInc')?.addEventListener('click', function(){ adjustIntegerInput(barcodeQty, 1); });
  document.getElementById('barcodeQtyDec')?.addEventListener('click', function(){ adjustIntegerInput(barcodeQty, -1); });
  [quickQty, barcodeQty].forEach(function(input){
    input?.addEventListener('input', function(){ this.value = this.value.replace(/[^0-9]/g, ''); });
    input?.addEventListener('blur', function(){ setIntegerInputValue(this, this.value); });
  });

  const partyResults = document.getElementById('party_results');
  const partyId = document.getElementById('party_id');
  const partyLabel = document.getElementById('party_label');
  let customerTimer = null;
  function hideCustomerResults(){ if(partyResults){ partyResults.style.display = 'none'; partyResults.innerHTML = ''; } }
  partySearch?.addEventListener('input', function(){
    const q = this.value.trim();
    if (partyId && partyLabel && q !== partyLabel.value) partyId.value = '0';
    clearTimeout(customerTimer);
    if (q.length < 1) { hideCustomerResults(); return; }
    customerTimer = setTimeout(async ()=>{
      try {
        const res = await fetch('<?= e(url('/ajax/parties/search')) ?>?type=customer&q=' + encodeURIComponent(q));
        const rows = await res.json();
        if (!partyResults) return;
        partyResults.innerHTML = '';
        if (!Array.isArray(rows) || !rows.length) { hideCustomerResults(); return; }
        rows.forEach(r => {
          const a = document.createElement('button');
          a.type = 'button';
          a.className = 'list-group-item list-group-item-action';
          a.textContent = `${r.name} (${r.code})${r.phone ? ' - ' + r.phone : ''}`;
          a.addEventListener('click', ()=>{
            partyId.value = r.id;
            partyLabel.value = a.textContent;
            partySearch.value = a.textContent;
            hideCustomerResults();
          });
          partyResults.appendChild(a);
        });
        partyResults.style.display = 'block';
      } catch (e) { hideCustomerResults(); }
    }, 250);
  });
  document.addEventListener('click', function(e){
    if (partyResults && !partyResults.contains(e.target) && e.target !== partySearch) hideCustomerResults();
  });

  checkoutBtn?.addEventListener('click', function(){ openPaymentModal(); });
  openCheckoutModalBtn?.addEventListener('click', function(){ openPaymentModal(); });
  closeCheckoutModalBtn?.addEventListener('click', function(){ closePaymentModal(); });
  backToCartBtn?.addEventListener('click', function(){ closePaymentModal(); });
  paymentModal?.addEventListener('click', function(e){ if (e.target === paymentModal) closePaymentModal(); });
  modalReceivedAmount?.addEventListener('input', function(){ syncPaymentModal(); });
  modalReceivedAmount?.addEventListener('blur', function(){ setMoneyInputValue(this, this.value); syncPaymentModal(); });
  modalReceivedAmount?.addEventListener('keydown', function(e){
    if (e.key === 'Enter') { e.preventDefault(); submitCheckout(!!document.getElementById('print_now')?.checked); }
    if (e.key === 'Escape') { e.preventDefault(); closePaymentModal(); }
  });
  quickCashButtonsWrap?.addEventListener('click', function(e){
    const btn = e.target.closest('[data-quick-cash]');
    if (!btn) return;
    setMoneyInputValue(modalReceivedAmount, btn.getAttribute('data-quick-cash') || '0');
    syncPaymentModal();
    modalReceivedAmount?.focus();
    modalReceivedAmount?.select();
  });
  confirmCheckoutBtn?.addEventListener('click', function(){ submitCheckout(false); });
  confirmCheckoutPrintBtn?.addEventListener('click', function(){ submitCheckout(true); });

  function submitSuspendCart(){
    if (checkoutBtn?.disabled) { showStatus('السلة فارغة، لا يمكن تعليقها.', false); return; }
    const form = document.getElementById('posCheckoutForm');
    const actionInput = form?.querySelector('input[name="action"]');
    if (actionInput) actionInput.value = 'suspend';
    form?.submit();
  }

  suspendCartBtn?.addEventListener('click', submitSuspendCart);
  suspendCurrentCartBtn?.addEventListener('click', submitSuspendCart);
  document.getElementById('focusBarcodeBtn')?.addEventListener('click', function(){ barcodeInput?.focus(); barcodeInput?.select(); });
  document.addEventListener('keydown', function(e){
    if (e.key === 'Escape' && paymentModal?.classList.contains('show')) { e.preventDefault(); closePaymentModal(); return; }
    if (e.key === 'F2') { e.preventDefault(); search?.focus(); search?.select(); }
    if (e.key === 'F4') { e.preventDefault(); if (checkoutBtn && !checkoutBtn.disabled) openPaymentModal(); }
    if (e.key === 'F6') { e.preventDefault(); partySearch?.focus(); partySearch?.select(); }
    if (e.key === 'F8') { e.preventDefault(); barcodeInput?.focus(); barcodeInput?.select(); }
  });

  document.getElementById('barcodeForm')?.addEventListener('submit', function(){
    setIntegerInputValue(barcodeQty, barcodeQty?.value || 1);
  });

  document.getElementById('posCheckoutForm')?.addEventListener('submit', function(e){
    const actionInput = this.querySelector('input[name="action"]');
    const actionValue = actionInput ? String(actionInput.value || 'checkout') : 'checkout';
    if (actionValue === 'checkout' && !paymentModal?.classList.contains('show')) {
      e.preventDefault();
      openPaymentModal();
      return;
    }
    const money = discountedTotal();
    if (paidInput) paidInput.value = formatMoney(money.net);
    if (receivedInput && Number(receivedInput.value || 0) <= 0) receivedInput.value = formatMoney(money.net);
  });
  window.posGrandTotal = <?= json_encode(round($cart_total,2)) ?>;
  window.posDiscount = 0;
  recalcPayment();
  setIntegerInputValue(quickQty, quickQty?.value || 1);
  setIntegerInputValue(barcodeQty, barcodeQty?.value || 1);
  if (search) { setTimeout(()=>search.focus(), 200); } else if (barcodeInput) { setTimeout(()=>barcodeInput.focus(), 200); }
})();
</script>
