<!-- Advanced Filtering and Sorting Interface -->
<div class="advanced-filters-container" id="advancedFiltersContainer">
    <!-- Filter Header -->
    <div class="filter-header d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">
            <span>🔍</span>
            Advanced Filters & Search
        </h5>
        <div class="filter-actions">
            <button type="button" class="btn btn-sm btn-outline-primary" id="saveFilterPreset">
                <span>💾</span> Save Preset
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" id="loadFilterPreset">
                <span>📂</span> Load Preset
            </button>
            <button type="button" class="btn btn-sm btn-outline-danger" id="clearAllFilters">
                <span>✕</span> Clear All
            </button>
        </div>
    </div>

    <!-- Filter Presets -->
    <div class="filter-presets mb-3" id="filterPresets" style="display: none;">
        <div class="card">
            <div class="card-body">
                <h6 class="card-title">Filter Presets</h6>
                <div class="row">
                    <div class="col-md-8">
                        <select class="form-select" id="presetSelect">
                            <option value="">Select a preset...</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <div class="btn-group w-100">
                            <button type="button" class="btn btn-primary" id="applyPreset">Apply</button>
                            <button type="button" class="btn btn-outline-danger" id="deletePreset">Delete</button>
                        </div>
                    </div>
                </div>
                <div class="mt-2">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="setAsDefault">
                        <label class="form-check-label" for="setAsDefault">
                            Set as default for this report type
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Advanced Search -->
    <div class="advanced-search mb-3">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <span>🔍</span>
                    Advanced Search
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <label for="searchQuery" class="form-label">Search Query</label>
                        <input type="text" class="form-control" id="searchQuery" 
                               placeholder="Enter search terms...">
                    </div>
                    <div class="col-md-3">
                        <label for="searchOperator" class="form-label">Operator</label>
                        <select class="form-select" id="searchOperator">
                            <option value="OR">OR (any field)</option>
                            <option value="AND">AND (all fields)</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Search In</label>
                        <div class="search-fields" id="searchFields">
                            <!-- Dynamic search fields will be populated here -->
                        </div>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-primary" id="performSearch">
                            <span>🔍</span> Search
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="saveSearch">
                            <span>🔖</span> Save Search
                        </button>
                        <button type="button" class="btn btn-outline-info" id="loadSavedSearch">
                            <i class="fas fa-history"></i> Load Saved
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Criteria -->
    <div class="filter-criteria">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <span>🎚️</span>
                    Filter Criteria
                </h6>
            </div>
            <div class="card-body">
                <div class="row" id="filterCriteriaContainer">
                    <!-- Dynamic filter fields will be populated here -->
                </div>
                <div class="row mt-3">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-success" id="applyFilters">
                            <span>✓</span> Apply Filters
                        </button>
                        <button type="button" class="btn btn-outline-warning" id="resetFilters">
                            <span>↶</span> Reset
                        </button>
                        <span class="ms-3 text-muted" id="filterSummary">No filters applied</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Sorting Options -->
    <div class="sorting-options mt-3">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-sort"></i>
                    Sorting Options
                </h6>
            </div>
            <div class="card-body">
                <div id="sortingContainer">
                    <div class="sort-row row mb-2">
                        <div class="col-md-5">
                            <select class="form-select sort-field">
                                <option value="">Select field to sort by...</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select sort-direction">
                                <option value="asc">Ascending</option>
                                <option value="desc">Descending</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-outline-success add-sort-field">
                                <span>+</span>
                            </button>
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-outline-danger remove-sort-field" disabled>
                                <span>−</span>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-primary" id="applySorting">
                            <i class="fas fa-sort"></i> Apply Sorting
                        </button>
                        <button type="button" class="btn btn-outline-secondary" id="clearSorting">
                            <span>✕</span> Clear Sorting
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Results Summary -->
    <div class="filter-results mt-3" id="filterResults" style="display: none;">
        <div class="alert alert-info">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <span>ℹ️</span>
                    <span id="resultsCount">0</span> results found
                    <span class="ms-2 text-muted" id="appliedFiltersText"></span>
                </div>
                <button type="button" class="btn btn-sm btn-outline-primary" id="exportFiltered">
                    <span>⬇️</span> Export Filtered Results
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Save Filter Preset Modal -->
<div class="modal fade" id="savePresetModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Save Filter Preset</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="presetName" class="form-label">Preset Name</label>
                    <input type="text" class="form-control" id="presetName" 
                           placeholder="Enter preset name...">
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="makeDefault">
                    <label class="form-check-label" for="makeDefault">
                        Set as default preset
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="sharePreset">
                    <label class="form-check-label" for="sharePreset">
                        Share with other users
                    </label>
                </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-primary" id="confirmSavePreset">Save Preset</button>
            </div>
        </div>
    </div>
