<?php $title=__('orders.orders', 'Orders'); ob_start(); ?>

<div class="d-flex justify-content-between align-items-center mb-2 flex-column flex-lg-row flex-md-column">
    <h1 class="h3 mb-3">
        <i class="fas fa-receipt"></i> <?= __('orders.orders', 'Orders') ?>
    </h1>
    <div class="gap-3 flex-lg-row flex-md-column text-center">
        <a href="/samanta_crm/reports/daily" class="btn btn-secondary mb-2"><i class="fas fa-calendar-day me-1"></i> <?= __('reports.daily', 'Daily Report') ?></a>
         
    </div>
    <div class="gap-3 flex-lg-row flex-md-column justify-content-center align-items-center text-center mb-3 mb-lg-0">
        <a href="/samanta_crm/orders/create" class="btn btn-primary mb-2"><i class="fas fa-plus"></i> <?= __('orders.new_order', 'New Order') ?></a>
         <a href="/samanta_crm/orders/panel" class="btn btn-info mb-2"><i class="fas fa-tablet-alt"></i> <?= __('orders.tablet_panel', 'Tablet Panel') ?></a>
        
        <a href="/samanta_crm/orders?export=excel" class="btn btn-secondary mb-2"><i class="fas fa-file-excel"></i> Excel</a>
        
        <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
        <button type="button" class="btn btn-danger mb-2" onclick="deleteAllOrders()">
            <i class="fas fa-trash-alt me-1"></i> Delete All Orders
        </button>
        <?php endif; ?>
    </div>
</div>

<form class="row g-2 align-items-end data-filters position-sticky sticky-top" method="GET" action="/samanta_crm/orders">
  <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 collapsed " id="filtersWrap">
      <div class="card-body py-3">
        <div class="row g-2 align-items-end">
          <div class="col-md-1 col-6">
            <label class="form-label small mb-0 "><?= __('common.per_page', 'Per Page') ?></label>
            <select id="perPageSelect" class="form-select form-select-sm">
              <option value="10">10</option>
              <option value="25" selected>25</option>
              <option value="50">50</option>
              <option value="100">100</option>
            </select>
          </div>
          <div class="col-md-2 col-6">
            <label class="form-label small mb-0 "><?= __('common.from', 'From') ?></label>
            <input type="date" name="date_from" value="<?=htmlspecialchars($filters['date_from'] ?? '', ENT_QUOTES, 'UTF-8')?>" class="form-control form-control-sm" placeholder="<?= __('common.from', 'From') ?>">
          </div>
          <div class="col-md-2 col-6">
            <label class="form-label small mb-0 "><?= __('common.to', 'To') ?></label>
            <input type="date" name="date_to" value="<?=htmlspecialchars($filters['date_to'] ?? '', ENT_QUOTES, 'UTF-8')?>" class="form-control form-control-sm" placeholder="<?= __('common.to', 'To') ?>">
          </div>
          <div class="col-md-3 col-6">
            <label class="form-label small mb-0 "><?= __('common.customer', 'Customer') ?></label>
            <select name="customer_id" class="form-select form-select-sm">
              <option value=""><?= __('common.all', 'All') ?></option>
              <?php foreach($customers as $c): ?>
                <option value="<?=$c['id'];?>" <?=$filters['customer_id']==$c['id']?'selected':'';?>><?=htmlspecialchars($c['name'] ?? '', ENT_QUOTES, 'UTF-8');?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-2 col-6">
            <label class="form-label small mb-0 "><?= __('customers.type', 'Customer Type') ?></label>
            <select name="customer_type" class="form-select form-select-sm">
              <option value=""><?= __('common.all', 'All') ?></option>
              <option value="inhouse" <?=($filters['customer_type']??'inhouse')==='inhouse'?'selected':'';?>><?= __('customers.inhouse', 'In-house') ?></option>
              <option value="customer" <?=($filters['customer_type']??'')==='customer'?'selected':'';?>><?= __('customers.customer', 'Customer') ?></option>
            </select>
          </div>
          <div class="col-md-2 col-6">
            <label class="form-label small mb-0 "><?= __('common.type', 'Type') ?></label>
            <select name="order_type" class="form-select form-select-sm">
              <option value=""><?= __('common.all', 'All') ?></option>
              <?php if(isset($orderTypes)) foreach($orderTypes as $ot): ?>
                <option value="<?= htmlspecialchars($ot, ENT_QUOTES, 'UTF-8') ?>" <?=$filters['order_type']==$ot?'selected':'';?>><?=ucfirst(htmlspecialchars($ot, ENT_QUOTES, 'UTF-8'))?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-2 col-6">
            <label class="form-label small mb-0 "><?= __('common.status', 'Status') ?></label>
            <select name="status" class="form-select form-select-sm">
              <option value=""><?= __('common.all', 'All') ?></option>
              <?php foreach(['pending','processing','completed','cancelled'] as $st): ?>
                <option value="<?=$st?>" <?=$filters['status']==$st?'selected':'';?>><?=ucfirst($st)?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-2 col-6">
            <label class="form-label small mb-0 "><?= __('orders.verified', 'Verified') ?></label>
            <select name="verified" class="form-select form-select-sm">
              <option value=""><?= __('common.all', 'All') ?></option>
              <option value="1" <?=$filters['verified']==='1'?'selected':'';?>><?= __('common.yes', 'Yes') ?></option>
              <option value="0" <?=$filters['verified']==='0'?'selected':'';?>><?= __('common.no', 'No') ?></option>
            </select>
          </div>
          <div class="col-auto">
            <button class="btn btn-outline-secondary btn-sm"><i class="fas fa-filter me-1"></i><?= __('common.filter', 'Filter') ?></button>
          </div>
        </div>
      </div>
    </div>
  </div>
