<?php
$title = 'Zamówienia Tortów';
ob_start();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-birthday-cake me-2"></i>Zamówienia Tortów</h2>
    <a href="<?= url('cake-orders/create') ?>" class="btn btn-primary">
        <i class="fas fa-plus me-1"></i>Nowe zamówienie
    </a>
    <a href="<?= url('cake-order') ?>" class="btn btn-secondary">
        <i class="fas fa-plus me-1"></i>Formularz publiczny
    </a>
    <a href="<?= url('cake-features') ?>" class="btn btn-secondary">
        <i class="fas fa-cog me-1"></i>Ustawienia tortów
    </a>
</div>

<!-- Filters -->
<div class="card mb-4 bg-warning-subtle">
    <div class="card-body">
        <form id="filterForm" method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">Wszystkie</option>
                    <option value="pending" <?= ($_GET['status'] ?? '') == 'pending' ? 'selected' : '' ?>>Oczekujące</option>
                    <option value="confirmed" <?= ($_GET['status'] ?? '') == 'confirmed' ? 'selected' : '' ?>>Potwierdzone</option>
                    <option value="in_production" <?= ($_GET['status'] ?? '') == 'in_production' ? 'selected' : '' ?>>W produkcji</option>
                    <option value="ready" <?= ($_GET['status'] ?? '') == 'ready' ? 'selected' : '' ?>>Gotowe</option>
                    <option value="completed" <?= ($_GET['status'] ?? '') == 'completed' ? 'selected' : '' ?>>Zrealizowane</option>
                    <option value="cancelled" <?= ($_GET['status'] ?? '') == 'cancelled' ? 'selected' : '' ?>>Anulowane</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Data od</label>
                <input type="date" name="date_from" class="form-control" value="<?= $_GET['date_from'] ?? '' ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Data do</label>
                <input type="date" name="date_to" class="form-control" value="<?= $_GET['date_to'] ?? '' ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Na stronie</label>
                <select name="per_page" class="form-select">
                    <option value="10" <?= ($_GET['per_page'] ?? 20) == 10 ? 'selected' : '' ?>>10</option>
                    <option value="20" <?= ($_GET['per_page'] ?? 20) == 20 ? 'selected' : '' ?>>20</option>
                    <option value="50" <?= ($_GET['per_page'] ?? 20) == 50 ? 'selected' : '' ?>>50</option>
                    <option value="100" <?= ($_GET['per_page'] ?? 20) == 100 ? 'selected' : '' ?>>100</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">&nbsp;</label>
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-filter me-1"></i>Filtruj
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Orders Table -->
<div class="card shadow-sm">
    <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fas fa-birthday-cake me-2"></i>Lista zamówień
        </h5>
        <span id="totalCount" class="badge bg-light text-dark"></span>
    </div>
    <div class="card-body p-0 position-relative">
        <!-- Loading Overlay -->
        <div id="loadingOverlay" class="position-absolute top-0 start-0 w-100 h-100 d-none" style="background: rgba(255,255,255,0.8); z-index: 10;">
            <div class="d-flex justify-content-center align-items-center h-100">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Ładowanie...</span>
                </div>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover table-striped mb-0">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Klient</th>
                        <th>Odbiór</th>
                        <th>Tort</th>
                        <th>Status</th>
                        <th>Data utworzenia</th>
                        <th>Akcje</th>
                    </tr>
                </thead>
                <tbody id="ordersTableBody">
                    <!-- Orders will be loaded via AJAX -->
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer">
        <div class="d-flex justify-content-between align-items-center">
            <div id="paginationInfo" class="text-muted small"></div>
            <nav id="paginationNav">
                <ul class="pagination pagination-sm mb-0">
                    <!-- Pagination will be loaded via AJAX -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- Order Details Offcanvas -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="orderDetailsPanel" style="width: 600px;">
    <div class="offcanvas-header bg-primary text-white">
        <h5 class="offcanvas-title">
            <i class="fas fa-birthday-cake me-2"></i>Szczegóły zamówienia <span id="orderDetailId"></span>
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body p-0">
        <div id="orderDetailsContent">
            <div class="d-flex justify-content-center align-items-center" style="min-height: 400px;">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Ładowanie...</span>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.offcanvas-end {
    width: 600px !important;
    max-width: 90vw;
}
.order-detail-row {
    padding: 0.75rem 1rem;
    border-bottom: 1px solid #e9ecef;
}
.order-detail-row:last-child {
    border-bottom: none;
}
.order-detail-label {
    font-weight: 600;
    color: #6c757d;
    font-size: 0.875rem;
    text-transform: uppercase;
    margin-bottom: 0.25rem;
}
.order-detail-value {
    font-size: 1rem;
    color: #212529;
}
.order-section-header {
    background: #f8f9fa;
    padding: 0.75rem 1rem;
    font-weight: 600;
    border-bottom: 2px solid #dee2e6;
    position: sticky;
    top: 0;
    z-index: 1;
}

