<?php $title=__('products.products', 'Products'); ob_start(); ?>
<?php
// Helper to safely escape possibly null values
if(!function_exists('h')){ function h($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); } }
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0">
        <i class="fas fa-users"></i> <?= __('products.products', 'Products') ?>    </h1>
    
    <div class="btn-group">
      <a href="/samanta_crm/products/create" class="btn btn-primary "><i class="fas fa-plus"></i> <?= __('common.add', 'Add') ?></a>
      <a href="/samanta_crm/products/import" class="btn btn-outline-secondary "><i class="fas fa-file-import"></i> <?= __('common.import', 'Import') ?></a>
    </div>
</div>




<form class="row g-2 align-items-end data-filters sticky-top" id="filtersForm" method="GET" action="">
  <div class="card mb-3 bg-warning-subtle">
    <div class="card-header py-2 d-flex justify-content-between align-items-center">
      <span class="small fw-bold"><i class="fas fa-filter me-1"></i><?= __('common.filters', 'Filters') ?></span>
      <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#filtersWrap">
        <i class="fas fa-chevron-down"></i>
      </button>
    </div>
    <div class="collapse show" id="filtersWrap">
      <div class="card-body py-3">
        <div class="row g-2 align-items-end">
          <div class="col-md-2 col-6"><label class="form-label small mb-0 d-none"><?= __('common.search', 'Search') ?></label><input type="text" name="q" value="<?= h($filter_q ?? '') ?>" class="form-control form-control-sm" placeholder="<?= __('common.search', 'Search') ?>"></div>
          <div class="col-md-2 col-6"><label class="form-label small mb-0 d-none"><?= __('common.category', 'Category') ?></label><select name="category" class="form-select form-select-sm"><option value=""><?= __('common.all', 'All') ?></option><?php foreach($categories as $c): ?><option value="<?= $c['id'] ?>" <?= $filter_category==$c['id']?'selected':'' ?>><?= h($c['name'] ?? '') ?></option><?php endforeach; ?></select></div>
          <div class="col-md-2 col-6"><label class="form-label small mb-0 d-none"><?= __('common.status', 'Status') ?></label><select name="status" class="form-select form-select-sm"><option value="all"><?= __('common.all', 'All') ?></option><option value="active" <?= $filter_status=='active'?'selected':'' ?>><?= __('common.active', 'Active') ?></option><option value="notactive" <?= $filter_status=='notactive'?'selected':'' ?>><?= __('common.inactive', 'Inactive') ?></option><option value="blocked" <?= $filter_status=='blocked'?'selected':'' ?>><?= __('common.blocked', 'Blocked') ?></option></select></div>
          <div class="col-auto"><button class="btn btn-primary btn-sm"><?= __('common.filter', 'Filter') ?></button></div>
          <input type="hidden" name="sort" value="<?= h($sort) ?>"><input type="hidden" name="dir" value="<?= h($dir) ?>">
        </div>
      </div>
    </div>
  </div>
</form>

