<!-- Items modal - placed outside card to avoid z-index issues -->
<div class="modal fade" id="modalItems" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title mb-0"><?= __('orders.select_products', 'Select Products') ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body pt-0">
        <div class="row g-2 mb-2 sticky-top bg-white py-2 d-flex flex-row" style="top:0;z-index:10;">
          <div class="col-4 col-md-4"><input type="text" class="form-control form-control-sm" placeholder="<?= __('common.search_products', 'Search products...') ?>" id="prodSearch"></div>
          <div class="col-4 col-md-4"><button type="button" class="btn btn-sm btn-outline-secondary" id="btnSelectAllVisible"><?= __('orders.select_all_visible', 'Select Visible') ?></button></div>
          <div class="col-4 col-md-4"><button type="button" class="btn btn-sm btn-outline-secondary" id="btnClearVisible"><?= __('orders.clear_visible', 'Clear Visible') ?></button></div>
        </div>
        <table class="table table-sm align-middle" id="productsTable">
          <thead class="table-light"><tr><th style="width:30px"></th><th><?= __('common.code', 'Code') ?></th><th><?= __("common.name", "Name") ?></th><th style="width:120px" class="d-none d-lg-table-cell"><?= __('common.unit', 'Unit') ?></th><th style="width:200px" class="d-none d-lg-table-cell"><?= __('common.quantity', 'Qty') ?></th><th style="width:80px" class="d-none d-lg-table-cell"><?= __('common.units', 'Units') ?></th></tr></thead>
          <tbody>
            <?php
              // Group products by category_name
              $grouped = [];
              foreach($products as $p){
                $cat = $p['category_name'] ?? 'Uncategorized';
                if(!isset($grouped[$cat])) $grouped[$cat] = [];
                $grouped[$cat][] = $p;
              }
              ksort($grouped, SORT_NATURAL | SORT_FLAG_CASE);
              foreach($grouped as $catName => $plist):
                $safeCat = htmlspecialchars($catName);
            ?>
              <tr class="table-secondary category-row sticky-top" style="top: 50px; z-index: 11;" data-category-row data-cat-key="<?= htmlspecialchars(strtolower($catName)) ?>">
                <td colspan="6" class="py-1">
                  <button type="button" class="btn btn-sm btn-outline-dark me-2 toggle-cat" data-cat="<?= htmlspecialchars(strtolower($catName)) ?>" data-collapsed="0"><i class="fas fa-folder-open"></i></button>
                  <strong><?= $safeCat ?></strong> <span class="text-muted small ms-1" data-cat-count="<?= htmlspecialchars(strtolower($catName)) ?>"></span>
                </td>
              </tr>
              <?php foreach($plist as $p): ?>
                <?php $existing=null; if(!empty($items)){ foreach($items as $it){ if($it['product_id']==$p['id']){ $existing=$it; break; } } } ?>
                <?php $prodUnit = htmlspecialchars(($p['price_unit'] ?? '') ?: ($p['production_unit'] ?? '')); ?>
                <tr class="product-row" data-cat="<?= htmlspecialchars(strtolower($catName)) ?>" data-name="<?= htmlspecialchars(strtolower(($p['name']??'').' '.($p['code']??''))) ?>">
                  <td><input type="checkbox" class="form-check-input item-check" data-id="<?= $p['id'] ?>" <?= $existing?'checked':'' ?>></td>
                  <td class="d-none d-md-table-cell"><code class="small"><?= htmlspecialchars($p['code']) ?></code></td>
                  <td class="product-name-cell">
                    <strong class="small"><?= htmlspecialchars($p['name']) ?></strong>
                    <!-- Mobile-only info (phones) -->
                    <div class="d-md-none small text-muted mt-1">
                      <code class="me-2"><?= htmlspecialchars($p['code']) ?></code>
                      <span class="badge bg-secondary"><?= $prodUnit ?></span>
                    </div>
                  </td>
                  <td class="d-none d-lg-table-cell"><?= htmlspecialchars($p['unit'] ?? '') ?></td>
                  <td>
                    <div class="d-flex align-items-center gap-1">
                      <div class="btn-group btn-group-sm me-1" role="group">
                        <button type="button" class="btn btn-outline-secondary qty-btn d-none d-lg-inline-block" data-id="<?= $p['id'] ?>" data-change="-10">-10</button>
                        <button type="button" class="btn btn-outline-secondary qty-btn d-none d-md-inline-block" data-id="<?= $p['id'] ?>" data-change="-5">-5</button>
                        <button type="button" class="btn btn-outline-secondary qty-btn" data-id="<?= $p['id'] ?>" data-change="-1">-1</button>
                        <button type="button" class="btn btn-outline-secondary qty-btn" data-id="<?= $p['id'] ?>" data-change="1">+1</button>
                        <button type="button" class="btn btn-outline-secondary qty-btn d-none d-md-inline-block" data-id="<?= $p['id'] ?>" data-change="5">+5</button>
                        <button type="button" class="btn btn-outline-secondary qty-btn d-none d-lg-inline-block" data-id="<?= $p['id'] ?>" data-change="10">+10</button>
                      </div>
                      <input type="number" step="0.1" class="form-control form-control-sm item-qty" data-id="<?= $p['id'] ?>" value="<?= $existing? number_format((float)($existing['quantity']), 1, '.', ''):'0.0' ?>" style="width:60px;">
                    </div>
                  </td>
                  <td class="d-none d-xl-table-cell"><?= $prodUnit ?></td>
                </tr>
              <?php endforeach; ?>
            <?php endforeach; ?>
          </tbody>
        </table>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal"><?= __('common.done', 'Done') ?></button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  const hidden = document.getElementById('orderItemsHidden');
  if(!hidden) {
    console.error('orderItemsHidden element not found');
    return;
  }
  
  function triggerAutoSave() {
    // Trigger auto-save event for order creation page
    document.dispatchEvent(new Event('itemsChanged'));
    if(window.orderAutoSave) {
      window.orderAutoSave.scheduleSave();
    }
  }
  
  function syncHiddenRow(id, qty, name, code, units){
    let row = hidden.querySelector(`.order-item-hidden[data-id="${id}"]`);
    if(!row){
      row = document.createElement('div');
      row.className='order-item-hidden'; row.dataset.id=id;
      row.innerHTML = `<input type="hidden" name="item_product_id[]" value="${id}">
<input type="hidden" name="item_qty[]" value="${qty}">
<input type="hidden" name="item_name_snapshot[]" value="${name}">
<input type="hidden" name="item_code_snapshot[]" value="${code}">
<input type="hidden" name="item_units_snapshot[]" value="${units}">`;
      hidden.appendChild(row);
    } else {
      row.querySelector('input[name="item_qty[]"]').value=qty;
    }
    triggerAutoSave();
  }
  function removeHidden(id){ 
    const row=hidden.querySelector(`.order-item-hidden[data-id="${id}"]`); 
    if(row) {
      row.remove(); 
      triggerAutoSave();
    }
  }
  
  // Expose syncHiddenRow and updateSummary globally for restore functionality
  window.syncHiddenRow = syncHiddenRow;
  
  function updateSummary(){
    const tbody=document.querySelector('#itemsSummaryTable tbody');
    if(!tbody) return;
    tbody.innerHTML='';
    const rows = hidden.querySelectorAll('.order-item-hidden');
    if(!rows.length){ tbody.innerHTML='<tr class="no-items"><td colspan="4" class="text-muted"><?= __('orders.no_items', 'No items') ?></td></tr>'; return; }
    rows.forEach(r=>{
      const code=r.querySelector('input[name="item_code_snapshot[]"]').value;
      const name=r.querySelector('input[name="item_name_snapshot[]"]').value;
      const qty=parseFloat(r.querySelector('input[name="item_qty[]"]').value).toFixed(1);
      const units=r.querySelector('input[name="item_units_snapshot[]"]')?.value || '';
      const tr=document.createElement('tr');
      tr.innerHTML=`<td><code>${code}</code></td><td><span class="fw-bold">${name}</span></td><td>${qty}</td><td>${units}</td>`; tbody.appendChild(tr);
    });
  }
  
  // Expose updateSummary globally
  window.updateSummary = updateSummary;
  function refreshCategoryCounts(){
    document.querySelectorAll('.category-row').forEach(cr=>{
      const key = cr.getAttribute('data-cat-key');
      const btn = cr.querySelector('.toggle-cat');
      const collapsed = btn && btn.getAttribute('data-collapsed')==='1';
      const products = document.querySelectorAll(`tr.product-row[data-cat="${key}"]`);
      let shown=0, selected=0; let total=products.length;
      products.forEach(p=>{ if(p.style.display!=="none") shown++; if(p.querySelector('.item-check').checked) selected++; });
      const badge = cr.querySelector(`[data-cat-count="${key}"]`);
      if(badge){ badge.textContent = total? `(${selected}/${total})`:''; }
      // Only hide category row if no items match filter AND not collapsed (collapsed should remain visible for reopening)
      cr.style.display = (shown===0 && !collapsed)? 'none' : '';
    });
  }
  function applyProductFilter(){
    const searchInput = document.getElementById('prodSearch');
    if(!searchInput) return;
    const v = searchInput.value.toLowerCase();
    document.querySelectorAll('#productsTable tbody tr.product-row').forEach(tr=>{
      const key=tr.getAttribute('data-cat');
      // If its category is collapsed keep hidden regardless of name match
      const catBtn=document.querySelector(`.toggle-cat[data-cat="${key}"]`);
      const collapsed = catBtn && catBtn.getAttribute('data-collapsed')==='1';
      if(collapsed){ tr.style.display='none'; return; }
      tr.style.display = tr.getAttribute('data-name').includes(v)? '' : 'none';
    });
    refreshCategoryCounts();
  }
  
  const prodSearch = document.getElementById('prodSearch');
  if(prodSearch) {
    prodSearch.addEventListener('input',applyProductFilter);
  }
  
  function updateQtyButtons(id, currentQty) {
    const qty = parseFloat(currentQty) || 0;
    document.querySelectorAll(`.qty-btn[data-id="${id}"]`).forEach(btn => {
      const change = parseInt(btn.getAttribute('data-change'));
      const newQty = qty + change;
      btn.disabled = newQty < 0;
    });
  }
  
  document.querySelectorAll('.item-check').forEach(cb=>{ 
    cb.addEventListener('change',()=>{ 
      const id=cb.getAttribute('data-id'); 
      const tr=cb.closest('tr'); 
      const qtyInput=tr.querySelector('.item-qty');
      let qty=parseFloat(qtyInput.value) || 0;
      
      if(cb.checked){ 
        // If checkbox is checked but qty is 0, set qty to 1.0
        if(qty === 0) {
          qty = 1.0;
          qtyInput.value = qty.toFixed(1);
        }
        const name=tr.children[2].textContent.trim(); 
        const code=tr.children[1].textContent.trim(); 
        const units=tr.children[5].textContent.trim();
        syncHiddenRow(id,qty,name.replace(/"/g,'&quot;'),code,units); 
      } else { 
        // If checkbox is unchecked, set qty to 0.0
        qtyInput.value = '0.0';
        removeHidden(id); 
      } 
      updateSummary(); 
      refreshCategoryCounts(); 
      updateQtyButtons(id, qtyInput.value); 
    }); 
  });
  document.querySelectorAll('.item-qty').forEach(inp=>{ 
    inp.addEventListener('input',()=>{ 
      const id=inp.getAttribute('data-id'); 
      const cb=document.querySelector(`.item-check[data-id="${id}"]`); 
      const qty = parseFloat(inp.value) || 0;
      
      // Auto-check/uncheck based on quantity
      if(qty > 0 && !cb.checked) {
        cb.checked = true;
      } else if(qty === 0 && cb.checked) {
        cb.checked = false;
      }
      
      if(cb.checked && qty > 0){ 
        const tr=inp.closest('tr'); 
        const name=tr.children[2].textContent.trim(); 
        const code=tr.children[1].textContent.trim(); 
        const units=tr.children[5].textContent.trim();
        syncHiddenRow(id,qty,name.replace(/"/g,'&quot;'),code,units); 
        updateSummary(); 
      } else if(qty === 0) {
        removeHidden(id);
        updateSummary();
      }
      
      updateQtyButtons(id, inp.value); 
      refreshCategoryCounts();
    }); 
  });
  
  // Add quantity button event listeners
  document.querySelectorAll('.qty-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.getAttribute('data-id');
      const change = parseInt(btn.getAttribute('data-change'));
      const qtyInput = document.querySelector(`.item-qty[data-id="${id}"]`);
      const currentQty = parseFloat(qtyInput.value) || 0;
      const newQty = Math.max(0, currentQty + change);
      qtyInput.value = newQty.toFixed(1);
      qtyInput.dispatchEvent(new Event('input'));
    });
  });
  
  const btnSelectAll = document.getElementById('btnSelectAllVisible');
  if(btnSelectAll) {
    btnSelectAll.addEventListener('click',()=>{ 
      document.querySelectorAll('#productsTable tbody tr.product-row').forEach(tr=>{ 
        if(tr.style.display==='none') return; 
        const cb=tr.querySelector('.item-check'); 
        if(!cb.checked){ cb.checked=true; cb.dispatchEvent(new Event('change')); } 
      }); 
      refreshCategoryCounts(); 
    });
  }
  
  const btnClearAll = document.getElementById('btnClearVisible');
  if(btnClearAll) {
    btnClearAll.addEventListener('click',()=>{ 
      document.querySelectorAll('#productsTable tbody tr.product-row').forEach(tr=>{ 
        if(tr.style.display==='none') return; 
        const cb=tr.querySelector('.item-check'); 
        if(cb.checked){ cb.checked=false; cb.dispatchEvent(new Event('change')); } 
      }); 
      refreshCategoryCounts(); 
    });
  }
  
  document.querySelectorAll('.toggle-cat').forEach(btn=>{ 
    btn.addEventListener('click',()=>{ 
      const key=btn.getAttribute('data-cat'); 
      const collapsed=btn.getAttribute('data-collapsed')==='1'; 
      btn.setAttribute('data-collapsed', collapsed? '0':'1'); 
      btn.innerHTML = collapsed? '<i class="fas fa-folder-open"></i>' : '<i class="fas fa-folder"></i>'; 
      applyProductFilter(); 
    }); 
  });
  
  applyProductFilter();
  updateSummary();
  
  // Initialize quantity button states and checkbox states
  document.querySelectorAll('.item-qty').forEach(inp => {
    const id = inp.getAttribute('data-id');
    const qty = parseFloat(inp.value) || 0;
    const cb = document.querySelector(`.item-check[data-id="${id}"]`);
    
    // Format quantity to one decimal place
    inp.value = qty.toFixed(1);
    
    // Set initial checkbox state based on quantity
    if(qty > 0 && !cb.checked) {
      cb.checked = true;
    } else if(qty === 0 && cb.checked) {
      cb.checked = false;
    }
    
    updateQtyButtons(id, inp.value);
  });
  
  // Dynamic filter of assigned users per customer
  const customerUserMap = <?php echo json_encode($customer_user_map ?? []); ?>;
  const customerSelect = document.querySelector('select[name="customer_id"]');
  const assignedSelect = document.getElementById('assignedUserSelect');
  
  function rebuildAssigned(){
    if(!customerSelect || !assignedSelect) return;
    const cid = customerSelect.value;
    const allowed = customerUserMap[cid] || null;
    const current = assignedSelect.value;
    assignedSelect.innerHTML='<option value=""><?= __('common.none', '-- none --') ?></option>';
    if(allowed){
      allowed.forEach(u=>{
        const opt=document.createElement('option'); opt.value=u.id; opt.textContent=u.name; if(current==u.id) opt.selected=true; assignedSelect.appendChild(opt);
      });
      assignedSelect.disabled=false;
    } else {
      // If no specific assignments, show all
      <?php $allUsersArr = array_map(function($u){ return ['id'=>$u['id'],'name'=>$u['name']]; }, $users); ?>
      const all = <?php echo json_encode($allUsersArr); ?>;
      all.forEach(u=>{ const opt=document.createElement('option'); opt.value=u.id; opt.textContent=u.name; if(current==u.id) opt.selected=true; assignedSelect.appendChild(opt); });
      assignedSelect.disabled=false;
    }
  }
  
  if(customerSelect){ customerSelect.addEventListener('change', rebuildAssigned); rebuildAssigned(); }
  
  // Sync delivery date min with order date
  const od=document.getElementById('orderDate');
  const dd=document.getElementById('deliveryDate');
  function syncDelMin(){ if(!od||!dd) return; dd.min=od.value; if(dd.value && dd.value < od.value){ dd.value=od.value; } }
  if(od){ od.addEventListener('change', syncDelMin); syncDelMin(); }
});
</script>
