<div class="row g-3 mb-3">
  <div class="col-md-4">
    <label class="form-label"><?= __('common.customer', 'Customer') ?> *</label>
    <select name="customer_id" class="form-select" required>
      <option value=""><?= __('common.select', '-- select --') ?></option>
      <?php foreach($customers as $c): ?>
        <option value="<?= $c['id'] ?>" <?= (isset($order) && isset($order['customer_id']) && $order['customer_id']==$c['id'])?'selected':'' ?>><?= htmlspecialchars($c['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <?php
    $orderDateVal = $order['order_date'] ?? date('Y-m-d H:i:s');
    $orderDatePart = substr($orderDateVal,0,10);
    $orderTimePart = substr($orderDateVal,11,5);
  ?>
  <div class="col-md-3">
    <label class="form-label"><?= __('orders.order_date', 'Order Date') ?></label>
    <input type="date" name="order_date" id="orderDate" class="form-control" value="<?= htmlspecialchars($orderDatePart) ?>" min="<?= date('Y-m-d') ?>">
  </div>
  <div class="col-md-2">
    <label class="form-label"><?= __('orders.order_time', 'Order Time') ?></label>
    <input type="time" name="order_time" id="orderTime" class="form-control" value="<?= htmlspecialchars($orderTimePart) ?>">
  </div>
  <div class="col-md-3">
    <label class="form-label"><?= __('orders.delivery_date', 'Delivery Date') ?></label>
    <input type="date" name="delivery_date" id="deliveryDate" class="form-control" value="<?= htmlspecialchars($order['delivery_date']??'') ?>" min="<?= date('Y-m-d') ?>" placeholder="<?= __('common.optional', '(optional)') ?>">
  </div>
  <div class="col-md-2">
    <label class="form-label"><?= __('orders.order_type', 'Order Type') ?></label>
    <?php $ot=$order['order_type']??'daily'; ?>
    <select name="order_type" class="form-select">
      <option value="daily" <?= $ot==='daily'?'selected':'' ?>><?= __('orders.type_daily', 'Daily Order') ?></option>
      <option value="additional" <?= $ot==='additional'?'selected':'' ?>><?= __('orders.type_additional', 'Additional Order') ?></option>
    </select>
  </div>
  <div class="col-md-2">
    <label class="form-label"><?= __('common.status', 'Status') ?></label>
    <?php $st=$order['status']??'pending'; ?>
    <select name="status" class="form-select">
      <option value="pending" <?= $st==='pending'?'selected':'' ?>><?= __('orders.status_pending', 'Pending') ?></option>
      <option value="completed" <?= $st==='completed'?'selected':'' ?>><?= __('orders.status_completed', 'Completed') ?></option>
      <option value="cancelled" <?= $st==='cancelled'?'selected':'' ?>><?= __('orders.status_cancelled', 'Cancelled') ?></option>
    </select>
  </div>
  <div class="col-md-2">
    <label class="form-label"><?= __('orders.assigned_user', 'Assigned User') ?></label>
  <select name="assigned_user_id" class="form-select" id="assignedUserSelect">
      <option value=""><?= __('common.none', '-- none --') ?></option>
      <?php foreach($users as $u): ?>
        <option value="<?= $u['id'] ?>" <?= isset($order['assigned_user_id']) && $order['assigned_user_id']==$u['id']?'selected':'' ?>><?= htmlspecialchars($u['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="col-md-1 d-flex align-items-end">
    <div class="form-check mt-auto">
  <input class="form-check-input" type="checkbox" name="confirm_flag" value="1" id="confirmFlag" <?= !empty($order['confirmed'])?'checked':'' ?>>
  <label class="form-check-label small" for="confirmFlag" title="<?= __('orders.verified_tooltip', 'Production manager verified; order will be processed') ?>"><?= __('orders.verified', 'Verified') ?></label>
    </div>
  </div>
  <div class="col-md-2 d-flex align-items-end">
    <button type="button" class="btn btn-sm btn-outline-primary w-100" data-bs-toggle="modal" data-bs-target="#modalItems"><i class="fas fa-boxes"></i> <?= __('orders.items', 'Items') ?></button>
  </div>
</div>
<div class="mb-3">
  <label class="form-label"><?= __('common.notes', 'Notes') ?></label>
  <textarea name="notes" class="form-control" rows="2"><?= htmlspecialchars($order['notes']??'') ?></textarea>
</div>
<div class="row g-3 mb-3">
  <div class="col-md-6">
    <label class="form-label"><?= __('orders.signature', 'Signature') ?></label>
    <textarea name="signature" class="form-control" rows="2" placeholder="<?= __('orders.signature_placeholder', 'Signature / Acknowledgement text') ?>"><?= htmlspecialchars($order['signature']??'') ?></textarea>
  </div>
  <div class="col-md-6">
    <label class="form-label"><?= __('orders.items_summary', 'Items Summary') ?></label>
    <div class="table-responsive" style="max-height:200px;overflow:auto;">
      <table class="table table-sm table-bordered mb-0" id="itemsSummaryTable">
        <thead><tr><th><?= __('common.code', 'Code') ?></th><th><?= __('common.name', 'Name') ?></th><th style="width:70px"><?= __('common.quantity', 'Qty') ?></th><th style="width:70px"><?= __('common.units', 'Units') ?></th></tr></thead>
        <tbody><tr class="no-items"><td colspan="4" class="text-muted"><?= __('orders.no_items', 'No items') ?></td></tr></tbody>
      </table>
    </div>
  </div>
</div>
<!-- Hidden item inputs container -->
<div id="orderItemsHidden" class="d-none">
<?php if(!empty($items)):
  foreach($items as $it): ?>
  <div class="order-item-hidden" data-id="<?= $it['product_id'] ?>">
    <input type="hidden" name="item_product_id[]" value="<?= $it['product_id'] ?>">
  <input type="hidden" name="item_qty[]" value="<?= htmlspecialchars($it['quantity'] ?? '') ?>">
  <input type="hidden" name="item_name_snapshot[]" value="<?= htmlspecialchars(($it['product_name_snapshot'] ?? '') ?: ($it['name'] ?? '')) ?>">
  <input type="hidden" name="item_code_snapshot[]" value="<?= htmlspecialchars(($it['product_code_snapshot'] ?? '') ?: ($it['code'] ?? '')) ?>">
  <input type="hidden" name="item_units_snapshot[]" value="<?= htmlspecialchars(($it['price_unit'] ?? '') ?: ($it['production_unit'] ?? '')) ?>">
  </div>
<?php endforeach; endif; ?>
</div>
<!-- Items modal -->
<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">
        <div class="row g-2 mb-2">
          <div class="col-md-4"><input type="text" class="form-control form-control-sm" placeholder="<?= __('common.search_products', 'Search products...') ?>" id="prodSearch"></div>
          <div class="col-md-2"><button type="button" class="btn btn-sm btn-outline-secondary w-100" id="btnSelectAllVisible"><?= __('orders.select_all_visible', 'Select Visible') ?></button></div>
          <div class="col-md-2"><button type="button" class="btn btn-sm btn-outline-secondary w-100" 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"><?= __('common.unit', 'Unit') ?></th><th style="width:200px"><?= __('common.quantity', 'Qty') ?></th><th style="width:80px"><?= __('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" 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; } } } ?>
                <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><?= htmlspecialchars($p['code']) ?></td>
                  <td><?= htmlspecialchars($p['name']) ?></td>
                  <td><?= htmlspecialchars($p['unit'] ?? '') ?></td>
                  <td>
                    <div class="d-flex align-items-center gap-1">
                      <div class="btn-group btn-group-sm me-2" role="group">
                        <button type="button" class="btn btn-outline-secondary qty-btn" data-id="<?= $p['id'] ?>" data-change="-10">-10</button>
                        <button type="button" class="btn btn-outline-secondary qty-btn" 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" 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="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><?= htmlspecialchars(($p['price_unit'] ?? '') ?: ($p['production_unit'] ?? '')) ?></td>
                </tr>
              <?php endforeach; ?>
            <?php endforeach; ?>
          </tbody>
        </table>
      </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>
(function(){
  const hidden = document.getElementById('orderItemsHidden');
  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;
    }
  }
  function removeHidden(id){ const row=hidden.querySelector(`.order-item-hidden[data-id="${id}"]`); if(row) row.remove(); }
  function updateSummary(){
    const tbody=document.querySelector('#itemsSummaryTable tbody');
    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}</td><td>${name}</td><td>${qty}</td><td>${units}</td>`; tbody.appendChild(tr);
    });
  }
  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 v=document.getElementById('prodSearch').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();
  }
  document.getElementById('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'));
    });
  });
  document.getElementById('btnSelectAllVisible').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(); });
  document.getElementById('btnClearVisible').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(){
    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>