<div class="card">
  <div class="card-header py-2 d-flex justify-content-between align-items-center">
    <span class="small fw-bold"><i class="fas fa-table me-1"></i><?= __('products.products', 'Products') ?></span>
    <div class="d-flex gap-2">
      <button type="button" class="btn btn-outline-danger btn-sm" disabled id="bulkDeleteBtn" onclick="bulkDeleteProducts()">
        <i class="fas fa-trash"></i> <?= __('common.remove_selected', 'Remove Selected') ?>
      </button>
      <!-- Debug: Role = <?= $_SESSION['user_role'] ?? 'NOT SET' ?> -->
      <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
      <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteAllProducts()">
        <i class="fas fa-trash-alt me-1"></i> Delete All
      </button>
      <?php endif; ?>
      <div class="dropdown">
        <button class="btn btn-outline-secondary dropdown-toggle btn-sm" type="button" data-bs-toggle="dropdown"><?= __('common.columns', 'Columns') ?></button>
        <div class="dropdown-menu p-2 small" style="min-width:220px" id="colChooser">
          <div class="text-muted small mb-1"><?= __('common.show_hide', 'Show / Hide') ?></div>
          <div id="colChooserList"></div>
          <hr class="my-1">
          <button type="button" class="btn btn-sm btn-outline-primary w-100" id="applyFiltersBtn"><?= __('common.apply_filters', 'Apply Filters') ?></button>
        </div>
      </div>
    </div>
  </div>
  <div class="card-body pt-0">
    <div class="small text-muted px-3 pt-2" id="selCount"></div>
    <div class="table-responsive">
    <table class="table table-sm table-hover align-middle data-table mb-0" id="productsTable">
      <thead>
        <tr>
      <th data-col="select" style="width:28px"><input type="checkbox" id="checkAll"></th>
          <?php
            $cols=[ 'code'=>'Code','name'=>__('common.name', 'Name'),'category_name'=>'Category','price'=>'Price','status'=>__('common.status', 'Status') ];
            $sortMap=[ 'code'=>'code','name'=>'name','category_name'=>'name','price'=>'price','status'=>'status' ];
            $filter_q_str=(string)($filter_q ?? '');
            $filter_category_str=(string)($filter_category ?? '');
            $filter_status_str=(string)($filter_status ?? 'all');
            $queryBase=function($col) use($filter_q_str,$filter_category_str,$filter_status_str,$sort,$dir,$sortMap){
              $newDir = ($sortMap[$col]??'name')===$sort && $dir==='asc'?'desc':'asc';
              return '?q='.urlencode($filter_q_str)
                .'&category='.urlencode($filter_category_str)
                .'&status='.urlencode($filter_status_str)
                .'&sort='.urlencode($sortMap[$col]??'name')
                .'&dir='.$newDir; };
          ?>
          <th data-col="code" class="mobile-show"><a href="<?= $queryBase('code') ?>" class="text-decoration-none"><?= __('common.code', 'Code') ?><?= $sort==='code'?' '.($dir==='asc'?'▲':'▼'):'' ?></a></th>
          <th data-col="name" class="mobile-show"><a href="<?= $queryBase('name') ?>" class="text-decoration-none"><?= __('common.name', 'Name') ?><?= $sort==='name'?' '.($dir==='asc'?'▲':'▼'):'' ?></a></th>
          <th data-col="category" class="mobile-hide"><a href="<?= $queryBase('category') ?>" class="text-decoration-none"><?= __('common.category', 'Category') ?><?= $sort==='category'?' '.($dir==='asc'?'▲':'▼'):'' ?></a></th>
          <th data-col="price" class="mobile-hide"><a href="<?= $queryBase('price') ?>" class="text-decoration-none"><?= __('common.price', 'Price') ?><?= $sort==='price'?' '.($dir==='asc'?'▲':'▼'):'' ?></a></th>
          <th data-col="status" class="mobile-hide"><a href="<?= $queryBase('status') ?>" class="text-decoration-none"><?= __('common.status', 'Status') ?><?= $sort==='status'?' '.($dir==='asc'?'▲':'▼'):'' ?></a></th>
          <th data-col="sort_order" class="mobile-hide"><a href="<?= $queryBase('sort_order') ?>" class="text-decoration-none"><?= __('common.sort', 'Sort') ?><?= $sort==='sort_order'?' '.($dir==='asc'?'▲':'▼'):'' ?></a></th>
          <?php
            $explicitHead=['code','name','category','price','status','sort_order'];
            foreach(($db_columns ?? []) as $dbc){ if(in_array($dbc,$explicitHead)) continue; echo '<th class="d-none" data-col="'.h($dbc).'">'.h(ucwords(str_replace('_',' ',$dbc))).'</th>'; }
          ?>
          <th data-col="actions"></th>
        </tr>
        <tr id="filterRow" class="align-middle"></tr>
      </thead>
      <tbody id="productTableBody" data-sortable="1">
        <!-- Products loaded dynamically via AJAX -->
      </tbody>
      <tbody>
        <tr id="loadingRow" style="display:none;">
          <td colspan="20" class="text-center py-4">
            <i class="fas fa-spinner fa-spin me-2"></i><?= __('common.loading', 'Loading') ?>...
          </td>
        </tr>
        <tr id="noDataRow" style="display:none;">
          <td colspan="20" class="text-center py-4 text-muted">
            <i class="fas fa-inbox me-2"></i><?= __('common.no_data', 'No data available') ?>
          </td>
        </tr>
      </tbody>
    </table>
    <div id="scrollSentinel" style="height:1px;"></div>
    </div>
  </div>
  <div class="card-footer py-2 d-flex justify-content-between align-items-center">
    <span></span>
    <div class="small text-muted" id="totalCount">
      <?= __('common.total', 'Total') ?>: <span id="totalItems">0</span> <?= __('common.items', 'items') ?>
    </div>
  </div>
    
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="deleteModalLabel">
          <i class="fas fa-exclamation-triangle me-2"></i><?= __('common.confirm_delete', 'Confirm Delete') ?>
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="mb-3"><?= __('products.delete_warning', 'You are about to delete the following product:') ?></p>
        <div class="alert alert-warning">
          <strong id="deleteProductName"></strong>
        </div>
        <p class="mb-3"><?= __('products.delete_instruction', 'To confirm deletion, please type') ?> <strong>DELETE</strong> <?= __('products.delete_instruction_below', 'in the box below:') ?></p>
        <input type="text" id="deleteConfirmInput" class="form-control" placeholder="DELETE" autocomplete="off">
        <div class="form-text text-danger" id="deleteError" style="display:none;">
          <?= __('products.delete_error', 'Please type DELETE to confirm') ?>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= __('common.cancel', 'Cancel') ?></button>
        <button type="button" class="btn btn-danger" id="confirmDeleteBtn" disabled>
          <i class="fas fa-trash me-1"></i><?= __('common.delete', 'Delete') ?>
        </button>
      </div>
    </div>
  </div>
