<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Mariyappa Nadar Ricemill | Pending Orders Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    
    <style>
        /* Full-height layout and compact paddings */
        html, body, #wrapper, #content-wrapper, #content { height: 100%; }
        .container-fluid { padding: 8px 10px; }
        
        .order-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 15px;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        
        .order-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
            border-color: #4e73df;
        }
        
        .order-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 10px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .order-number {
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .order-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            background: rgba(255, 255, 255, 0.2);
        }
        
        .status-pending .order-header {
            background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);
        }
        
        .status-delivered .order-header {
            background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        }
        
        .status-cancelled .order-header {
            background: linear-gradient(135deg, #e74a3b 0%, #c0392b 100%);
        }
        
        .order-body {
            padding: 12px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        
        .order-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 6px;
            margin-bottom: 10px;
            flex-grow: 1;
        }
        
        .info-item {
            padding: 8px;
            background: #f8f9fc;
            border-radius: 6px;
            text-align: center;
        }
        
        .info-label {
            font-size: 0.7rem;
            color: #858796;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-weight: 600;
            color: #5a5c69;
            font-size: 0.85rem;
        }
        
        .customer-info {
            background: #e3f2fd;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 10px;
        }
        
        .customer-name {
            font-weight: 600;
            color: #1976d2;
            font-size: 0.9rem;
        }
        
        .customer-details {
            font-size: 0.75rem;
            color: #666;
        }
        
        .order-actions {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
            margin-top: auto;
            border-top: 1px solid #f8f9fc;
            padding-top: 10px;
        }
        
        .btn-action {
            flex: 1;
            min-width: 70px;
            padding: 6px 8px;
            border: none;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.15s ease-in-out;
            text-align: center;
        }
        
        .btn-deliver {
            background: #1cc88a;
            color: white;
        }
        
        .btn-deliver:hover {
            background: #17a673;
            transform: translateY(-1px);
        }
        
        .btn-edit {
            background: #f6c23e;
            color: white;
        }
        
        .btn-edit:hover {
            background: #dda20a;
            transform: translateY(-1px);
        }
        
        .btn-cancel {
            background: #e74a3b;
            color: white;
        }
        
        .btn-cancel:hover {
            background: #c0392b;
            transform: translateY(-1px);
        }
        
        .btn-view {
            background: #36b9cc;
            color: white;
        }
        
        .btn-view:hover {
            background: #2c9faf;
            transform: translateY(-1px);
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 6px 10px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            margin-bottom: 12px;
            font-size: 0.85rem;
        }
        
        .back-btn:hover {
            background: #545b62;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .filter-tabs {
            display: flex;
            background: white;
            border-radius: 8px;
            padding: 4px;
            margin-bottom: 12px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .filter-tab {
            flex: 1;
            padding: 8px 12px;
            background: none;
            border: none;
            border-radius: 6px;
            color: #858796;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.15s ease-in-out;
            font-size: 0.85rem;
            text-align: center;
        }
        
        .filter-tab.active {
            background: #4e73df;
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 2rem 1rem;
            color: #858796;
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #dddfeb;
        }
        
        /* Tighter grid gutters */
        .row > [class^="col-"] { padding-left: 6px; padding-right: 6px; }

        @media (max-width: 768px) {
            .order-info {
                grid-template-columns: 1fr;
                gap: 4px;
            }
            
            .order-actions {
                gap: 3px;
            }
            
            .btn-action {
                font-size: 0.65rem;
                padding: 4px 6px;
                flex: 1;
                min-width: 60px;
            }
            
            .page-header {
                padding: 10px 12px;
            }
            
            .filter-tab {
                padding: 6px 8px;
                font-size: 0.8rem;
            }
            
            .order-header {
                padding: 8px 10px;
            }
            
            .order-body {
                padding: 8px;
            }
            
            .customer-info {
                padding: 6px;
                margin-bottom: 8px;
            }
            
            .customer-name {
                font-size: 0.85rem;
            }
            
            .customer-details {
                font-size: 0.7rem;
            }
        }
        
        /* Filter Modal Styles */
        .filter-option-btn {
            height: 80px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border-radius: 8px;
            transition: all 0.2s ease;
        }
        
        .filter-option-btn i {
            font-size: 1.5rem;
        }
        
        .filter-option-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .custom-date-range {
            background: #f8f9fc;
            border-radius: 8px;
            padding: 15px;
        }
        
        .d-flex.gap-2 {
            gap: 8px;
        }
    </style>
</head>

<body id="page-top">
    <!-- Page Wrapper -->
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include_once('includes/sidebar.php'); ?>
        
        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">
            <!-- Main Content -->
            <div id="content">
                <!-- Topbar -->
                <?php include_once('includes/topbar.php'); ?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Back Button -->
                    <a href="pos.php" class="back-btn">
                        <i class="fas fa-arrow-left"></i>
                        Back to POS
                    </a>
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h1 class="h5 mb-1">
                                    <i class="fas fa-bookmark mr-2"></i>
                                    Orders Management
                                </h1>
                                <p class="mb-0" style="font-size: 0.85rem; opacity: 0.9;">Manage pending and delivered orders</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-sm" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);" onclick="openDateFilterModal()">
                                    <i class="fas fa-filter mr-1"></i>Filter
                                </button>
                                <a href="pos.php" class="btn btn-sm" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                                    <i class="fas fa-plus mr-1"></i>New Order
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Filter Tabs -->
                    <div class="filter-tabs">
                        <button class="filter-tab active" onclick="filterOrders('Pending')" id="tab-pending">
                            <i class="fas fa-clock mr-1"></i>Pending
                        </button>
                        <button class="filter-tab" onclick="filterOrders('Delivered')" id="tab-delivered">
                            <i class="fas fa-check mr-1"></i>Delivered
                        </button>
                        <button class="filter-tab" onclick="filterOrders('Cancelled')" id="tab-cancelled">
                            <i class="fas fa-times mr-1"></i>Cancelled
                        </button>
                    </div>
                    
                    <!-- Orders Container -->
                    <div class="row" id="orders-container">
                        <div class="col-12">
                            <div class="empty-state">
                                <i class="fas fa-spinner fa-spin"></i>
                                <h5>Loading orders...</h5>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
            <!-- End of Main Content -->
            
            <!-- Footer -->
            <?php include_once('includes/footer.php'); ?>
        </div>
        <!-- End of Content Wrapper -->
    </div>
    <!-- End of Page Wrapper -->
    
    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Date Filter Modal -->
    <div class="modal fade" id="dateFilterModal" tabindex="-1" role="dialog" aria-labelledby="dateFilterModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="dateFilterModalLabel">
                        <i class="fas fa-filter mr-2"></i>Filter Orders by Date
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <p class="text-muted">Select a time period to filter your orders</p>
                    </div>
                    
                    <div class="row">
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('today')">
                                <i class="fas fa-calendar-day mb-1"></i><br>
                                <span>Today</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('yesterday')">
                                <i class="fas fa-calendar-minus mb-1"></i><br>
                                <span>Yesterday</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('this_week')">
                                <i class="fas fa-calendar-week mb-1"></i><br>
                                <span>This Week</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('last_week')">
                                <i class="fas fa-calendar-alt mb-1"></i><br>
                                <span>Last Week</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('this_month')">
                                <i class="fas fa-calendar mb-1"></i><br>
                                <span>This Month</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('last_month')">
                                <i class="fas fa-calendar-times mb-1"></i><br>
                                <span>Last Month</span>
                            </button>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <!-- Custom Date Range -->
                    <div class="custom-date-range">
                        <h6 class="text-center mb-3"><i class="fas fa-calendar-check mr-1"></i>Custom Date Range</h6>
                        <div class="row">
                            <div class="col-6">
                                <label class="small text-muted">From Date:</label>
                                <input type="date" class="form-control form-control-sm" id="fromDate">
                            </div>
                            <div class="col-6">
                                <label class="small text-muted">To Date:</label>
                                <input type="date" class="form-control form-control-sm" id="toDate">
                            </div>
                        </div>
                        <div class="text-center mt-3">
                            <button type="button" class="btn btn-success btn-sm" onclick="applyCustomDateFilter()">
                                <i class="fas fa-search mr-1"></i>Apply Custom Filter
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" onclick="clearDateFilter()">
                        <i class="fas fa-undo mr-1"></i>Clear Filter
                    </button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <!-- Core plugin JavaScript-->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    
    <!-- Custom scripts for all pages-->
    <script src="js/sb-admin-2.min.js"></script>
    
    <script>
        let currentFilter = 'Pending';
        
        $(document).ready(function() {
            // Hide sidebar on load for compact, content-focused layout
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            
            loadOrders('Pending');
        });
        
        // Filter orders by status
        function filterOrders(status) {
            currentFilter = status;
            
            // Update active tab
            $('.filter-tab').removeClass('active');
            $('#tab-' + status.toLowerCase()).addClass('active');
            
            // Load orders
            loadOrders(status);
        }
        
        // Load orders from API
        function loadOrders(status) {
            $('#orders-container').html(`
                <div class="empty-state">
                    <i class="fas fa-spinner fa-spin"></i>
                    <h4>Loading orders...</h4>
                </div>
            `);
            
            $.ajax({
                url: 'api/pending-orders.php',
                method: 'GET',
                data: { status: status },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        renderOrders(response.data, status);
                    } else {
                        showError('Error loading orders: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading orders:', error);
                    showError('Error loading orders. Please try again.');
                }
            });
        }
        
        // Render orders list
        function renderOrders(orders, status) {
            const container = $('#orders-container');
            
            if (orders.length === 0) {
                container.html(`
                    <div class="col-12">
                        <div class="empty-state">
                            <i class="fas fa-bookmark"></i>
                            <h5>No ${status.toLowerCase()} orders found</h5>
                            <p>There are no orders with ${status.toLowerCase()} status at the moment.</p>
                            <a href="pos.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-plus mr-1"></i>Create New Order
                            </a>
                        </div>
                    </div>
                `);
                return;
            }
            
            let html = '';
            orders.forEach(order => {
                html += renderOrderCard(order, status);
            });
            
            container.html(html);
        }
        
        // Create order card HTML
        function createOrderCard(order) {
            const statusClass = 'status-' + order.OrderStatus.toLowerCase();
            const orderDate = new Date(order.OrderDate).toLocaleDateString('en-IN', {
                day: '2-digit', month: 'short'
            });
            const orderTime = order.OrderTime.substring(0, 5);
            
            let actions = '';
            if (order.OrderStatus === 'Pending') {
                actions = `
                    <button class="btn-action btn-deliver" onclick="deliverOrder('${order.ID}')">
                        <i class="fas fa-truck"></i> Deliver
                    </button>
                    <button class="btn-action btn-edit" onclick="editOrder('${order.ID}')">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn-action btn-cancel" onclick="cancelOrder('${order.ID}')">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                `;
            } else {
                actions = `
                    <button class="btn-action btn-view" onclick="viewOrder('${order.ID}')">
                        <i class="fas fa-eye"></i> View
                    </button>
                `;
            }
            
            let deliveryInfo = '';
            if (order.DeliveryDate) {
                const deliveryDate = new Date(order.DeliveryDate).toLocaleDateString('en-IN', {
                    day: '2-digit', month: 'short'
                });
                deliveryInfo = `
                    <div class="info-item">
                        <div class="info-label">Delivered</div>
                        <div class="info-value">${deliveryDate}</div>
                    </div>
                `;
            }
            
            return `
                <div class="col-lg-3 col-md-4 col-sm-6 col-12">
                    <div class="order-card ${statusClass}">
                        <div class="order-header">
                            <div class="order-number">${order.OrderNumber}</div>
                            <div class="order-status">${order.OrderStatus}</div>
                        </div>
                        <div class="order-body">
                            <div class="customer-info">
                                <div class="customer-name">${order.CustomerName}</div>
                                <div class="customer-details">${order.Mobile} • ${order.Area}</div>
                            </div>
                            
                            <div class="order-info">
                                <div class="info-item">
                                    <div class="info-label">Date</div>
                                    <div class="info-value">${orderDate}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Amount</div>
                                    <div class="info-value">₹${parseFloat(order.TotalAmount).toFixed(0)}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Items</div>
                                    <div class="info-value">${order.ItemCount} items</div>
                                </div>
                                ${deliveryInfo || `
                                <div class="info-item">
                                    <div class="info-label">Time</div>
                                    <div class="info-value">${orderTime}</div>
                                </div>
                                `}
                            </div>
                            
                            ${order.Notes ? `
                            <div style="background: #fff3cd; padding: 4px 6px; border-radius: 4px; margin: 6px 0; font-size: 0.7rem; color: #856404;">
                                <strong>Note:</strong> ${order.Notes}
                            </div>
                            ` : ''}
                            
                            <div class="order-actions">
                                ${actions}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // Mark order as delivered and proceed to checkout
        function deliverOrder(orderId) {
            if (confirm('Mark this order as delivered and proceed to checkout?')) {
                // Redirect to POS with order data for checkout
                window.location.href = `pos.php?deliver_order=${orderId}`;
            }
        }
        
        // Edit order
        function editOrder(orderId) {
            window.location.href = `pos.php?edit_order=${orderId}`;
        }
        
        // Cancel order
        function cancelOrder(orderId) {
            if (confirm('Are you sure you want to cancel this order? This action cannot be undone.')) {
                $.ajax({
                    url: 'api/pending-orders.php',
                    method: 'PUT',
                    data: JSON.stringify({
                        order_id: orderId,
                        order_status: 'Cancelled'
                    }),
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            alert('Order cancelled successfully');
                            loadOrders(currentFilter);
                        } else {
                            alert('Error cancelling order: ' + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error cancelling order:', error);
                        alert('Error cancelling order. Please try again.');
                    }
                });
            }
        }
        
        // View order details
        function viewOrder(orderId) {
            // TODO: Implement order details modal
            alert('View order details functionality coming soon!');
        }
        
        // Show error message
        function showError(message) {
            $('#orders-container').html(`
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-exclamation-triangle" style="color: #e74a3b;"></i>
                        <h5>Error</h5>
                        <p>${message}</p>
                        <button class="btn btn-primary btn-sm" onclick="loadOrders(currentFilter)">Try Again</button>
                    </div>
                </div>
            `);
        }
        
        // Date Filter Functions
        let currentDateFilter = null;
        
        // Open date filter modal
        function openDateFilterModal() {
            $('#dateFilterModal').modal('show');
        }
        
        // Apply predefined date filter
        function applyDateFilter(filterType) {
            const today = new Date();
            let fromDate, toDate;
            
            switch(filterType) {
                case 'today':
                    fromDate = toDate = today.toISOString().split('T')[0];
                    break;
                    
                case 'yesterday':
                    const yesterday = new Date(today);
                    yesterday.setDate(yesterday.getDate() - 1);
                    fromDate = toDate = yesterday.toISOString().split('T')[0];
                    break;
                    
                case 'this_week':
                    const startOfWeek = new Date(today);
                    const dayOfWeek = today.getDay();
                    startOfWeek.setDate(today.getDate() - dayOfWeek);
                    fromDate = startOfWeek.toISOString().split('T')[0];
                    toDate = today.toISOString().split('T')[0];
                    break;
                    
                case 'last_week':
                    const lastWeekEnd = new Date(today);
                    const lastWeekStart = new Date(today);
                    lastWeekEnd.setDate(today.getDate() - today.getDay() - 1);
                    lastWeekStart.setDate(lastWeekEnd.getDate() - 6);
                    fromDate = lastWeekStart.toISOString().split('T')[0];
                    toDate = lastWeekEnd.toISOString().split('T')[0];
                    break;
                    
                case 'this_month':
                    fromDate = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
                    toDate = today.toISOString().split('T')[0];
                    break;
                    
                case 'last_month':
                    const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                    const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
                    fromDate = lastMonth.toISOString().split('T')[0];
                    toDate = lastMonthEnd.toISOString().split('T')[0];
                    break;
            }
            
            currentDateFilter = { from: fromDate, to: toDate, type: filterType };
            loadOrdersWithDateFilter();
            $('#dateFilterModal').modal('hide');
        }
        
        // Apply custom date range filter
        function applyCustomDateFilter() {
            const fromDate = $('#fromDate').val();
            const toDate = $('#toDate').val();
            
            if (!fromDate || !toDate) {
                alert('Please select both from and to dates');
                return;
            }
            
            if (new Date(fromDate) > new Date(toDate)) {
                alert('From date cannot be later than to date');
                return;
            }
            
            currentDateFilter = { from: fromDate, to: toDate, type: 'custom' };
            loadOrdersWithDateFilter();
            $('#dateFilterModal').modal('hide');
        }
        
        // Clear date filter
        function clearDateFilter() {
            currentDateFilter = null;
            loadOrders(currentFilter);
            $('#dateFilterModal').modal('hide');
        }
        
        // Load orders with date filter
        function loadOrdersWithDateFilter() {
            if (!currentDateFilter) {
                loadOrders(currentFilter);
                return;
            }
            
            $('#orders-container').html(`
                <div class="empty-state">
                    <i class="fas fa-spinner fa-spin"></i>
                    <h4>Filtering orders...</h4>
                </div>
            `);
            
            $.ajax({
                url: 'api/pending-orders.php',
                method: 'GET',
                data: { 
                    status: currentFilter,
                    from_date: currentDateFilter.from,
                    to_date: currentDateFilter.to
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        renderFilteredOrders(response.data, currentFilter);
                    } else {
                        showError('Error loading filtered orders: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading filtered orders:', error);
                    showError('Error loading filtered orders. Please try again.');
                }
            });
        }
        
        // Render filtered orders
        function renderFilteredOrders(orders, status) {
            const container = $('#orders-container');
            
            if (orders.length === 0) {
                container.html(`
                    <div class="col-12">
                        <div class="empty-state">
                            <i class="fas fa-calendar-times"></i>
                            <h4>No orders found</h4>
                            <p>No ${status.toLowerCase()} orders found for the selected date range</p>
                            <button class="btn btn-outline-primary btn-sm" onclick="clearDateFilter()">
                                <i class="fas fa-undo mr-1"></i>Clear Filter
                            </button>
                        </div>
                    </div>
                `);
                return;
            }
            
            // Show filter info
            let filterText = '';
            if (currentDateFilter.type === 'custom') {
                filterText = `Custom range: ${currentDateFilter.from} to ${currentDateFilter.to}`;
            } else {
                filterText = currentDateFilter.type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
            }
            
            let html = `
                <div class="col-12 mb-3">
                    <div class="alert alert-info alert-dismissible fade show" role="alert">
                        <i class="fas fa-filter mr-2"></i>
                        <strong>Filtered by:</strong> ${filterText} (${orders.length} orders found)
                        <button type="button" class="btn btn-sm btn-outline-primary ml-3" onclick="clearDateFilter()">
                            <i class="fas fa-times mr-1"></i>Clear Filter
                        </button>
                    </div>
                </div>
            `;
            
            // Render orders (reuse existing rendering logic)
            orders.forEach(order => {
                html += renderOrderCard(order, status);
            });
            
            container.html(html);
        }
        
        // Render individual order card (extracted for reuse)
        function renderOrderCard(order, status) {
            const statusBadge = status === 'Pending' ? 
                '<span class="badge badge-warning">Pending</span>' : 
                status === 'Delivered' ?
                '<span class="badge badge-success">Delivered</span>' :
                '<span class="badge badge-secondary">Cancelled</span>';
                
            const actionButtons = status === 'Pending' ? 
                `<button class="btn-action btn-deliver" onclick="deliverOrder(${order.ID})">
                    <i class="fas fa-truck"></i> Deliver
                </button>
                <button class="btn-action btn-edit" onclick="editOrder(${order.ID})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn-action btn-cancel" onclick="cancelOrder(${order.ID})">
                    <i class="fas fa-times"></i> Cancel
                </button>` :
                `<button class="btn-action btn-view" onclick="viewOrder(${order.ID})">
                    <i class="fas fa-eye"></i> View
                </button>`;
                
            const orderDate = new Date(order.CreatedAt || order.OrderDate).toLocaleDateString('en-IN', {
                day: '2-digit', month: 'short'
            });
            const orderTime = new Date(order.CreatedAt || order.OrderDate).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
                
            return `
                <div class="col-lg-3 col-md-4 col-sm-6 col-12">
                    <div class="order-card status-${status.toLowerCase()}">
                        <div class="order-header">
                            <div class="order-number">#${order.OrderNumber}</div>
                            <div class="order-status">${status}</div>
                        </div>
                        
                        <div class="order-body">
                            <div class="customer-info">
                                <div class="customer-name">${order.CustomerName}</div>
                                <div class="customer-details">
                                    <i class="fas fa-phone mr-1"></i>${order.Mobile || 'N/A'}
                                    ${order.Area ? ` • ${order.Area}` : ''}
                                </div>
                            </div>
                            
                            <div class="order-info">
                                <div class="info-item">
                                    <div class="info-label">Date</div>
                                    <div class="info-value">${orderDate}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Amount</div>
                                    <div class="info-value">₹${parseFloat(order.TotalAmount || 0).toFixed(0)}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Items</div>
                                    <div class="info-value">${order.ItemCount || 0}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Time</div>
                                    <div class="info-value">${orderTime}</div>
                                </div>
                            </div>
                            
                            <div class="order-actions">
                                ${actionButtons}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
    </script>
</body>
</html>