</form>

<div class="card">
  <div class="card-header py-2">
    <span class="small fw-bold"><i class="fas fa-table me-1"></i><?= __('orders.orders', 'Orders') ?></span>
  </div>
  <div class="card-body pt-0">
    <div class="table-responsive">
      <table class="table table-sm table-hover align-middle data-table mb-0" id="ordersTable">
        <thead class="table-light">
          <tr>
            <th>ID</th>
            <th><?= __('orders.order_date', 'Order Date') ?></th>
            <th class="d-none d-lg-table-cell"><?= __('orders.delivery_date', 'Delivery Date') ?></th>
            <th class="d-none d-md-table-cell"><?= __("common.type", "Type") ?></th>
            <th><?= __('common.customer', 'Customer') ?></th>
            <th class="d-none d-xl-table-cell"><?= __('orders.assigned', 'Assigned') ?></th>
            <th><?= __("common.status", "Status") ?></th>
            <th class="d-none d-lg-table-cell"><?= __('orders.items', 'Items') ?></th>
            <th class="d-none d-xl-table-cell"><?= __('orders.verified', 'Verified') ?></th>
            <th class="text-end"><?= __('common.actions', 'Actions') ?></th>
          </tr>
        </thead>
        <tbody id="ordersTableBody">
          <!-- Orders loaded via AJAX -->
        </tbody>
      </table>
    </div>
  </div>
  <div class="card-footer py-2" id="paginationFooter">
    <!-- Pagination loaded via AJAX -->
  </div>
</div>

<!-- Loading Overlay -->
<div id="loadingOverlay" class="position-fixed top-0 start-0 w-100 h-100 d-none" style="background: rgba(0,0,0,0.3); z-index: 9999;">
  <div class="position-absolute top-50 start-50 translate-middle">
    <div class="spinner-border text-light" role="status">
      <span class="visually-hidden">Loading...</span>
    </div>
  </div>
</div>

<!-- Order Details Offcanvas -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="orderDetailsOffcanvas" style="width: 500px;">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title">Order Details</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
  </div>
  <div class="offcanvas-body" id="orderDetailsContent">
    <div class="text-center py-5">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">Loading...</span>
      </div>
    </div>
  </div>
</div>

<!-- Delete All Orders 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 ORDERS
        </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 ORDERS</strong> from the database.</p>
        <p class="mb-3">This action will:</p>
        <ul class="text-danger">
          <li>Delete ALL orders permanently</li>
          <li>Delete ALL order items</li>
          <li>Remove ALL order history</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 ORDERS" to confirm</label>
          <input type="text" id="deleteAllConfirmInput" class="form-control" placeholder="DELETE ALL ORDERS" autocomplete="off">
          <div class="form-text text-danger" id="deleteAllError" style="display:none;">
            Please type exactly: DELETE ALL ORDERS
          </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 ORDERS
        </button>
      </div>
    </div>
  </div>
</div>