</div>

<form id="deleteForm" method="POST" style="display:none;"></form>

<!-- Delete All Products Modal -->
<div class="modal fade" id="deleteAllModal" tabindex="-1" aria-labelledby="deleteAllModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="deleteAllModalLabel">
          <i class="fas fa-exclamation-triangle me-2"></i>DELETE ALL PRODUCTS
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-danger">
          <i class="fas fa-radiation me-2"></i>
          <strong>DANGER ZONE - IRREVERSIBLE ACTION!</strong>
        </div>
        <p class="mb-3">You are about to <strong class="text-danger">DELETE ALL PRODUCTS</strong> from the database.</p>
        <p class="mb-3">This action will:</p>
        <ul class="text-danger">
          <li>Delete ALL products permanently</li>
          <li>Remove ALL product relationships</li>
          <li>Cannot be undone!</li>
        </ul>
        
        <hr class="my-4">
        
        <div class="mb-3">
          <label class="form-label fw-bold">Step 1: Solve this challenge</label>
          <div class="d-flex align-items-center gap-3">
            <span class="fs-4" id="mathQuestion">? + ? = ?</span>
            <input type="number" id="mathAnswer" class="form-control" style="max-width:100px" placeholder="Answer">
          </div>
          <div class="form-text text-danger" id="mathError" style="display:none;">
            Incorrect answer. Please try again.
          </div>
        </div>
        
        <div class="mb-3">
          <label class="form-label fw-bold">Step 2: Type "DELETE ALL PRODUCTS" to confirm</label>
          <input type="text" id="deleteAllConfirmInput" class="form-control" placeholder="DELETE ALL PRODUCTS" autocomplete="off">
          <div class="form-text text-danger" id="deleteAllError" style="display:none;">
            Please type exactly: DELETE ALL PRODUCTS
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="confirmDeleteAllBtn" disabled>
          <i class="fas fa-trash-alt me-1"></i>DELETE ALL PRODUCTS
        </button>
      </div>
    </div>
  </div>
</div>

<script>
// Global variables
window.DB_COLUMNS = <?php echo json_encode($db_columns ?? []); ?>;
window.DATA_CATEGORIES = <?php echo json_encode(array_map(fn($c)=>['id'=>$c['id'],'name'=>$c['name']], $categories)); ?>;
window.DATA_STATUS = ['active','notactive','blocked'];

// Checkbox update function (defined early for use in attachRowHandlers)
function updateCheckboxes() {
  const checkAll = document.getElementById('checkAll');
  const checks = [...document.querySelectorAll('#productTableBody .rowCheck')];
  const bulkBtn = document.getElementById('bulkDeleteBtn');
  const selCount = document.getElementById('selCount');
  
  const selected = checks.filter(c => c.checked).length;
  bulkBtn.disabled = selected === 0;
  selCount.textContent = selected ? selected + ' selected' : '';
  
  if (selected === checks.length && checks.length > 0) {
    checkAll.indeterminate = false;
    checkAll.checked = true;
  } else if (selected === 0) {
    checkAll.indeterminate = false;
    checkAll.checked = false;
  } else {
    checkAll.indeterminate = true;
  }
}

// AJAX Dynamic Loading
let currentOffset = 0;
const LOAD_LIMIT = 50;
let isLoading = false;
let hasMoreData = true;

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text || '';
  return div.innerHTML;
}

function getFilters() {
  const form = document.querySelector('.data-filters');
  return {
    q: form.querySelector('[name="q"]').value,
    category: form.querySelector('[name="category"]').value,
    status: form.querySelector('[name="status"]').value,
    sort: form.querySelector('[name="sort"]').value,
    dir: form.querySelector('[name="dir"]').value
  };
}

