@extends('admin.master')

@section('main')
<div class="container-fluid mt-4">
    <div class="card shadow-lg rounded-3">
        <div class="card-header bg-dark text-white rounded-top">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <h3 class="mb-0">📦 Advanced Orders Management</h3>
                <div class="col-md-5">
                    <div class="input-group">
                        <input type="text" id="globalSearch" class="form-control rounded-start" 
                               placeholder="Search across all fields...">
                        <button class="btn btn-outline-light rounded-end" type="button" id="resetAllFilters">
                            <i class="bi bi-arrow-counterclockwise"></i> Reset
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card-body p-4">
            <!-- Column Filters Row -->
            <div class="row g-3 mb-4">
                <div class="col-md-2">
                    <label class="form-label small fw-bold">Order ID</label>
                    <input type="text" class="form-control filter-input" data-column="0" placeholder="Filter ID...">
                </div>
               
              
             
                <div class="col-md-2">
                    <label class="form-label small fw-bold">From Date</label>
                    <input type="date" class="form-control filter-date" data-column="12" data-filter="from">
                </div>
                <div class="col-md-2">
                    <label class="form-label small fw-bold">To Date</label>
                    <input type="date" class="form-control filter-date" data-column="12" data-filter="to">
                </div>
            </div>

            @if($orders->count() > 0)
            <div class="table-responsive" style="max-height: 65vh;">
                <table class="table table-bordered table-hover align-middle bg-white mb-0" id="ordersTable">
                    <thead class="table-light sticky-top" style="top: -1px;">
                        <tr>
                            <th width="100">Order ID</th>
                            <th width="200">Products</th>
                            
                            <th width="100">Price</th>
                        
                            <th width="150">Email</th>
                            <th width="200">Address</th>
                            <th width="100">Phone</th>
                            
                        
                        
                            <th width="120">Date</th>
            
                        </tr>
                    </thead>
                    <tbody id="ordersTableBody">
                        @foreach($orders as $order)
                        <tr class="order-row"
                            data-id="{{ $order->id }}"
                            data-name="{{ strtolower($order->name) }}"
                            data-email="{{ strtolower($order->email) }}"
                            data-address="{{ strtolower($order->address) }}"
                            data-phone="{{ $order->number }}"
                        
                            data-method="{{ strtolower($order->payment_status ?? 'cod') }}"
                            data-date="{{ $order->created_at->format('Y-m-d') }}"
                            data-city="{{ strtolower($order->city) }}"
                            data-state="{{ strtolower($order->state) }}"
                            data-zip="{{ $order->zip }}">
                            <td>#{{ $order->id }}</td>

  <td>
    <div class="order-items">
        @foreach($order->items as $item)
            <div class="order-item">
                <span class="product-name">{{ $item->product_name }}</span>
                <span class="quantity-badge">{{ $item->quantity }}</span>
            </div>
        @endforeach
    </div>
</td>
                        
                          
                            <td>
                               {{ $order->amount }} 
                            </td>
                         
                            <td>{{ $order->email }}</td>
                            <td>
                                {{ $order->address }}, 
                                {{ $order->city }}, 
                                {{ $order->amount }} 
                                {{ $order->zip }}
                            </td>
                            <td>{{ $order->number }}</td>
                       
                          
                        
                            <td>{{ $order->created_at->format('d M Y') }}</td>
                            <td>
                               
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            @else
                <div class="text-center py-5 text-muted bg-light rounded-3">
                    <i class="bi bi-cart-x display-4"></i>
                    <h4 class="mt-3">No orders found</h4>
                </div>
            @endif

            <div id="noResultsMessage" class="text-center py-5 bg-light rounded-3" style="display: none;">
                <i class="bi bi-search display-4 text-muted"></i>
                <h4 class="mt-3 text-muted">No orders match your filters</h4>
                <button class="btn btn-outline-dark mt-3" id="resetFiltersBtn">
                    <i class="bi bi-arrow-counterclockwise"></i> Reset All Filters
                </button>
            </div>
        </div>
    </div>
</div>

