<!-- Customer Relation 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();
    }
  }
  
  // Checkbox change handler
  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>