function buildProductRow(p) {
  const dbCols = window.DB_COLUMNS;
  const explicitCell = ['code','name','category','price','status','sort_order'];
  
  let extraCols = '';
  dbCols.forEach(dbc => {
    if (explicitCell.includes(dbc)) return;
    let val = p[dbc] ?? '';
    if (dbc === 'report_flags') {
      if (typeof val === 'string') {
        try { val = JSON.parse(val).join(','); } catch(e) {}
      } else if (Array.isArray(val)) {
        val = val.join(',');
      }
    }
    extraCols += `<td class="d-none" data-col="${escapeHtml(dbc)}">${escapeHtml(val)}</td>`;
  });
  
  const statusBadge = p.status === 'active' ? 'success' : (p.status === 'blocked' ? 'danger' : 'secondary');
  const priceDisplay = p.price !== null ? parseFloat(p.price).toFixed(2) + ' ' + escapeHtml(p.price_unit ?? '') : '';
  
  return `<tr data-id="${p.id}" draggable="true">
    <td data-col="select" class="mobile-show"><input type="checkbox" name="ids[]" value="${p.id}" class="rowCheck"></td>
    <td data-col="code" class="text-muted cursor-move editable mobile-show" data-field="code" style="cursor:move" title="Drag to reorder / dblclick to edit">☰ <span class="cell-value"><code>${escapeHtml(p.code ?? '')}</code></span></td>
    <td data-col="name" class="editable mobile-show" data-field="name">
      <span class="cell-value fw-bold">${escapeHtml(p.name ?? '')}</span>
      <div class="mobile-details d-md-none small text-muted mt-1">
        ${escapeHtml(p.category_name ?? '')}</div>
        ${priceDisplay || ''}</div>
       <span class="badge text-${statusBadge}">${escapeHtml(p.status ?? '')}</span></div>
      </div>
    </td>
    <td data-col="category" class="editable mobile-hide" data-field="category_id" data-type="select" data-source="category"><span class="cell-value" data-id="${escapeHtml(p.category_id ?? '')}">${escapeHtml(p.category_name ?? '')}</span></td>
    <td data-col="price" class="editable mobile-hide" data-field="price"><span class="cell-value">${priceDisplay}</span></td>
    <td data-col="status" class="editable mobile-hide" data-field="status" data-type="select" data-source="status"><span class="badge cell-value bg-${statusBadge}" data-id="${escapeHtml(p.status ?? '')}">${escapeHtml(p.status ?? '')}</span></td>
    <td data-col="sort_order" class="editable mobile-hide" data-field="sort_order"><span class="cell-value">${parseInt(p.sort_order ?? 0)}</span></td>
    ${extraCols}
    <td data-col="actions" class="text-end mobile-show">
      <a href="/samanta_crm/products/${p.id}/edit" class="btn btn-sm btn-outline-primary"><i class="fas fa-edit d-md-none"></i><span class="d-none d-md-inline"><?= __('common.edit', 'Edit') ?></span></a>
      <button type="button" class="btn btn-sm btn-outline-danger delete-btn" data-id="${p.id}" data-name="${escapeHtml(p.name ?? '')}"><i class="fas fa-trash d-md-none"></i><span class="d-none d-md-inline"><?= __('common.delete', 'Delete') ?></span></button>
    </td>
  </tr>`;
}

function loadProducts(reset = false) {
  if (isLoading || (!hasMoreData && !reset)) return;
  
  if (reset) {
    currentOffset = 0;
    hasMoreData = true;
    document.getElementById('productTableBody').innerHTML = '';
  }
  
  isLoading = true;
  document.getElementById('loadingRow').style.display = '';
  document.getElementById('noDataRow').style.display = 'none';
  
  const filters = getFilters();
  const params = new URLSearchParams({
    ...filters,
    offset: currentOffset,
    limit: LOAD_LIMIT
  });
  
  fetch('/samanta_crm/products/get-products?' + params)
    .then(r => r.json())
    .then(data => {
      if (data.success) {
        const tbody = document.getElementById('productTableBody');
        
        if (data.products.length === 0 && currentOffset === 0) {
          document.getElementById('noDataRow').style.display = '';
        } else {
          data.products.forEach(p => {
            tbody.insertAdjacentHTML('beforeend', buildProductRow(p));
          });
          
          currentOffset += data.products.length;
          hasMoreData = data.hasMore;
          
          // Re-attach event handlers
          attachRowHandlers();
          applyVisibility();
          applyFilters();
          updateCheckboxes();
        }
        
        document.getElementById('totalItems').textContent = data.total;
      }
    })
    .catch(err => {
      console.error('Load error:', err);
      alert('Failed to load products');
    })
    .finally(() => {
      isLoading = false;
      document.getElementById('loadingRow').style.display = 'none';
    });
}

function attachRowHandlers() {
  const tbody = document.getElementById('productTableBody');
  let draggingRow = null;
  
  // Drag & drop
  tbody.querySelectorAll('tr').forEach(tr => {
    if (tr.dataset.handlersAttached) return;
    tr.dataset.handlersAttached = 'true';
    
    tr.addEventListener('dragstart', e => {
      draggingRow = tr;
      e.dataTransfer.effectAllowed = 'move';
      tr.classList.add('opacity-50');
    });
    
    tr.addEventListener('dragend', () => {
      if (draggingRow) {
        draggingRow.classList.remove('opacity-50');
        draggingRow = null;
      }
    });
    
    tr.addEventListener('dragover', e => {
      e.preventDefault();
      if (!draggingRow || tr === draggingRow) return;
      const rows = [...tbody.children];
      const targetIndex = rows.indexOf(tr);
      if (targetIndex > rows.indexOf(draggingRow)) tr.after(draggingRow);
      else tr.before(draggingRow);
    });
  });
  
  tbody.addEventListener('drop', () => saveOrder(), { once: false });
  
  // Inline editing
  tbody.querySelectorAll('td.editable').forEach(td => {
    if (td.dataset.editAttached) return;
    td.dataset.editAttached = 'true';
    td.addEventListener('dblclick', () => makeEditable(td));
  });
  
  // Checkboxes
  tbody.querySelectorAll('.rowCheck').forEach(c => {
    if (c.dataset.checkAttached) return;
    c.dataset.checkAttached = 'true';
    c.addEventListener('change', updateCheckboxes);
  });
  
  // Delete buttons
  tbody.querySelectorAll('.delete-btn').forEach(btn => {
    if (btn.dataset.deleteAttached) return;
    btn.dataset.deleteAttached = 'true';
    btn.addEventListener('click', function() {
      const id = this.dataset.id;
      const name = this.dataset.name;
      confirmDelete(id, name);
    });
  });
}