</div>

<!-- Save Search Modal -->
<div class="modal fade" id="saveSearchModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Save Search</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="searchName" class="form-label">Search Name</label>
                    <input type="text" class="form-control" id="searchName" 
                           placeholder="Enter search name...">
                </div>
                <div class="mb-3">
                    <label class="form-label">Search Summary</label>
                    <div class="form-control-plaintext" id="searchSummary"></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-primary" id="confirmSaveSearch">Save Search</button>
            </div>
        </div>
    </div>
</div>

<!-- Load Saved Search Modal -->
<div class="modal fade" id="loadSearchModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Load Saved Search</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Criteria</th>
                                <th>Results</th>
                                <th>Last Used</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="savedSearchesList">
                            <!-- Saved searches will be populated here -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<style>
.advanced-filters-container {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.filter-header {
    border-bottom: 2px solid #dee2e6;
    padding-bottom: 10px;
}

.sort-row {
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 10px;
    background: white;
}

.search-fields {
    max-height: 120px;
    overflow-y: auto;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 8px;
}

.search-fields .form-check {
    margin-bottom: 5px;
}

.filter-criteria .row > div {
    margin-bottom: 15px;
}

.btn-group .btn {
    border-radius: 0;
}

.btn-group .btn:first-child {
    border-top-left-radius: 0.375rem;
    border-bottom-left-radius: 0.375rem;
}

.btn-group .btn:last-child {
    border-top-right-radius: 0.375rem;
    border-bottom-right-radius: 0.375rem;
}

.alert-info {
    border-left: 4px solid #0dcaf0;
}

.modal-body .form-control-plaintext {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 8px 12px;
    min-height: 60px;
}

@media (max-width: 768px) {
    .advanced-filters-container {
        padding: 15px;
    }
    
    .filter-actions {
        flex-direction: column;
        gap: 5px;
    }
    
    .filter-actions .btn {
        width: 100%;
    }
}
</style>

<script>
class AdvancedFilteringSystem {
    constructor(reportType, filterableFields, sortableFields) {
        this.reportType = reportType;
        this.filterableFields = filterableFields;
        this.sortableFields = sortableFields;
        this.currentFilters = {};
        this.currentSort = [];
        this.currentSearch = {};
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.populateFilterFields();
        this.populateSortFields();
        this.populateSearchFields();
        this.loadPersistentSettings();
        this.loadFilterPresets();
    }
    
    setupEventListeners() {
        // Filter actions
        $('#applyFilters').on('click', () => this.applyFilters());
        $('#resetFilters').on('click', () => this.resetFilters());
        $('#clearAllFilters').on('click', () => this.clearAllFilters());
        
        // Search actions
        $('#performSearch').on('click', () => this.performSearch());
        $('#saveSearch').on('click', () => this.showSaveSearchModal());
        $('#loadSavedSearch').on('click', () => this.showLoadSearchModal());
        
        // Sorting actions
        $('#applySorting').on('click', () => this.applySorting());
        $('#clearSorting').on('click', () => this.clearSorting());
        
        // Sort field management
        $(document).on('click', '.add-sort-field', (e) => this.addSortField(e));
        $(document).on('click', '.remove-sort-field', (e) => this.removeSortField(e));
        
        // Preset actions
        $('#saveFilterPreset').on('click', () => this.showSavePresetModal());
        $('#loadFilterPreset').on('click', () => this.togglePresetPanel());
        $('#applyPreset').on('click', () => this.applyPreset());
        $('#deletePreset').on('click', () => this.deletePreset());
        
        // Modal actions
        $('#confirmSavePreset').on('click', () => this.savePreset());
        $('#confirmSaveSearch').on('click', () => this.saveSearch());
        
        // Export filtered results
        $('#exportFiltered').on('click', () => this.exportFilteredResults());
        
        // Auto-save filters on change
        $(document).on('change', '.filter-field', () => this.autoSaveFilters());
    }
    
    populateFilterFields() {
        const container = $('#filterCriteriaContainer');
        container.empty();
        
        Object.entries(this.filterableFields).forEach(([fieldName, config]) => {
            const fieldHtml = this.createFilterField(fieldName, config);
            container.append(fieldHtml);
        });
    }
    
    createFilterField(fieldName, config) {
        const fieldId = `filter_${fieldName}`;
        let inputHtml = '';
        
        switch (config.type) {
            case 'text':
                inputHtml = `
                    <div class="input-group">
                        <select class="form-select" style="max-width: 120px;" id="${fieldId}_type">
                            <option value="contains">Contains</option>
                            <option value="exact">Exact</option>
                            <option value="starts_with">Starts with</option>
                            <option value="ends_with">Ends with</option>
                            <option value="regex">Regex</option>
                        </select>
                        <input type="text" class="form-control filter-field" 
                               id="${fieldId}" data-field="${fieldName}" 
                               placeholder="Enter ${config.label.toLowerCase()}...">
                    </div>
                `;
                break;
                
            case 'date_range':
                inputHtml = `
                    <div class="row">
                        <div class="col-6">
                            <input type="date" class="form-control filter-field" 
                                   id="${fieldId}_start" data-field="${fieldName}" 
                                   data-range="start" placeholder="Start date">
                        </div>
                        <div class="col-6">
                            <input type="date" class="form-control filter-field" 
                                   id="${fieldId}_end" data-field="${fieldName}" 
                                   data-range="end" placeholder="End date">
                        </div>
                    </div>
                `;
                break;
                
            case 'number_range':
                inputHtml = `
                    <div class="row">
                        <div class="col-6">
                            <input type="number" class="form-control filter-field" 
                                   id="${fieldId}_min" data-field="${fieldName}" 
                                   data-range="min" placeholder="Min value">
                        </div>
                        <div class="col-6">
                            <input type="number" class="form-control filter-field" 
                                   id="${fieldId}_max" data-field="${fieldName}" 
                                   data-range="max" placeholder="Max value">
                        </div>
                    </div>
                `;
                break;
                
            case 'select':
                inputHtml = `
                    <select class="form-select filter-field" id="${fieldId}" 
                            data-field="${fieldName}" multiple>
                        <option value="">Loading options...</option>
                    </select>
                `;
                // Load options asynchronously
                this.loadFilterOptions(fieldName, fieldId);
                break;
        }
        
        return `
            <div class="col-md-6 col-lg-4">
                <label for="${fieldId}" class="form-label">${config.label}</label>
                ${inputHtml}
            </div>
        `;
    }
    
    populateSortFields() {
        const sortSelect = $('.sort-field');
        sortSelect.empty().append('<option value="">Select field to sort by...</option>');
        
        this.sortableFields.forEach(field => {
            const label = this.filterableFields[field]?.label || field.replace('_', ' ');
            sortSelect.append(`<option value="${field}">${label}</option>`);
        });
    }
    
    populateSearchFields() {
        const container = $('#searchFields');
        container.empty();
        
        Object.entries(this.filterableFields).forEach(([fieldName, config]) => {
            if (config.type === 'text' || config.type === 'select') {
                container.append(`
                    <div class="form-check">
                        <input class="form-check-input search-field-checkbox" 
                               type="checkbox" value="${fieldName}" 
                               id="search_${fieldName}" checked>
                        <label class="form-check-label" for="search_${fieldName}">
                            ${config.label}
                        </label>
                    </div>
                `);
            }
        });
    }
    
    async loadFilterOptions(fieldName, fieldId) {
        try {
            const response = await fetch(`/api/filter-options/${this.reportType}/${fieldName}/`);
            const options = await response.json();
            
            const select = $(`#${fieldId}`);
            select.empty();
            
            options.forEach(option => {
                select.append(`<option value="${option.value}">${option.label}</option>`);
            });
            
        } catch (error) {
            console.error('Error loading filter options:', error);
        }
    }
    
    applyFilters() {
        this.currentFilters = this.collectFilterValues();
        this.updateFilterSummary();
        this.savePersistentSettings();
        this.refreshResults();
    }
    
    collectFilterValues() {
        const filters = {};
        
        $('.filter-field').each((index, element) => {
            const $element = $(element);
            const fieldName = $element.data('field');
            const value = $element.val();
            
            if (!value || value.length === 0) return;
            
            const fieldConfig = this.filterableFields[fieldName];
            
            if (fieldConfig.type === 'text') {
                const searchType = $(`#filter_${fieldName}_type`).val();
                filters[fieldName] = {
                    type: searchType,
                    value: value
                };
            } else if (fieldConfig.type === 'date_range' || fieldConfig.type === 'number_range') {
                const rangeType = $element.data('range');
                if (!filters[fieldName]) filters[fieldName] = {};
                filters[fieldName][rangeType] = value;
            } else {
                filters[fieldName] = Array.isArray(value) ? value : [value];
            }
        });
        
        return filters;
    }
    
    performSearch() {
        const query = $('#searchQuery').val();
        const operator = $('#searchOperator').val();
        const fields = $('.search-field-checkbox:checked').map((i, el) => $(el).val()).get();
        
        if (!query || fields.length === 0) {
            alert('Please enter a search query and select at least one field to search in.');
            return;
        }
        
        this.currentSearch = {
            query: query,
            operator: operator,
            fields: fields
        };
        
        this.refreshResults();
    }
    
    applySorting() {
        this.currentSort = [];
        
        $('.sort-row').each((index, row) => {
            const field = $(row).find('.sort-field').val();
            const direction = $(row).find('.sort-direction').val();
            
            if (field) {
                this.currentSort.push({
                    field: field,
                    direction: direction
                });
            }
        });
        
        this.savePersistentSettings();
        this.refreshResults();
    }
    
    addSortField(event) {
        const sortRow = $(event.target).closest('.sort-row');
        const newRow = sortRow.clone();
        
        // Clear values in new row
        newRow.find('select').val('');
        newRow.find('.remove-sort-field').prop('disabled', false);
        
        $('#sortingContainer').append(newRow);
        this.updateSortButtons();
    }
    
    removeSortField(event) {
        const sortRow = $(event.target).closest('.sort-row');
        sortRow.remove();
        this.updateSortButtons();
    }
    
    updateSortButtons() {
        const sortRows = $('.sort-row');
        sortRows.find('.remove-sort-field').prop('disabled', sortRows.length <= 1);
    }
    
    updateFilterSummary() {
        const summary = this.buildFilterSummary();
        $('#filterSummary').text(summary);
    }
    
    buildFilterSummary() {
        const parts = [];
        
        Object.entries(this.currentFilters).forEach(([field, value]) => {
            const config = this.filterableFields[field];
            if (!config) return;
            
            if (typeof value === 'object' && !Array.isArray(value)) {
                if (value.type && value.value) {
                    parts.push(`${config.label} ${value.type}: ${value.value}`);
                } else if (value.start || value.end || value.min !== undefined || value.max !== undefined) {
                    const start = value.start || value.min;
                    const end = value.end || value.max;
                    if (start && end) {
                        parts.push(`${config.label}: ${start} to ${end}`);
                    } else if (start) {
                        parts.push(`${config.label}: from ${start}`);
                    } else if (end) {
                        parts.push(`${config.label}: up to ${end}`);
                    }
                }
            } else if (Array.isArray(value)) {
                parts.push(`${config.label}: ${value.join(', ')}`);
            } else {
                parts.push(`${config.label}: ${value}`);
            }
        });
        
        if (this.currentSearch.query) {
            parts.push(`Search: "${this.currentSearch.query}" in ${this.currentSearch.fields.length} fields`);
        }
        
        return parts.length > 0 ? parts.join('; ') : 'No filters applied';
    }
    
    async refreshResults() {
        try {
            const params = new URLSearchParams({
                filters: JSON.stringify(this.currentFilters),
                search: JSON.stringify(this.currentSearch),
                sort: JSON.stringify(this.currentSort)
            });
            
            const response = await fetch(`/api/reports/${this.reportType}/filtered/?${params}`);
            const data = await response.json();
            
            // Update results count
            $('#resultsCount').text(data.count || 0);
            $('#appliedFiltersText').text(this.buildFilterSummary());
            $('#filterResults').show();
            
            // Trigger custom event for other components to update
            $(document).trigger('filtersApplied', [data]);
            
        } catch (error) {
            console.error('Error refreshing results:', error);
        }
    }
    
    resetFilters() {
        $('.filter-field').val('');
        this.currentFilters = {};
        this.updateFilterSummary();
        this.refreshResults();
    }
    
    clearAllFilters() {
        this.resetFilters();
        $('#searchQuery').val('');
        this.currentSearch = {};
        this.clearSorting();
    }
    
    clearSorting() {
        $('.sort-field').val('');
        $('.sort-direction').val('asc');
        this.currentSort = [];
        this.refreshResults();
    }
    
    showSavePresetModal() {
        if (Object.keys(this.currentFilters).length === 0) {
            alert('Please apply some filters before saving a preset.');
            return;
        }
        
        $('#savePresetModal').modal('show');
    }
    
    showSaveSearchModal() {
        if (!this.currentSearch.query) {
            alert('Please perform a search before saving.');
            return;
        }
        
        $('#searchSummary').text(this.buildFilterSummary());
        $('#saveSearchModal').modal('show');
    }
    
    showLoadSearchModal() {
        this.loadSavedSearches();
        $('#loadSearchModal').modal('show');
    }
    
    async savePreset() {
        const name = $('#presetName').val();
        const isDefault = $('#makeDefault').is(':checked');
        const isShared = $('#sharePreset').is(':checked');
        
        if (!name) {
            alert('Please enter a preset name.');
            return;
        }
        
        try {
            const response = await fetch('/api/filter-presets/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.getCsrfToken()
                },
                body: JSON.stringify({
                    name: name,
                    report_type: this.reportType,
                    filters: this.currentFilters,
                    is_default: isDefault,
                    is_shared: isShared
                })
            });
            
            if (response.ok) {
                $('#savePresetModal').modal('hide');
                $('#presetName').val('');
                this.loadFilterPresets();
                alert('Preset saved successfully!');
            } else {
                alert('Error saving preset. Please try again.');
            }
            
        } catch (error) {
            console.error('Error saving preset:', error);
            alert('Error saving preset. Please try again.');
        }
    }
    
    async saveSearch() {
        const name = $('#searchName').val();
        
        if (!name) {
            alert('Please enter a search name.');
            return;
        }
        
        try {
            const response = await fetch('/api/saved-searches/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.getCsrfToken()
                },
                body: JSON.stringify({
                    name: name,
                    report_type: this.reportType,
                    search_criteria: this.currentSearch
                })
            });
            
            if (response.ok) {
                $('#saveSearchModal').modal('hide');
                $('#searchName').val('');
                alert('Search saved successfully!');
            } else {
                alert('Error saving search. Please try again.');
            }
            
        } catch (error) {
            console.error('Error saving search:', error);
            alert('Error saving search. Please try again.');
        }
    }
    
    async loadFilterPresets() {
        try {
            const response = await fetch(`/api/filter-presets/${this.reportType}/`);
            const presets = await response.json();
            
            const select = $('#presetSelect');
            select.empty().append('<option value="">Select a preset...</option>');
            
            presets.forEach(preset => {
                const defaultText = preset.is_default ? ' (Default)' : '';
                select.append(`<option value="${preset.id}">${preset.name}${defaultText}</option>`);
            });
            
        } catch (error) {
            console.error('Error loading presets:', error);
        }
    }
    
    async loadSavedSearches() {
        try {
            const response = await fetch(`/api/saved-searches/${this.reportType}/`);
            const searches = await response.json();
            
            const tbody = $('#savedSearchesList');
            tbody.empty();
            
            searches.forEach(search => {
                tbody.append(`
                    <tr>
                        <td>${search.name}</td>
                        <td>${JSON.stringify(search.search_criteria)}</td>
                        <td>${search.result_count}</td>
                        <td>${new Date(search.last_executed).toLocaleDateString()}</td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="advancedFilters.loadSearch(${search.id})">
                                Load
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="advancedFilters.deleteSearch(${search.id})">
                                Delete
                            </button>
                        </td>
                    </tr>
                `);
            });
            
        } catch (error) {
            console.error('Error loading saved searches:', error);
        }
    }
    
    togglePresetPanel() {
        $('#filterPresets').toggle();
    }
    
    async applyPreset() {
        const presetId = $('#presetSelect').val();
        if (!presetId) return;
        
        try {
            const response = await fetch(`/api/filter-presets/${presetId}/`);
            const preset = await response.json();
            
            this.currentFilters = preset.filters;
            this.populateFilterFields();
            this.applyFilters();
            
        } catch (error) {
            console.error('Error applying preset:', error);
        }
    }
    
    savePersistentSettings() {
        const settings = {
            filters: this.currentFilters,
            sort: this.currentSort,
            search: this.currentSearch
        };
        
        localStorage.setItem(`advancedFilters_${this.reportType}`, JSON.stringify(settings));
    }
    
    loadPersistentSettings() {
        const saved = localStorage.getItem(`advancedFilters_${this.reportType}`);
        if (saved) {
            const settings = JSON.parse(saved);
            this.currentFilters = settings.filters || {};
            this.currentSort = settings.sort || [];
            this.currentSearch = settings.search || {};
            
            // Apply saved settings to UI
            this.restoreFilterValues();
            this.restoreSortValues();
            this.restoreSearchValues();
        }
    }
    
    restoreFilterValues() {
        Object.entries(this.currentFilters).forEach(([field, value]) => {
            const fieldConfig = this.filterableFields[field];
            if (!fieldConfig) return;
            
            if (fieldConfig.type === 'text' && typeof value === 'object') {
                $(`#filter_${field}_type`).val(value.type || 'contains');
                $(`#filter_${field}`).val(value.value || '');
            } else if (fieldConfig.type === 'date_range' || fieldConfig.type === 'number_range') {
                if (value.start || value.min !== undefined) {
                    $(`#filter_${field}_start, #filter_${field}_min`).val(value.start || value.min);
                }
                if (value.end || value.max !== undefined) {
                    $(`#filter_${field}_end, #filter_${field}_max`).val(value.end || value.max);
                }
            } else {
                $(`#filter_${field}`).val(value);
            }
        });
        
        this.updateFilterSummary();
    }
    
    restoreSortValues() {
        // Clear existing sort rows except first
        $('.sort-row:not(:first)').remove();
        
        this.currentSort.forEach((sort, index) => {
            if (index === 0) {
                $('.sort-field').first().val(sort.field);
                $('.sort-direction').first().val(sort.direction);
            } else {
                this.addSortField({target: $('.add-sort-field').first()});
                $('.sort-field').last().val(sort.field);
                $('.sort-direction').last().val(sort.direction);
            }
        });
    }
    
    restoreSearchValues() {
        if (this.currentSearch.query) {
            $('#searchQuery').val(this.currentSearch.query);
            $('#searchOperator').val(this.currentSearch.operator || 'OR');
            
            // Uncheck all, then check selected fields
            $('.search-field-checkbox').prop('checked', false);
            (this.currentSearch.fields || []).forEach(field => {
                $(`#search_${field}`).prop('checked', true);
            });
        }
    }
    
    autoSaveFilters() {
        // Debounce auto-save
        clearTimeout(this.autoSaveTimeout);
        this.autoSaveTimeout = setTimeout(() => {
            this.currentFilters = this.collectFilterValues();
            this.savePersistentSettings();
            this.updateFilterSummary();
        }, 1000);
    }
    
    async exportFilteredResults() {
        try {
            const params = new URLSearchParams({
                filters: JSON.stringify(this.currentFilters),
                search: JSON.stringify(this.currentSearch),
                sort: JSON.stringify(this.currentSort),
                export: 'excel'
            });
            
            window.location.href = `/api/reports/${this.reportType}/export/?${params}`;
            
        } catch (error) {
            console.error('Error exporting filtered results:', error);
        }
    }
    
    getCsrfToken() {
        return document.querySelector('[name=csrfmiddlewaretoken]').value;
    }
}

// Initialize when DOM is ready
$(document).ready(function() {
    // This will be initialized by the parent page with appropriate parameters
    window.initAdvancedFilters = function(reportType, filterableFields, sortableFields) {
        window.advancedFilters = new AdvancedFilteringSystem(reportType, filterableFields, sortableFields);
    };
});
</script>