<style>
    /* Your existing styles remain the same */
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Toastr if not already done
        if (typeof toastr === 'undefined') {
            console.warn('Toastr not loaded - make sure to include toastr.js');
        }

        const globalSearch = document.getElementById('globalSearch');
        const filterInputs = document.querySelectorAll('.filter-input');
        const filterSelects = document.querySelectorAll('.filter-select');
        const filterDates = document.querySelectorAll('.filter-date');
        const resetBtn = document.getElementById('resetAllFilters');
        const resetFiltersBtn = document.getElementById('resetFiltersBtn');
        const orderRows = document.querySelectorAll('.order-row');
        const noResultsMessage = document.getElementById('noResultsMessage');
        const defaultNoOrders = document.querySelector('.text-center.py-5');
        const ordersTableBody = document.getElementById('ordersTableBody');
    
        // Initialize filters object
        let filters = {
            global: '',
            columns: Array(13).fill(''), // Match number of columns
            dateRange: { from: '', to: '' }
        };
    
        // Improved filtering function
        function applyFilters() {
            let hasVisibleRows = false;
            const searchText = filters.global.toLowerCase();
            
            orderRows.forEach(row => {
                let shouldShow = true;
                
                // Apply global search
                if (searchText) {
                    const rowText = row.textContent.toLowerCase();
                    shouldShow = rowText.includes(searchText);
                }
                
                // Apply column filters
                for (let i = 0; i < filters.columns.length && shouldShow; i++) {
                    if (filters.columns[i]) {
                        const filterValue = filters.columns[i].toLowerCase();
                        const cell = row.children[i];
                        if (cell) {
                            const cellText = cell.textContent.toLowerCase();
                            shouldShow = cellText.includes(filterValue);
                        }
                    }
                }
                
                // Apply date range filter
                if (shouldShow && (filters.dateRange.from || filters.dateRange.to)) {
                    const rowDateStr = row.dataset.date;
                    if (rowDateStr) {
                        const rowDate = new Date(rowDateStr);
                        const fromDate = filters.dateRange.from ? new Date(filters.dateRange.from) : null;
                        const toDate = filters.dateRange.to ? new Date(filters.dateRange.to) : null;
                        
                        if (fromDate && rowDate < fromDate) shouldShow = false;
                        if (toDate && rowDate > toDate) shouldShow = false;
                    }
                }
                
                // Set row visibility
                row.style.display = shouldShow ? '' : 'none';
                if (shouldShow) hasVisibleRows = true;
            });
            
            // Toggle no results message
            const hasActiveFilters = filters.global || 
                                   filters.columns.some(f => f) || 
                                   filters.dateRange.from || 
                                   filters.dateRange.to;
            
            noResultsMessage.style.display = (hasActiveFilters && !hasVisibleRows) ? 'block' : 'none';
            
            if (defaultNoOrders) {
                defaultNoOrders.style.display = hasVisibleRows ? 'none' : '';
            }
            
            ordersTableBody.style.display = hasVisibleRows ? '' : 'none';
        }
    
        // Event listeners for filters
        globalSearch.addEventListener('input', function() {
            filters.global = this.value.trim();
            applyFilters();
        });
    
        filterInputs.forEach(input => {
            input.addEventListener('input', function() {
                const columnIndex = parseInt(this.dataset.column);
                filters.columns[columnIndex] = this.value.trim();
                applyFilters();
            });
        });
    
        filterSelects.forEach(select => {
            select.addEventListener('change', function() {
                const columnIndex = parseInt(this.dataset.column);
                filters.columns[columnIndex] = this.value;
                applyFilters();
            });
        });
    
        filterDates.forEach(dateInput => {
            dateInput.addEventListener('change', function() {
                if (this.dataset.filter === 'from') {
                    filters.dateRange.from = this.value;
                } else {
                    filters.dateRange.to = this.value;
                }
                applyFilters();
            });
        });
    
        // Reset all filters
        function resetAllFilters() {
            filters = {
                global: '',
                columns: Array(13).fill(''),
                dateRange: { from: '', to: '' }
            };
            
            globalSearch.value = '';
            filterInputs.forEach(input => input.value = '');
            filterSelects.forEach(select => select.value = '');
            filterDates.forEach(dateInput => dateInput.value = '');
            
            applyFilters();
        }
    
        resetBtn.addEventListener('click', resetAllFilters);
        resetFiltersBtn.addEventListener('click', resetAllFilters);

        // Status update with better error handling
        document.querySelectorAll('.status-select').forEach(select => {
            select.addEventListener('change', async function() {
                const orderId = this.dataset.orderId;
                const newStatus = this.value;
                const previousValue = this.dataset.previousValue || this.value;
                
                try {
                    const response = await fetch(`/admin/orders/${orderId}/status`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({ status: newStatus })
                    });

                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || 'Failed to update status');
                    }

                    if (data.success) {
                        toastr.success('Order status updated successfully');
                        this.dataset.previousValue = newStatus;
                        // Update the data-status attribute for filtering
                        this.closest('tr').dataset.status = newStatus.toLowerCase();
                    } else {
                        throw new Error(data.message || 'Update failed');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    toastr.error(error.message || 'An error occurred');
                    this.value = previousValue;
                }
            });
        });

        // Payment status update
        document.querySelectorAll('.payment-status').forEach(select => {
            select.addEventListener('change', async function() {
                const orderId = this.dataset.orderId;
                const newStatus = this.value;
                const previousValue = this.dataset.previousValue || this.value;
                
                try {
                    const response = await fetch(`/admin/orders/${orderId}/payment-status`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({ payment_status: newStatus })
                    });

                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || 'Failed to update payment status');
                    }

                    if (data.success) {
                        toastr.success('Payment status updated successfully');
                        this.dataset.previousValue = newStatus;
                        // Update the data-method attribute for filtering
                        this.closest('tr').dataset.method = newStatus.toLowerCase();
                    } else {
                        throw new Error(data.message || 'Update failed');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    toastr.error(error.message || 'An error occurred');
                    this.value = previousValue;
                }
            });
        });

        // Send invoice
        document.querySelectorAll('.send-invoice').forEach(button => {
            button.addEventListener('click', async function() {
                const orderId = this.dataset.orderId;
                const btn = this;
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-hourglass"></i>';
                
                try {
                    const response = await fetch(`/admin/orders/${orderId}/send-invoice`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        }
                    });

                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || 'Failed to send invoice');
                    }

                    if (data.success) {
                        toastr.success('Invoice sent successfully');
                    } else {
                        throw new Error(data.message || 'Sending failed');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    toastr.error(error.message || 'An error occurred');
                } finally {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="bi bi-envelope"></i>';
                }
            });
        });
    });
</script>
@endsection