function saveOrder() {
  const tbody = document.getElementById('productTableBody');
  const ids = [...tbody.querySelectorAll('tr')].map(r => r.getAttribute('data-id'));
  fetch('/samanta_crm/products/save-order', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: ids.map(id => 'order[]=' + encodeURIComponent(id)).join('&')
  })
  .then(r => r.json())
  .then(j => { if (!j.success) alert('Failed to save order'); });
}

// Infinite scroll
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting && hasMoreData && !isLoading) {
      loadProducts();
    }
  });
}, { rootMargin: '200px' });

const sentinel = document.getElementById('scrollSentinel');
if (sentinel) observer.observe(sentinel);

// Filter form
document.querySelector('.data-filters').addEventListener('submit', e => {
  e.preventDefault();
  loadProducts(true);
});

// Auto-filter on change
document.querySelectorAll('.data-filters select').forEach(el => {
  el.addEventListener('change', () => loadProducts(true));
});

let searchTimeout;
document.querySelector('.data-filters input[name="q"]').addEventListener('input', e => {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => loadProducts(true), 500);
});

// Initial load
loadProducts(true);

// Delete confirmation with modal
let deleteProductId = null;
let deleteModal = null;

function confirmDelete(productId, productName) {
  deleteProductId = productId;
  document.getElementById('deleteProductName').textContent = productName;
  document.getElementById('deleteConfirmInput').value = '';
  document.getElementById('deleteError').style.display = 'none';
  document.getElementById('confirmDeleteBtn').disabled = true;
  
  if (!deleteModal) {
    deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
  }
  deleteModal.show();
}

// Enable delete button only when "DELETE" is typed
document.getElementById('deleteConfirmInput').addEventListener('input', function() {
  const btn = document.getElementById('confirmDeleteBtn');
  const error = document.getElementById('deleteError');
  
  if (this.value === 'DELETE') {
    btn.disabled = false;
    error.style.display = 'none';
  } else {
    btn.disabled = true;
  }
});

// Handle delete confirmation
document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
  const input = document.getElementById('deleteConfirmInput');
  const error = document.getElementById('deleteError');
  
  if (input.value !== 'DELETE') {
    error.style.display = 'block';
    return;
  }
  
  // Submit delete form
  const form = document.getElementById('deleteForm');
  form.action = '/samanta_crm/products/' + deleteProductId + '/delete';
  form.method = 'POST';
  form.submit();
});

// Bulk delete function
function bulkDeleteProducts() {
  const selected = [...document.querySelectorAll('#productTableBody .rowCheck:checked')];
  
  if (selected.length === 0) {
    alert('<?= __('common.select_items', 'Please select items to delete') ?>');
    return;
  }
  
  if (!confirm('<?= __('products.delete_confirm_bulk', 'Are you sure you want to delete') ?> ' + selected.length + ' <?= __('common.products', 'products') ?>?')) {
    return;
  }
  
  console.log('Deleting products:', selected.map(c => c.value));
  
  // Create and submit form
  const form = document.createElement('form');
  form.method = 'POST';
  form.action = '/samanta_crm/products/bulk-delete';
  form.style.display = 'none';
  
  selected.forEach(checkbox => {
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'ids[]';
    input.value = checkbox.value;
    form.appendChild(input);
  });
  
  document.body.appendChild(form);
  
  console.log('Form data:', new FormData(form));
  console.log('Submitting to:', form.action);
  
  form.submit();
}

// Reset on modal close
document.getElementById('deleteModal').addEventListener('hidden.bs.modal', function() {
  deleteProductId = null;
  document.getElementById('deleteConfirmInput').value = '';
  document.getElementById('deleteError').style.display = 'none';
});

// Delete All Products functionality
let deleteAllModal = null;
let mathNum1 = 0;
let mathNum2 = 0;
let mathCorrectAnswer = 0;

function deleteAllProducts() {
  // Generate random math challenge
  mathNum1 = Math.floor(Math.random() * 20) + 1;
  mathNum2 = Math.floor(Math.random() * 20) + 1;
  mathCorrectAnswer = mathNum1 + mathNum2;
  
  document.getElementById('mathQuestion').textContent = `${mathNum1} + ${mathNum2} = ?`;
  document.getElementById('mathAnswer').value = '';
  document.getElementById('deleteAllConfirmInput').value = '';
  document.getElementById('mathError').style.display = 'none';
  document.getElementById('deleteAllError').style.display = 'none';
  document.getElementById('confirmDeleteAllBtn').disabled = true;
  
  if (!deleteAllModal) {
    deleteAllModal = new bootstrap.Modal(document.getElementById('deleteAllModal'));
  }
  deleteAllModal.show();
}