<script>
let currentPage = 1;
let perPage = 25;
let isLoading = false;

function showLoading() {
  document.getElementById('loadingOverlay').classList.remove('d-none');
  isLoading = true;
}

function hideLoading() {
  document.getElementById('loadingOverlay').classList.add('d-none');
  isLoading = false;
}

function getFilters() {
  const form = document.querySelector('.data-filters');
  const formData = new FormData(form);
  const filters = {};
  for (const [key, value] of formData.entries()) {
    if (value) filters[key] = value;
  }
  // Default customer_type to 'inhouse' if not set
  if (!filters.customer_type) {
    filters.customer_type = 'inhouse';
  }
  return filters;
}

function fetchOrders(page = 1) {
  if (isLoading) return;
  
  showLoading();
  currentPage = page;
  
  const filters = getFilters();
  const params = new URLSearchParams({
    ajax: '1',
    page: page,
    per_page: perPage,
    ...filters
  });
  
  fetch(`/samanta_crm/orders?${params}`)
    .then(response => response.json())
    .then(data => {
      renderOrders(data.orders);
      renderPagination(data.pagination);
      hideLoading();
    })
    .catch(error => {
      console.error('Error fetching orders:', error);
      hideLoading();
    });
}

function renderOrders(orders) {
  const tbody = document.getElementById('ordersTableBody');
  
  if (orders.length === 0) {
    tbody.innerHTML = '<tr><td colspan="10" class="text-center text-muted py-4">No orders found</td></tr>';
    return;
  }
  
  tbody.innerHTML = orders.map(o => {
    const orderDate = new Date(o.order_date);
    const deliveryDate = new Date(o.delivery_date);
    const statusBadge = o.status === 'completed' ? 'success' : (o.status === 'cancelled' ? 'danger' : 'secondary');
    const verifiedIcon = o.confirmed ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>';
    
    return `
      <tr>
        <td><code class="small"><strong>${o.id}</strong></code></td>
        <td class="text-nowrap small">
          ${orderDate.toLocaleDateString('en-GB', {day: '2-digit', month: '2-digit', year: '2-digit'}).replace(/\//g, '/')}
          <br>
          <span class="text-muted" style="font-size:0.7rem">${orderDate.toLocaleTimeString('en-GB', {hour: '2-digit', minute: '2-digit'})}</span>
        </td>
        <td class="text-nowrap small d-none d-lg-table-cell">${deliveryDate.toLocaleDateString('en-GB', {day: '2-digit', month: '2-digit', year: '2-digit'}).replace(/\//g, '/')}</td>
        <td class="d-none d-md-table-cell"><span class="badge bg-${o.order_type || ''}">${o.order_type || ''}</span></td>
        <td>
          <strong class="small">${o.customer_name || ''}</strong>
          <div class="d-md-none small text-muted mt-1">
            <span class="badge bg-${o.order_type || ''} me-1">${o.order_type || ''}</span>
            <span class="badge bg-${statusBadge}">${o.status || ''}</span>
          </div>
          <div class="d-lg-none small text-muted mt-1">
            <i class="fas fa-truck me-1"></i>${deliveryDate.toLocaleDateString('en-GB', {day: '2-digit', month: '2-digit', year: '2-digit'}).replace(/\//g, '/')}
          </div>
        </td>
        <td class="text-muted small d-none d-xl-table-cell">${o.assigned_user_name || ''}</td>
        <td class="d-none d-md-table-cell"><span class="badge bg-${statusBadge}">${o.status || ''}</span></td>
        <td class="d-none d-lg-table-cell">${o.items_count || 0}</td>
        <td class="text-center d-none d-xl-table-cell">${verifiedIcon}</td>
        <td class="text-end">
          <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-secondary" onclick="viewOrderDetails(${o.id})" title="Quick View"><i class="fas fa-eye"></i></button>
            <a href="/samanta_crm/orders/${o.id}/edit" class="btn btn-outline-primary d-none d-sm-inline-block" title="Edit"><i class="fas fa-edit"></i></a>
            <form method="POST" action="/samanta_crm/orders/${o.id}/delete" onsubmit="return confirm('Delete order #${o.id}?');" class="d-inline d-none d-sm-inline-block">
              <button class="btn btn-outline-danger" title="Delete"><i class="fas fa-trash"></i></button>
            </form>
          </div>
        </td>
            </form>
          </div>
        </td>
      </tr>
    `;
  }).join('');
}

