<div class="mb-3">
  <label class="form-label"><?= __('common.name', 'Name') ?> *</label>
  <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($customer['name']??'') ?>" required>
</div>
<div class="row g-3">
  <div class="col-md-4">
    <label class="form-label"><?= __('common.email', 'Email') ?></label>
    <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($customer['email']??'') ?>">
  </div>
  <div class="col-md-4">
    <label class="form-label"><?= __('customers.phone', 'Phone') ?></label>
    <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($customer['phone']??'') ?>">
  </div>
  <div class="col-md-4">
    <label class="form-label"><?= __("common.status", "Status") ?></label>
    <select name="status" class="form-select">
      <?php $st=$customer['status']??'active'; ?>
      <option value="active" <?= $st==='active'?'selected':'' ?>><?= __("common.active", "Active") ?></option>
      <option value="inactive" <?= $st==='inactive'?'selected':'' ?>><?= __("common.inactive", "Inactive") ?></option>
    </select>
  </div>
</div>
<div class="mb-3 mt-3">
  <label class="form-label"><?= __('customers.address', 'Address') ?></label>
  <textarea name="address" class="form-control" rows="2"><?= htmlspecialchars($customer['address']??'') ?></textarea>
</div>
<div class="mb-3">
  <label class="form-label"><?= __('common.notes', 'Notes') ?></label>
  <textarea name="notes" class="form-control" rows="2"><?= htmlspecialchars($customer['notes']??'') ?></textarea>
</div>
<hr>
<?php
$selCatsIds = isset($sel_categories)? array_column($sel_categories,'id'):[];
$selBlockedIds = isset($sel_blocked)? array_column($sel_blocked,'id'):[];
$selAddIds = isset($sel_additional)? array_column($sel_additional,'id'):[];
$selUserIds = isset($sel_users)? array_column($sel_users,'id'):[];
$countCats = isset($relation_counts)?$relation_counts['categories']:count($selCatsIds);
$countBlocked = isset($relation_counts)?$relation_counts['blocked']:count($selBlockedIds);
$countAdd = isset($relation_counts)?$relation_counts['additional']:count($selAddIds);
$countUsers = isset($relation_counts)?$relation_counts['users']:count($selUserIds);
?>
<div class="row g-3">
  <div class="col-md-3">
    <label class="form-label"><?= __('customers.category_access', 'Category Access') ?> <span class="badge bg-secondary" id="catCount"><?= $countCats ?></span></label>
    <div class="border rounded p-2 small bg-light" id="catSummary"><?= __('common.none', 'None') ?></div>
    <button type="button" class="btn btn-sm btn-outline-primary mt-2" data-bs-toggle="modal" data-bs-target="#modalCategories"><i class="fas fa-folder-open me-1"></i><?= __('common.manage', 'Manage') ?></button>
  </div>
  <div class="col-md-3">
    <label class="form-label"><?= __('customers.blocked_products', 'Blocked Products') ?> <span class="badge bg-secondary" id="blkCount"><?= $countBlocked ?></span></label>
    <div class="border rounded p-2 small bg-light" id="blkSummary"><?= __('common.none', 'None') ?></div>
    <button type="button" class="btn btn-sm btn-outline-danger mt-2" data-bs-toggle="modal" data-bs-target="#modalBlocked"><i class="fas fa-ban me-1"></i><?= __('common.manage', 'Manage') ?></button>
  </div>
  <div class="col-md-3">
    <label class="form-label"><?= __('customers.additional_products', 'Additional Products') ?> <span class="badge bg-secondary" id="addCount"><?= $countAdd ?></span></label>
    <div class="border rounded p-2 small bg-light" id="addSummary"><?= __('common.none', 'None') ?></div>
    <button type="button" class="btn btn-sm btn-outline-success mt-2" data-bs-toggle="modal" data-bs-target="#modalAdditional"><i class="fas fa-plus-circle me-1"></i><?= __('common.manage', 'Manage') ?></button>
  </div>
  <div class="col-md-3">
    <label class="form-label"><?= __('customers.assigned_users', 'Assigned Users') ?> <span class="badge bg-secondary" id="usrCount"><?= $countUsers ?></span></label>
    <select name="assigned_users[]" class="visually-hidden" multiple id="hiddenUsersSelect">
      <?php foreach($users as $u): if(in_array($u['id'],$selUserIds)): ?><option value="<?= $u['id'] ?>" selected></option><?php endif; endforeach; ?>
    </select>
    <div class="border rounded p-2 small bg-light" id="usrSummary"><?= __('common.none', 'None') ?></div>
    <button type="button" class="btn btn-sm btn-outline-secondary mt-2" data-bs-toggle="modal" data-bs-target="#modalUsers"><i class="fas fa-users me-1"></i><?= __('common.manage', 'Manage') ?></button>
  </div>
</div>

<!-- Hidden containers for selected IDs -->
<div id="hiddenInputs" class="d-none">
  <!-- Populated by JS with <input type='hidden' name='category_access[]'> etc -->
  <?php foreach($selCatsIds as $id): ?><input type="hidden" name="category_access[]" value="<?= $id ?>" data-rel="cat"><?php endforeach; ?>
  <?php foreach($selBlockedIds as $id): ?><input type="hidden" name="blocked_products[]" value="<?= $id ?>" data-rel="blk"><?php endforeach; ?>
  <?php foreach($selAddIds as $id): ?><input type="hidden" name="additional_products[]" value="<?= $id ?>" data-rel="add"><?php endforeach; ?>
</div>