// Validate math answer
document.getElementById('mathAnswer').addEventListener('input', function() {
  validateDeleteAll();
});

// Validate confirmation text
document.getElementById('deleteAllConfirmInput').addEventListener('input', function() {
  validateDeleteAll();
});

function validateDeleteAll() {
  const mathAnswer = parseInt(document.getElementById('mathAnswer').value);
  const confirmText = document.getElementById('deleteAllConfirmInput').value;
  const btn = document.getElementById('confirmDeleteAllBtn');
  const mathError = document.getElementById('mathError');
  const textError = document.getElementById('deleteAllError');
  
  let mathValid = false;
  let textValid = false;
  
  // Check math
  if (mathAnswer === mathCorrectAnswer) {
    mathValid = true;
    mathError.style.display = 'none';
  } else if (document.getElementById('mathAnswer').value !== '') {
    mathError.style.display = 'block';
  }
  
  // Check text
  if (confirmText === 'DELETE ALL PRODUCTS') {
    textValid = true;
    textError.style.display = 'none';
  } else if (confirmText !== '') {
    textError.style.display = 'block';
  }
  
  // Enable button only if both valid
  btn.disabled = !(mathValid && textValid);
}

// Handle delete all confirmation
document.getElementById('confirmDeleteAllBtn').addEventListener('click', function() {
  const mathAnswer = parseInt(document.getElementById('mathAnswer').value);
  const confirmText = document.getElementById('deleteAllConfirmInput').value;
  
  if (mathAnswer !== mathCorrectAnswer) {
    document.getElementById('mathError').style.display = 'block';
    return;
  }
  
  if (confirmText !== 'DELETE ALL PRODUCTS') {
    document.getElementById('deleteAllError').style.display = 'block';
    return;
  }
  
  // Final confirmation
  if (!confirm('THIS IS YOUR LAST WARNING!\n\nAll products will be permanently deleted.\n\nClick OK to proceed with deletion.')) {
    return;
  }
  
  // Submit delete all
  const form = document.createElement('form');
  form.method = 'POST';
  form.action = '/samanta_crm/products/delete-all';
  form.style.display = 'none';
  
  document.body.appendChild(form);
  form.submit();
});

// Reset on modal close
document.getElementById('deleteAllModal').addEventListener('hidden.bs.modal', function() {
  document.getElementById('mathAnswer').value = '';
  document.getElementById('deleteAllConfirmInput').value = '';
  document.getElementById('mathError').style.display = 'none';
  document.getElementById('deleteAllError').style.display = 'none';
});

// Column visibility + filters (global scope)
const STORAGE_COLS='productColumnsVisible';
const STORAGE_FILTERS='productColumnFilters';
const dbCols = <?php echo json_encode($db_columns ?? []); ?>;
const aliasMap = { category_id:'category', report_flags:'flags' };
const baseCols=['select'];
const derived=['category','price','status','sort_order'];
let allColumns = Array.from(new Set(baseCols.concat(dbCols.map(c=>aliasMap[c]||c)).concat(['actions'])));
if(!allColumns.includes('category')) allColumns.splice( allColumns.indexOf('category_id')!==-1? allColumns.indexOf('category_id')+1 : 2, 0, 'category');
const filterable = allColumns.filter(c=>['select','actions','report_flags','notes','description'].indexOf(c)===-1);
let visible = JSON.parse(localStorage.getItem(STORAGE_COLS) || 'null') || ['select','code','name','category','price','status','sort_order','actions'];
if(!visible.includes('select')) visible.unshift('select');
if(!visible.includes('actions')) visible.push('actions');
const table=document.getElementById('productsTable');
let filters = JSON.parse(localStorage.getItem(STORAGE_FILTERS) || '{}');

function getHeaderCols(){
  return Array.from(document.querySelectorAll('#productsTable thead tr:first-child th[data-col]'))
    .map(th=>th.getAttribute('data-col'));
}

function applyVisibility(){
  const headerOrder = getHeaderCols();
  headerOrder.forEach(col=>{
    const show = visible.includes(col) || col==='select' || col==='actions';
    table.querySelectorAll('[data-col="'+col+'"]').forEach(el=>{ if(show) el.classList.remove('d-none'); else el.classList.add('d-none'); });
  });
  buildFilterRow();
}