function renderPagination(pagination) {
  const footer = document.getElementById('paginationFooter');
  
  if (!pagination || pagination.total_count === 0) {
    footer.innerHTML = '';
    return;
  }
  
  const startItem = (pagination.current_page - 1) * pagination.per_page + 1;
  const endItem = Math.min(pagination.current_page * pagination.per_page, pagination.total_count);
  
  let paginationHTML = '<div class="d-flex justify-content-between align-items-center">';
  
  // Previous/Next buttons
  paginationHTML += '<div class="btn-group btn-group-sm">';
  paginationHTML += `<button class="btn btn-outline-secondary" onclick="fetchOrders(${pagination.current_page - 1})" ${!pagination.has_prev ? 'disabled' : ''}><i class="fas fa-chevron-left"></i> Previous</button>`;
  paginationHTML += `<button class="btn btn-outline-secondary" onclick="fetchOrders(${pagination.current_page + 1})" ${!pagination.has_next ? 'disabled' : ''}>Next <i class="fas fa-chevron-right"></i></button>`;
  paginationHTML += '</div>';
  
  // Page info
  paginationHTML += `<div class="small text-muted">Showing ${startItem}-${endItem} of ${pagination.total_count} orders</div>`;
  
  // Page numbers
  paginationHTML += '<div class="btn-group btn-group-sm">';
  
  const maxPages = 5;
  let startPage = Math.max(1, pagination.current_page - Math.floor(maxPages / 2));
  let endPage = Math.min(pagination.total_pages, startPage + maxPages - 1);
  
  if (endPage - startPage < maxPages - 1) {
    startPage = Math.max(1, endPage - maxPages + 1);
  }
  
  if (startPage > 1) {
    paginationHTML += `<button class="btn btn-outline-secondary" onclick="fetchOrders(1)">1</button>`;
    if (startPage > 2) {
      paginationHTML += '<button class="btn btn-outline-secondary" disabled>...</button>';
    }
  }
  
  for (let i = startPage; i <= endPage; i++) {
    paginationHTML += `<button class="btn ${i === pagination.current_page ? 'btn-primary' : 'btn-outline-secondary'}" onclick="fetchOrders(${i})">${i}</button>`;
  }
  
  if (endPage < pagination.total_pages) {
    if (endPage < pagination.total_pages - 1) {
      paginationHTML += '<button class="btn btn-outline-secondary" disabled>...</button>';
    }
    paginationHTML += `<button class="btn btn-outline-secondary" onclick="fetchOrders(${pagination.total_pages})">${pagination.total_pages}</button>`;
  }
  
  paginationHTML += '</div></div>';
  footer.innerHTML = paginationHTML;
}

function viewOrderDetails(orderId) {
  const offcanvas = new bootstrap.Offcanvas(document.getElementById('orderDetailsOffcanvas'));
  offcanvas.show();
  
  // Show loading state
  document.getElementById('orderDetailsContent').innerHTML = `
    <div class="text-center py-5">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">Loading...</span>
      </div>
    </div>
  `;
  
  // Fetch order details
  fetch(`/samanta_crm/orders/${orderId}?ajax=1`)
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        renderOrderDetails(data.order, data.items);
      } else {
        document.getElementById('orderDetailsContent').innerHTML = `
          <div class="alert alert-danger">Error loading order details</div>
        `;
      }
    })
    .catch(error => {
      console.error('Error fetching order details:', error);
      document.getElementById('orderDetailsContent').innerHTML = `
        <div class="alert alert-danger">Error loading order details</div>
      `;
    });
}

