document.addEventListener('DOMContentLoaded', () => {
  const filterTable = (inputId, tableId) => {
    const input = document.getElementById(inputId);
    if (!input) return;
    input.addEventListener('keyup', () => {
      const value = input.value.toLowerCase();
      document.querySelectorAll(`#${tableId} tbody tr`).forEach((row) => {
        row.style.display = row.innerText.toLowerCase().includes(value) ? '' : 'none';
      });
    });
  };

  filterTable('clientSearch', 'clientsTable');
  filterTable('fournisseurSearch', 'fournisseursTable');
  filterTable('articleSearch', 'articlesTable');
  filterTable('stockSearch', 'stockTable');

  const stockEntrySelect = document.querySelector('select[name="article_id"]');
  const stockEntryPrice = document.querySelector('input[name="prix_achat_ht"]');
  if (stockEntrySelect && stockEntryPrice) {
    stockEntrySelect.addEventListener('change', () => {
      const option = stockEntrySelect.options[stockEntrySelect.selectedIndex];
      const price = option ? option.getAttribute('data-price') : null;
      if (price !== null && price !== '') {
        stockEntryPrice.value = Number(price).toFixed(2);
      }
    });
  }
});
/* =========================================================
   Phoenix P3.7.4
   DarlinkTable générique : sélection + double-clic + clavier
   ========================================================= */

document.addEventListener('DOMContentLoaded', () => {

    const tables = document.querySelectorAll('.darlink-table-modern');

    tables.forEach(table => {
        const rows = Array.from(table.querySelectorAll('tbody tr'))
            .filter(row => row.querySelectorAll('td').length > 1);

        rows.forEach(row => {

            row.addEventListener('click', function () {
                rows.forEach(r => r.classList.remove('selected'));
                this.classList.add('selected');
            });

            row.addEventListener('dblclick', function () {
                const url = this.dataset.editUrl;
                if (url) {
                    window.location.href = url;
                }
            });

        });
    });

    document.addEventListener('keydown', function(e){

        const activeTable = document.querySelector('.darlink-table-modern');
        if (!activeTable) return;

        const rows = Array.from(activeTable.querySelectorAll('tbody tr'))
            .filter(row => row.style.display !== 'none' && row.querySelectorAll('td').length > 1);

        if (!rows.length) return;

        let selectedIndex = rows.findIndex(row => row.classList.contains('selected'));

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            selectedIndex = selectedIndex < rows.length - 1 ? selectedIndex + 1 : 0;
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : rows.length - 1;
        } else if (e.key === 'Enter') {
            const selectedRow = rows[selectedIndex];
            if (selectedRow && selectedRow.dataset.editUrl) {
                window.location.href = selectedRow.dataset.editUrl;
            }
            return;
        } else {
            return;
        }

        rows.forEach(r => r.classList.remove('selected'));
        rows[selectedIndex].classList.add('selected');
        rows[selectedIndex].scrollIntoView({ block: 'nearest' });

    });

});
/* =========================================================
   Phoenix P2.5.7.1b LTS
   Tri générique des colonnes DarlinkTable
   ========================================================= */

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('table').forEach(table => {
        const headers = table.querySelectorAll('th.darlink-sortable');
        const tbody = table.querySelector('tbody');
        if (!headers.length || !tbody) return;

        headers.forEach(header => {
            header.addEventListener('click', () => {
                const columnIndex = Number.parseInt(header.dataset.column || '', 10);
                if (Number.isNaN(columnIndex)) return;

                const nextDirection = header.dataset.direction === 'asc' ? 'desc' : 'asc';
                headers.forEach(item => {
                    item.dataset.direction = 'none';
                    const indicator = item.querySelector('.sort-indicator');
                    if (indicator) indicator.textContent = '↕';
                });

                header.dataset.direction = nextDirection;
                const activeIndicator = header.querySelector('.sort-indicator');
                if (activeIndicator) activeIndicator.textContent = nextDirection === 'asc' ? '▲' : '▼';

                const rows = Array.from(tbody.querySelectorAll(':scope > tr'))
                    .filter(row => row.querySelectorAll('td').length > columnIndex);

                const sortableValue = row => {
                    const cell = row.children[columnIndex];
                    const raw = (cell?.dataset.sortValue || cell?.innerText || '').trim();
                    const normalized = raw.replace(/\s/g, '').replace(',', '.').replace(/[^0-9.+-]/g, '');
                    const numeric = Number(normalized);
                    return normalized !== '' && Number.isFinite(numeric) ? {type: 'number', value: numeric} : {type: 'text', value: raw.toLocaleLowerCase('fr-FR')};
                };

                rows.sort((rowA, rowB) => {
                    const a = sortableValue(rowA);
                    const b = sortableValue(rowB);
                    let comparison;
                    if (a.type === 'number' && b.type === 'number') comparison = a.value - b.value;
                    else comparison = String(a.value).localeCompare(String(b.value), 'fr', {numeric: true, sensitivity: 'base'});
                    return nextDirection === 'asc' ? comparison : -comparison;
                });

                rows.forEach(row => tbody.appendChild(row));
            });
        });
    });
});