function buildFilterRow(){
  const filterRow=document.getElementById('filterRow');
  if(!filterRow) return; 
  filterRow.innerHTML='';
  const headerCols = getHeaderCols();
  headerCols.forEach(col=>{
    const cell=document.createElement('th'); cell.dataset.col=col;
    const colHidden = !visible.includes(col) && col!=='select' && col!=='actions';
    if(colHidden) cell.classList.add('d-none');
    if(filterable.includes(col) && !colHidden){
      if(col==='status'){
        const sel=document.createElement('select'); sel.className='form-select form-select-sm'; sel.innerHTML='<option value="">*</option><option value="active">active</option><option value="notactive">notactive</option><option value="blocked">blocked</option>'; sel.value=filters[col]||''; sel.onchange=()=>{ filters[col]=sel.value; persistFilters(); applyFilters(); }; cell.appendChild(sel);
      } else {
        const input=document.createElement('input'); input.type='text'; input.className='form-control form-control-sm'; input.placeholder='filter'; input.value=filters[col]||''; input.oninput=()=>{ filters[col]=input.value; persistFilters(); applyFilters(); }; cell.appendChild(input);
      }
    }
    filterRow.appendChild(cell);
  });
}

function persistFilters(){ 
  localStorage.setItem(STORAGE_FILTERS, JSON.stringify(filters)); 
}

function applyFilters(){
  const rows=[...document.querySelectorAll('#productTableBody tr')];
  rows.forEach(r=>{
    let show=true;
    for(const col of filterable){
      if(filters[col]){
        const cell=r.querySelector('[data-col="'+col+'"]');
        const txt=(cell? cell.innerText : '').toLowerCase();
        if(!txt.includes(filters[col].toLowerCase())){ show=false; break; }
      }
    }
    r.style.display=show?'' : 'none';
  });
}

(function(){
  const chooserList=document.getElementById('colChooserList');
  if(chooserList){
    allColumns.forEach(col=>{
      if(col==='select'||col==='actions') return;
      const id='col_'+col;
      const wrap=document.createElement('div'); wrap.className='form-check';
      wrap.innerHTML='<input class="form-check-input" type="checkbox" id="'+id+'"> <label class="form-check-label" for="'+id+'">'+col.replace('_',' ')+'</label>';
      const chk=wrap.querySelector('input'); chk.checked=visible.includes(col);
      chk.addEventListener('change',()=>{ if(chk.checked){ if(!visible.includes(col)) visible.push(col); } else { visible=visible.filter(c=>c!==col); } localStorage.setItem(STORAGE_COLS, JSON.stringify(visible)); applyVisibility(); });
      chooserList.appendChild(wrap);
    });
  }
  
  applyVisibility();
  applyFilters();
  
  const checkAll=document.getElementById('checkAll');
  const bulkBtn=document.getElementById('bulkDeleteBtn');
  const selCount=document.getElementById('selCount');
  
  checkAll && (checkAll.onchange=()=>{ 
    const checks = [...document.querySelectorAll('#productTableBody .rowCheck')];
    checks.forEach(c=>c.checked=checkAll.checked); 
    updateCheckboxes(); 
  });
  
  // Drag & drop reorder (simple HTML5 API)
  const tbody=document.getElementById('productTableBody');
  if(tbody){
    let draggingRow=null; let startIndex=null;
    tbody.querySelectorAll('tr').forEach(tr=>{ tr.draggable=true; tr.addEventListener('dragstart',e=>{ draggingRow=tr; startIndex=[...tbody.children].indexOf(tr); e.dataTransfer.effectAllowed='move'; tr.classList.add('opacity-50'); }); tr.addEventListener('dragend',()=>{ if(draggingRow){ draggingRow.classList.remove('opacity-50'); draggingRow=null; } }); tr.addEventListener('dragover',e=>{ e.preventDefault(); const target=tr; if(!draggingRow || target===draggingRow) return; const rows=[...tbody.children]; const targetIndex=rows.indexOf(target); if(targetIndex>rows.indexOf(draggingRow)) target.after(draggingRow); else target.before(draggingRow); }); });
    tbody.addEventListener('drop',()=>{ saveOrder(); });
    function saveOrder(){ const ids=[...tbody.querySelectorAll('tr')].map(r=>r.getAttribute('data-id')); fetch('/samanta_crm/products/save-order',{ method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: ids.map(id=>'order[]='+encodeURIComponent(id)).join('&') })
      .then(r=>r.json()).then(j=>{ if(!j.success){ alert('Failed to save order'); } }); }
  }
  // Inline editing with support for select fields
  const DATA_CATEGORIES = <?php echo json_encode(array_map(fn($c)=>['id'=>$c['id'],'name'=>$c['name']], $categories)); ?>;
  const DATA_STATUS = ['active','notactive','blocked'];
  function makeEditable(td){
    if(td.classList.contains('editing')) return; const field=td.dataset.field; if(!field) return;
    const row=td.closest('tr'); const id=row.getAttribute('data-id');
    const span=td.querySelector('.cell-value'); const original=span?span.textContent.trim():''; const originalId=span? span.getAttribute('data-id') || original : original;
    td.classList.add('editing');
    let input;
    if(td.dataset.type==='select'){
      input=document.createElement('select'); input.className='form-select form-select-sm';
      let source=[]; if(td.dataset.source==='status'){ source=DATA_STATUS.map(s=>({value:s,label:s})); }
      else if(td.dataset.source==='category'){ source=DATA_CATEGORIES.map(c=>({value:c.id,label:c.name})); }
      source.forEach(opt=>{ const o=document.createElement('option'); o.value=opt.value; o.textContent=opt.label; if(String(opt.value)===String(originalId)) o.selected=true; input.appendChild(o); });
    } else { input=document.createElement('input'); input.type='text'; input.className='form-control form-control-sm'; input.value=original; }
    span && span.classList.add('d-none'); td.appendChild(input); input.focus(); if(input.select) input.select();
    function cancel(){ td.classList.remove('editing'); if(span) span.classList.remove('d-none'); input.remove(); }
    function commit(){ const newVal=(input.tagName==='SELECT'? input.value : input.value.trim()); if(newVal===originalId){ cancel(); return; }
      const formData=new URLSearchParams(); formData.append('id',id); formData.append('field',field); formData.append('value',newVal);
      fetch('/samanta_crm/products/inline-update',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:formData.toString()})
        .then(r=>r.json()).then(j=>{ if(j.success){ if(field==='status'){ span.textContent=j.value; span.setAttribute('data-id',j.value); span.className='badge cell-value bg-'+(j.value==='active'?'success':(j.value==='blocked'?'danger':'secondary')); } else if(field==='category_id'){ const match=DATA_CATEGORIES.find(c=>String(c.id)===String(j.value)); span.textContent=match?match.name:''; span.setAttribute('data-id',j.value); } else { span.textContent=j.value; } cancel(); } else { alert(j.error||'Save failed'); cancel(); } })
        .catch(()=>{ alert('Network error'); cancel(); });
    }
    input.addEventListener('keydown',e=>{ if(e.key==='Enter'){ e.preventDefault(); commit(); } else if(e.key==='Escape'){ e.preventDefault(); cancel(); } });
    if(input.tagName==='SELECT') input.addEventListener('change',commit);
    input.addEventListener('blur',()=>{ setTimeout(()=>{ if(td.contains(input)) cancel(); },150); });
  }
  document.querySelectorAll('#productTableBody td.editable').forEach(td=>{
    td.addEventListener('dblclick',()=>makeEditable(td));
  });
})();
</script>