function renderOrderDetails(order, items) {
  const orderDate = new Date(order.order_date);
  const deliveryDate = order.delivery_date ? new Date(order.delivery_date) : null;
  const statusBadge = order.status === 'completed' ? 'success' : (order.status === 'cancelled' ? 'danger' : 'secondary');
  
  let itemsHtml = '';
  if (items && items.length > 0) {
    itemsHtml = items.map(item => {
      const itemName = item.product_name_snapshot || item.name || 'Unknown';
      const itemCode = item.product_code_snapshot || item.code || '';
      const qty = parseFloat(item.quantity || 0);
      const unit = item.price_unit || item.production_unit || '';
      const price = item.unit_price ? parseFloat(item.unit_price) : null;
      
      return `
        <tr>
          <td class="small">${itemCode ? `<code>${itemCode}</code>` : ''}</td>
          <td class="small">${itemName}</td>
          <td class="text-end small">${qty.toFixed(1)} ${unit}</td>
          ${price !== null ? `<td class="text-end small">€${price.toFixed(2)}</td>` : '<td></td>'}
        </tr>
      `;
    }).join('');
  } else {
    itemsHtml = '<tr><td colspan="4" class="text-center text-muted small">No items</td></tr>';
  }
  
  const content = `
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start mb-3">
          <div>
            <h6 class="mb-1">Order #${order.id}</h6>
            <span class="badge bg-${statusBadge}">${order.status || ''}</span>
            ${order.confirmed ? '<span class="badge bg-success ms-1"><i class="fas fa-check"></i> Verified</span>' : ''}
          </div>
          <div class="text-end">
            <a href="/samanta_crm/orders/${order.id}/edit" class="btn btn-sm btn-primary">
              <i class="fas fa-edit"></i> Edit
            </a>
          </div>
        </div>
        
        <div class="row g-2 small">
          <div class="col-6">
            <strong class="text-muted d-block">Customer</strong>
            ${order.customer_name || ''}
          </div>
          <div class="col-6">
            <strong class="text-muted d-block">Order Type</strong>
            <span class="badge bg-${order.order_type || ''}">${order.order_type || ''}</span>
          </div>
          <div class="col-6">
            <strong class="text-muted d-block">Order Date</strong>
            ${orderDate.toLocaleDateString('en-GB')} ${orderDate.toLocaleTimeString('en-GB', {hour: '2-digit', minute: '2-digit'})}
          </div>
          <div class="col-6">
            <strong class="text-muted d-block">Delivery Date</strong>
            ${deliveryDate ? deliveryDate.toLocaleDateString('en-GB') : 'N/A'}
          </div>
          ${order.assigned_user_name ? `
          <div class="col-12">
            <strong class="text-muted d-block">Assigned To</strong>
            ${order.assigned_user_name}
          </div>
          ` : ''}
          ${order.notes ? `
          <div class="col-12">
            <strong class="text-muted d-block">Notes</strong>
            <div class="p-2 bg-light rounded">${order.notes}</div>
          </div>
          ` : ''}
        </div>
      </div>
    </div>
    
    <div class="card border-0 shadow-sm">
      <div class="card-header bg-white">
        <strong>Order Items (${items.length})</strong>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th class="small">Code</th>
                <th class="small">Item</th>
                <th class="text-end small">Qty</th>
                <th class="text-end small">Price</th>
              </tr>
            </thead>
            <tbody>
              ${itemsHtml}
            </tbody>
          </table>
        </div>
      </div>
    </div>
    
    <div class="mt-3 d-grid gap-2">
      <a href="/samanta_crm/orders/${order.id}" class="btn btn-outline-secondary">
        <i class="fas fa-file-alt me-1"></i> Full Details
      </a>
      <button class="btn btn-outline-primary" onclick="window.print()">
        <i class="fas fa-print me-1"></i> Print
      </button>
    </div>
  `;
  
  document.getElementById('orderDetailsContent').innerHTML = content;
}

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

function deleteAllOrders() {
  // 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', validateDeleteAll);

// Validate confirmation text
document.getElementById('deleteAllConfirmInput').addEventListener('input', 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 ORDERS') {
    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 ORDERS') {
    document.getElementById('deleteAllError').style.display = 'block';
    return;
  }
  
  // Final confirmation
  if (!confirm('THIS IS YOUR LAST WARNING!\n\nAll orders 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/orders/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';
});

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
  // Initial load
  fetchOrders(1);
  
  // Per page change
  document.getElementById('perPageSelect').addEventListener('change', function() {
    perPage = parseInt(this.value);
    fetchOrders(1);
  });
  
  // Filter form submission
  document.querySelector('.data-filters').addEventListener('submit', function(e) {
    e.preventDefault();
    fetchOrders(1);
  });
  
  // Filter inputs change (for instant filtering)
  const filterInputs = document.querySelectorAll('.data-filters select, .data-filters input');
  filterInputs.forEach(input => {
    if (input.id !== 'perPageSelect') {
      input.addEventListener('change', function() {
        fetchOrders(1);
      });
    }
  });
});
</script>

<?php $content=ob_get_clean(); require __DIR__.'/../layout.php'; ?>