<!-- Modals -->
<?php
function renderRelationModal($id,$title,$items,$selected,$type){ ?>
<div class="modal fade" id="<?= $id ?>" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title mb-0"><?= htmlspecialchars($title) ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="d-flex mb-2 gap-2">
          <input type="text" class="form-control form-control-sm" placeholder="<?= __('common.search', 'Search...') ?>" data-filter="<?= $id ?>">
          <button type="button" class="btn btn-sm btn-outline-secondary" data-select-all="<?= $id ?>"><?= __('common.all', 'All') ?></button>
          <button type="button" class="btn btn-sm btn-outline-secondary" data-clear-all="<?= $id ?>"><?= __('common.none', 'None') ?></button>
        </div>
        <table class="table table-sm table-striped align-middle mb-0">
          <thead><tr><th style="width:40px"></th><th><?= __("common.name", "Name") ?></th></tr></thead>
          <tbody>
            <?php foreach($items as $it): $checked=in_array($it['id'],$selected); ?>
              <tr data-row="<?= $id ?>" data-name="<?= htmlspecialchars(strtolower($it['name'])) ?>">
                <td><input type="checkbox" class="form-check-input" data-rel-check="<?= $type ?>" value="<?= $it['id'] ?>" <?= $checked?'checked':'' ?>></td>
                <td><?= htmlspecialchars($it['name']) ?></td>
              </tr>
            <?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>
<?php } ?>

<?php renderRelationModal('modalCategories',__('customers.select_categories', 'Select Categories'),$categories,$selCatsIds,'cat'); ?>
<?php renderRelationModal('modalBlocked',__('customers.select_blocked_products', 'Select Blocked Products'),$products,$selBlockedIds,'blk'); ?>
<?php renderRelationModal('modalAdditional',__('customers.select_additional_products', 'Select Additional Products'),$products,$selAddIds,'add'); ?>
<?php renderRelationModal('modalUsers',__('customers.assign_users', 'Assign Users'),$users,$selUserIds,'usr'); ?>

<script>
(function(){
  const hiddenContainer = document.getElementById('hiddenInputs');
  const summaryEls = {cat:document.getElementById('catSummary'), blk:document.getElementById('blkSummary'), add:document.getElementById('addSummary'), usr:document.getElementById('usrSummary')};
  const countEls = {cat:document.getElementById('catCount'), blk:document.getElementById('blkCount'), add:document.getElementById('addCount'), usr:document.getElementById('usrCount')};
  function updateSummary(type){
    const values = Array.from((type==='usr'? document.querySelectorAll('#hiddenUsersSelect option[selected]'): hiddenContainer.querySelectorAll(`input[data-rel="${type}"]`))).map(el=>el.value);
    let names=[];
    if(values.length){
      const sourceRows = document.querySelectorAll(`[data-rel-check="${type}"]`);
      const map = {}; sourceRows.forEach(cb=>{ map[cb.value]= cb.closest('tr').querySelectorAll('td')[1].textContent.trim(); });
      names = values.slice(0,5).map(v=>map[v]||v); if(values.length>5) names.push('…');
      summaryEls[type].textContent = names.join(', ');
    } else { summaryEls[type].textContent='<?= __('common.none', 'None') ?>'; }
    if(countEls[type]) countEls[type].textContent = values.length; }
  function syncHidden(type,id,checked){
    if(type==='usr'){
      const sel=document.getElementById('hiddenUsersSelect');
      let opt = Array.from(sel.options).find(o=>o.value===id);
      if(checked && !opt){ opt=document.createElement('option'); opt.value=id; opt.selected=true; sel.appendChild(opt);} else if(!checked && opt){ sel.removeChild(opt);} return; }
    if(checked){ const input=document.createElement('input'); input.type='hidden'; input.name=(type==='cat'?'category_access[]': (type==='blk'?'blocked_products[]':'additional_products[]')); input.value=id; input.dataset.rel=type; hiddenContainer.appendChild(input); }
    else { const existing=hiddenContainer.querySelector(`input[data-rel="${type}"][value="${id}"]`); if(existing) existing.remove(); }
  }
  document.querySelectorAll('[data-rel-check]').forEach(cb=>{ cb.addEventListener('change',()=>{ syncHidden(cb.getAttribute('data-rel-check'), cb.value, cb.checked); updateSummary(cb.getAttribute('data-rel-check')); }); });
  // Search filter
  document.querySelectorAll('[data-filter]').forEach(inp=>{ inp.addEventListener('input',()=>{ const val=inp.value.toLowerCase(); document.querySelectorAll(`tr[data-row="${inp.getAttribute('data-filter')}"]`).forEach(tr=>{ tr.style.display = tr.getAttribute('data-name').includes(val)?'':'none'; }); }); });
  // Select/Clear all (visible rows only)
  document.querySelectorAll('[data-select-all]').forEach(btn=>{ btn.addEventListener('click',()=>{ const id=btn.getAttribute('data-select-all'); document.querySelectorAll(`tr[data-row="${id}"]`).forEach(tr=>{ if(tr.style.display==='none') return; const cb=tr.querySelector('[data-rel-check]'); if(!cb.checked){ cb.checked=true; cb.dispatchEvent(new Event('change')); } }); }); });
  document.querySelectorAll('[data-clear-all]').forEach(btn=>{ btn.addEventListener('click',()=>{ const id=btn.getAttribute('data-clear-all'); document.querySelectorAll(`tr[data-row="${id}"]`).forEach(tr=>{ if(tr.style.display==='none') return; const cb=tr.querySelector('[data-rel-check]'); if(cb.checked){ cb.checked=false; cb.dispatchEvent(new Event('change')); } }); }); });
  // Initial summaries
  ['cat','blk','add','usr'].forEach(updateSummary);
})();
</script>