<style>
/* Hide columns on mobile, show on desktop */
.mobile-hide {
  display: none;
}

.mobile-show {
  display: table-cell;
}

@media (min-width: 768px) {
  .mobile-hide {
    display: table-cell;
  }
}

/* Mobile details that appear under product name */
.mobile-details {
  display: none;
  padding: 0.5rem 0;
  border-top: 1px solid #e9ecef;
  margin-top: 0.5rem;
}

@media (max-width: 767px) {
  .mobile-details {
    display: block;
  }
  
  .mobile-details > div {
    padding: 0.25rem 0;
  }
  
  /* Make table more compact on mobile */
  #productsTable {
    min-width: auto !important;
  }
  
  /* Reduce padding in table cells for mobile */
  #productsTable td,
  #productsTable th {
    padding: 0.5rem 0.25rem;
    font-size: 0.875rem;
  }
  
  /* Code column more compact */
  #productsTable td[data-col="code"] {
    font-size: 0.75rem;
    min-width: 50px;
  }
  
  /* Name column takes more space */
  #productsTable td[data-col="name"] {
    width: auto;
    max-width: 200px;
  }
  
  /* Make checkboxes touch-friendly */
  #productsTable input[type="checkbox"] {
    width: 1.25rem;
    height: 1.25rem;
    cursor: pointer;
  }
  
  /* Action buttons show only icons on mobile */
  #productsTable td[data-col="actions"] {
    white-space: nowrap;
  }
  
  #productsTable td[data-col="actions"] .btn {
    padding: 0.375rem 0.5rem;
    min-width: 36px;
  }
  
  /* Ensure badges in mobile details are readable */
  .mobile-details .badge {
    font-size: 0.75rem;
    padding: 0.25em 0.5em;
  }
  
  /* Hide filter row on mobile for cleaner look */
  #filterRow {
    display: none;
  }
  
  /* Make selection counter more prominent */
  #selCount {
    font-size: 0.875rem;
    padding: 0.5rem 1rem !important;
  }
}

/* Desktop improvements */
@media (min-width: 768px) {
  /* Improve touch targets for drag handle */
  #productsTable td[data-col="code"] {
    min-width: 80px;
  }
  
  /* Table with reasonable minimum width */
  #productsTable {
    min-width: 800px;
  }
  
  /* Sticky header on scroll */
  .table-responsive {
    max-height: calc(100vh - 400px);
    overflow-y: auto;
  }
  
  #productsTable thead th {
    position: sticky;
    top: 0;
    background: white;
    z-index: 10;
    box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1);
  }
}

/* Better visual feedback for dragging */
.opacity-50 {
  opacity: 0.5 !important;
}

/* Smooth scrolling on touch devices */
.table-responsive {
  -webkit-overflow-scrolling: touch;
}
</style>

<?php $content=ob_get_clean(); include '../app/Views/layout.php'; ?>