@media print {
    .print-hide, .offcanvas-header, .btn-close {
        display: none !important;
    }
    .offcanvas {
        position: static !important;
        width: 100% !important;
        height: auto !important;
        visibility: visible !important;
        transform: none !important;
    }
    #printableArea {
        max-width: 100%;
    }
}
</style>

<script>
// Print order details
function printOrderDetails() {
    window.print();
}

// AJAX Pagination
let currentPage = 1;
let currentFilters = {};

// Get URL parameters on page load
function getUrlParams() {
    const params = new URLSearchParams(window.location.search);
    return {
        status: params.get('status') || '',
        date_from: params.get('date_from') || '',
        date_to: params.get('date_to') || '',
        per_page: parseInt(params.get('per_page')) || 20,
        page: parseInt(params.get('page')) || 1
    };
}

// Update URL without page reload
function updateUrl(params) {
    const url = new URL(window.location);
    Object.keys(params).forEach(key => {
        if (params[key]) {
            url.searchParams.set(key, params[key]);
        } else {
            url.searchParams.delete(key);
        }
    });
    window.history.pushState({}, '', url);
}

// Fetch orders via AJAX
function fetchOrders(page = 1) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    const tbody = document.getElementById('ordersTableBody');
    
    // Show loading
    loadingOverlay.classList.remove('d-none');
    
    // Build query params
    const params = new URLSearchParams({
        ajax: '1',
        page: page,
        per_page: currentFilters.per_page || 20,
        status: currentFilters.status || '',
        date_from: currentFilters.date_from || '',
        date_to: currentFilters.date_to || ''
    });
    
    // Use absolute path from site root
    const baseUrl = window.location.pathname.split('/cake-orders')[0];
    const fetchUrl = baseUrl + '/cake-orders?' + params.toString();
    
    fetch(fetchUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            // Render orders
            renderOrders(data.orders);
            
            // Render pagination
            renderPagination(data.pagination);
            
            // Update current page
            currentPage = page;
            
            // Update URL
            updateUrl({
                page: page,
                per_page: currentFilters.per_page,
                status: currentFilters.status,
                date_from: currentFilters.date_from,
                date_to: currentFilters.date_to
            });
            
            // Hide loading
            loadingOverlay.classList.add('d-none');
        })
        .catch(error => {
            console.error('Error fetching orders:', error);
            tbody.innerHTML = '<tr><td colspan="7" class="text-center text-danger py-4">Błąd ładowania danych</td></tr>';
            loadingOverlay.classList.add('d-none');
        });
}

// Render orders in table
function renderOrders(orders) {
    const tbody = document.getElementById('ordersTableBody');
    
    if (orders.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="text-center text-muted py-4">
                    <i class="fas fa-inbox fa-3x mb-3 d-block"></i>
                    Brak zamówień
                </td>
            </tr>
        `;
        return;
    }
    
    const statusBadges = {
        'pending': 'warning',
        'confirmed': 'info',
        'in_production': 'primary',
        'ready': 'success',
        'completed': 'secondary',
        'cancelled': 'danger'
    };
    
    const statusNames = {
        'pending': 'Oczekujące',
        'confirmed': 'Potwierdzone',
        'in_production': 'W produkcji',
        'ready': 'Gotowe',
        'completed': 'Zrealizowane',
        'cancelled': 'Anulowane'
    };
    
    // Get base URL
    const baseUrl = window.location.pathname.split('/cake-orders')[0];
    
    tbody.innerHTML = orders.map(order => {
        const badge = statusBadges[order.status] || 'secondary';
        const statusName = statusNames[order.status] || order.status;
        const pickupDate = new Date(order.pickup_date).toLocaleDateString('pl-PL');
        const createdAt = new Date(order.created_at).toLocaleString('pl-PL');
        
        return `
            <tr>
                <td><strong>#${order.id}</strong></td>
                <td>
                    ${escapeHtml(order.customer_name)}<br>
                    <small class="text-muted">${escapeHtml(order.customer_phone)}</small>
                </td>
                <td>
                    ${pickupDate}<br>
                    <small class="text-muted">${order.pickup_time || '-'}</small>
                </td>
                <td>
                    <small>
                        ${escapeHtml(order.flavor_name || order.flavor_custom || '-')}<br>
                        ${escapeHtml(order.size_name || order.size_custom || '-')}
                    </small>
                </td>
                <td>
                    <span class="badge bg-${badge}">${statusName}</span>
                </td>
                <td>
                    <small>${createdAt}</small>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button onclick="viewOrderDetails(${order.id}); return false;" class="btn btn-info" title="Podgląd">
                            <i class="fas fa-eye"></i>
                        </button>
                        <a href="${baseUrl}/cake-orders/edit/${order.id}" class="btn btn-warning" title="Edytuj">
                            <i class="fas fa-edit"></i>
                        </a>
                        <a href="${baseUrl}/cake-orders/delete/${order.id}" 
                           class="btn btn-danger" 
                           title="Usuń"
                           onclick="return confirm('Czy na pewno usunąć to zamówienie?')">
                            <i class="fas fa-trash"></i>
                        </a>
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

// Render pagination controls
function renderPagination(pagination) {
    const paginationInfo = document.getElementById('paginationInfo');
    const paginationNav = document.getElementById('paginationNav').querySelector('.pagination');
    const totalCount = document.getElementById('totalCount');
    
    // Update total count badge
    totalCount.textContent = `Wszystkich: ${pagination.total_count}`;
    
    // Update info text
    const start = ((pagination.current_page - 1) * pagination.per_page) + 1;
    const end = Math.min(pagination.current_page * pagination.per_page, pagination.total_count);
    paginationInfo.textContent = `Wyświetlanie ${start}-${end} z ${pagination.total_count}`;
    
    // Build pagination buttons
    let paginationHtml = '';
    
    // Previous button
    paginationHtml += `
        <li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${pagination.current_page - 1}); return false;">
                <i class="fas fa-chevron-left"></i>
            </a>
        </li>
    `;
    
    // Page numbers
    const maxButtons = 5;
    let startPage = Math.max(1, pagination.current_page - Math.floor(maxButtons / 2));
    let endPage = Math.min(pagination.total_pages, startPage + maxButtons - 1);
    
    if (endPage - startPage < maxButtons - 1) {
        startPage = Math.max(1, endPage - maxButtons + 1);
    }
    
    // First page
    if (startPage > 1) {
        paginationHtml += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(1); return false;">1</a>
            </li>
        `;
        if (startPage > 2) {
            paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
    }
    
    // Page buttons
    for (let i = startPage; i <= endPage; i++) {
        paginationHtml += `
            <li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changePage(${i}); return false;">${i}</a>
            </li>
        `;
    }
    
    // Last page
    if (endPage < pagination.total_pages) {
        if (endPage < pagination.total_pages - 1) {
            paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
        paginationHtml += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${pagination.total_pages}); return false;">${pagination.total_pages}</a>
            </li>
        `;
    }
    
    // Next button
    paginationHtml += `
        <li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${pagination.current_page + 1}); return false;">
                <i class="fas fa-chevron-right"></i>
            </a>
        </li>
    `;
    
    paginationNav.innerHTML = paginationHtml;
}

// Change page handler
function changePage(page) {
    if (page < 1) return;
    fetchOrders(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// HTML escape helper
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// View order details in offcanvas
function viewOrderDetails(orderId) {
    const offcanvas = new bootstrap.Offcanvas(document.getElementById('orderDetailsPanel'));
    const content = document.getElementById('orderDetailsContent');
    const titleId = document.getElementById('orderDetailId');
    
    // Update title
    titleId.textContent = `#${orderId}`;
    
    // Show loading
    content.innerHTML = `
        <div class="d-flex justify-content-center align-items-center" style="min-height: 400px;">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Ładowanie...</span>
            </div>
        </div>
    `;
    
    // Show offcanvas
    offcanvas.show();
    
    // Build proper URL - use current URL structure
    const currentPath = window.location.pathname;
    let fetchUrl;
    
    if (currentPath.includes('/samanta_crm/public')) {
        fetchUrl = `/samanta_crm/public/cake-orders/${orderId}?ajax=1`;
    } else if (currentPath.includes('/samanta_crm')) {
        fetchUrl = `/samanta_crm/cake-orders/${orderId}?ajax=1`;
    } else {
        fetchUrl = `/cake-orders/${orderId}?ajax=1`;
    }
    
    fetch(fetchUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(order => {
            renderOrderDetails(order);
        })
        .catch(error => {
            console.error('Error fetching order details:', error);
            content.innerHTML = `
                <div class="alert alert-danger m-3">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Błąd ładowania szczegółów zamówienia
                </div>
            `;
        });
}

// Render order details
function renderOrderDetails(order) {
    const content = document.getElementById('orderDetailsContent');
    
    const statusBadges = {
        'pending': 'warning',
        'confirmed': 'info',
        'in_production': 'primary',
        'ready': 'success',
        'completed': 'secondary',
        'cancelled': 'danger'
    };
    
    const statusNames = {
        'pending': 'Oczekujące',
        'confirmed': 'Potwierdzone',
        'in_production': 'W produkcji',
        'ready': 'Gotowe',
        'completed': 'Zrealizowane',
        'cancelled': 'Anulowane'
    };
    
    const badge = statusBadges[order.status] || 'secondary';
    const statusName = statusNames[order.status] || order.status;
    const baseUrl = window.location.pathname.split('/cake-orders')[0];
    
    const pickupDate = new Date(order.pickup_date).toLocaleDateString('pl-PL', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
    });
    const createdDate = new Date(order.created_at).toLocaleDateString('pl-PL', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    content.innerHTML = `
        <div id="printableArea">
            <!-- Invoice Header -->
            <div class="bg-primary text-white p-4">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h3 class="mb-1">ZAMÓWIENIE TORTU</h3>
                        <p class="mb-0 opacity-75">Nr zamówienia: #${order.id}</p>
                    </div>
                    <div class="text-end">
                        <div class="badge bg-${badge} fs-6 px-3 py-2">${statusName}</div>
                        <div class="mt-2 small opacity-75">Data: ${createdDate}</div>
                    </div>
                </div>
            </div>
            
            <!-- Customer & Pickup Info -->
            <div class="row g-0 border-bottom">
                <div class="col-md-6 p-4 border-end">
                    <h6 class="text-uppercase text-muted small fw-bold mb-3">
                        <i class="fas fa-user me-2"></i>Dane klienta
                    </h6>
                    <div class="mb-2">
                        <strong>${escapeHtml(order.customer_name)}</strong>
                    </div>
                    <div class="text-muted mb-1">
                        <i class="fas fa-phone me-2"></i>
                        <a href="tel:${escapeHtml(order.customer_phone)}" class="text-decoration-none">
                            ${escapeHtml(order.customer_phone)}
                        </a>
                    </div>
                    ${order.customer_email ? `
                    <div class="text-muted">
                        <i class="fas fa-envelope me-2"></i>
                        <a href="mailto:${escapeHtml(order.customer_email)}" class="text-decoration-none">
                            ${escapeHtml(order.customer_email)}
                        </a>
                    </div>
                    ` : ''}
                </div>
                <div class="col-md-6 p-4">
                    <h6 class="text-uppercase text-muted small fw-bold mb-3">
                        <i class="fas fa-calendar-check me-2"></i>Odbiór zamówienia
                    </h6>
                    <div class="mb-2">
                        <i class="fas fa-calendar me-2 text-primary"></i>
                        <strong>${pickupDate}</strong>
                    </div>
                    <div class="mb-2">
                        <i class="fas fa-clock me-2 text-primary"></i>
                        <strong>${order.pickup_time || 'Nie określono'}</strong>
                    </div>
                    ${order.pickup_location_name || order.pickup_location_custom ? `
                    <div>
                        <i class="fas fa-map-marker-alt me-2 text-primary"></i>
                        ${escapeHtml(order.pickup_location_name || order.pickup_location_custom)}
                    </div>
                    ` : ''}
                </div>
            </div>
            
            <!-- Cake Specification -->
            <div class="p-4 border-bottom bg-light">
                <h6 class="text-uppercase text-muted small fw-bold mb-3">
                    <i class="fas fa-birthday-cake me-2"></i>Specyfikacja tortu
                </h6>
                
                <table class="table table-sm table-borderless mb-0">
                    <tbody>
                        <tr>
                            <td width="150" class="text-muted">Smak:</td>
                            <td><strong>${escapeHtml(order.flavor_name || order.flavor_custom || '-')}</strong></td>
                        </tr>
                        <tr>
                            <td class="text-muted">Rozmiar:</td>
                            <td><strong>${escapeHtml(order.size_name || order.size_custom || '-')}</strong></td>
                        </tr>
                        ${order.cake_type_name || order.cake_type_custom ? `
                        <tr>
                            <td class="text-muted">Rodzaj:</td>
                            <td>${escapeHtml(order.cake_type_name || order.cake_type_custom)}</td>
                        </tr>
                        ` : ''}
                        ${order.inscription ? `
                        <tr>
                            <td class="text-muted">Napis na torcie:</td>
                            <td><em class="text-primary">"${escapeHtml(order.inscription)}"</em></td>
                        </tr>
                        ` : ''}
                        ${order.has_candles ? `
                        <tr>
                            <td class="text-muted">Świeczki:</td>
                            <td>${order.candles_count || 'Tak'}</td>
                        </tr>
                        ` : ''}
                        ${order.has_number_candle ? `
                        <tr>
                            <td class="text-muted">Świeczka cyfra:</td>
                            <td>${order.number_candle_value || 'Tak'}</td>
                        </tr>
                        ` : ''}
                        ${order.has_wafer_photo ? `
                        <tr>
                            <td class="text-muted">Zdjęcie na opłatku:</td>
                            <td>Tak</td>
                        </tr>
                        ` : ''}
                        ${order.has_figurine ? `
                        <tr>
                            <td class="text-muted">Figurka:</td>
                            <td>${escapeHtml(order.figurine_description || 'Tak')}</td>
                        </tr>
                        ` : ''}
                    </tbody>
                </table>
            </div>
            
            ${order.card_text ? `
            <div class="p-4 border-bottom">
                <h6 class="text-uppercase text-muted small fw-bold mb-2">
                    <i class="fas fa-envelope me-2"></i>Tekst kartki
                </h6>
                <p class="mb-0 fst-italic">${escapeHtml(order.card_text)}</p>
            </div>
            ` : ''}
            
            ${order.cake_image ? `
            <div class="p-4 border-bottom text-center">
                <h6 class="text-uppercase text-muted small fw-bold mb-3">
                    <i class="fas fa-image me-2"></i>Wzór tortu
                </h6>
                <img src="${escapeHtml(order.cake_image)}" alt="Tort" class="img-fluid rounded shadow-sm" style="max-height: 300px;">
            </div>
            ` : ''}
            
            ${order.wafer_image ? `
            <div class="p-4 border-bottom text-center">
                <h6 class="text-uppercase text-muted small fw-bold mb-3">
                    <i class="fas fa-image me-2"></i>Zdjęcie na opłatek
                </h6>
                <img src="${escapeHtml(order.wafer_image)}" alt="Opłatek" class="img-fluid rounded shadow-sm" style="max-height: 300px;">
            </div>
            ` : ''}
            
            ${order.notes ? `
            <div class="p-4 border-bottom bg-warning-subtle">
                <h6 class="text-uppercase text-muted small fw-bold mb-2">
                    <i class="fas fa-sticky-note me-2"></i>Notatki wewnętrzne
                </h6>
                <p class="mb-0">${escapeHtml(order.notes)}</p>
            </div>
            ` : ''}
            
            <!-- Price -->
            ${order.total_price ? `
            <div class="p-4 bg-success-subtle">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 text-uppercase">Cena całkowita:</h5>
                    <h3 class="mb-0 text-success fw-bold">${parseFloat(order.total_price).toFixed(2)} PLN</h3>
                </div>
            </div>
            ` : ''}
        </div>
        
        <!-- Action Buttons -->
        <div class="p-3 border-top bg-light print-hide">
            <div class="d-grid gap-2">
                <button onclick="printOrderDetails()" class="btn btn-primary">
                    <i class="fas fa-print me-2"></i>Drukuj zamówienie
                </button>
                <a href="${baseUrl}/cake-orders/edit/${order.id}" class="btn btn-warning">
                    <i class="fas fa-edit me-2"></i>Edytuj zamówienie
                </a>
                <a href="${baseUrl}/cake-orders/${order.id}" class="btn btn-outline-secondary">
                    <i class="fas fa-external-link-alt me-2"></i>Otwórz pełną stronę
                </a>
            </div>
        </div>
    `;
}

// Filter form submit handler
document.getElementById('filterForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    // Get form values
    const formData = new FormData(this);
    currentFilters = {
        status: formData.get('status'),
        date_from: formData.get('date_from'),
        date_to: formData.get('date_to'),
        per_page: parseInt(formData.get('per_page')) || 20
    };
    
    // Fetch with new filters from page 1
    fetchOrders(1);
});

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Get initial params from URL
    const urlParams = getUrlParams();
    currentFilters = {
        status: urlParams.status,
        date_from: urlParams.date_from,
        date_to: urlParams.date_to,
        per_page: urlParams.per_page
    };
    
    // Fetch initial data
    fetchOrders(urlParams.page);
});
</script>

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