<x-app-layout>
    <style>
        /* Main Container Styles */
        .order-management-container {
            font-family: 'Inter', sans-serif;
            padding: 20px;
            background-color: #f8fafc;
            min-height: calc(100vh - 64px);
        }
        
        /* Header Styles */
        .header-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            margin-bottom: 20px;
        }
        
        .header-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1e293b;
        }
        
        .header-subtitle {
            font-size: 1rem;
            color: #64748b;
            margin-left: 8px;
        }
        
        /* Status Cards Container */
        .status-cards-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 25px;
            padding-bottom: 15px;
            overflow-x: auto;
        }
        
        /* Status Card Styles */
        .status-card {
            flex: 1 1 160px;
            min-width: 160px;
            background-color: white;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid #e2e8f0;
        }
        
        .status-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .status-card.active {
            border: 2px solid #1b59f8;
            background-color: #f0f5ff;
        }
        
        .status-name {
            font-size: 0.85rem;
            color: #64748b;
            font-weight: 500;
            margin-bottom: 5px;
        }
        
        .status-count {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        /* Table Styles */
        .orders-table-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .table-actions {
            display: flex;
            gap: 10px;
        }
        
        .export-btn {
            background-color: #1b59f8;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .export-btn:hover {
            background-color: #1547c7;
        }
        
        /* Enhanced Status Badge Styles */
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-align: center;
            display: inline-block;
            min-width: 100px;
            text-transform: capitalize;
        }
        
        .badge-pending {
            background-color: #ffedd5;
            color: #9a3412;
            border: 1px solid #fdba74;
        }
        
        .badge-accepted {
            background-color: #dbeafe;
            color: #1e40af;
            border: 1px solid #93c5fd;
        }
        
        .badge-pickup {
            background-color: #e0f2fe;
            color: #0c4a6e;
            border: 1px solid #7dd3fc;
        }
        
        .badge-completed {
            background-color: #dcfce7;
            color: #166534;
            border: 1px solid #86efac;
        }
        
        .badge-cancelled {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #fca5a5;
        }
        
        .badge-vendor {
            background-color: #f3e8ff;
            color: #6b21a8;
            border: 1px solid #d8b4fe;
        }
        
        .badge-ready {
            background-color: #fef3c7;
            color: #92400e;
            border: 1px solid #fcd34d;
        }
        
        /* Action Button */
        .action-btn {
            padding: 5px 12px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            background-color: #1b59f8;
            color: white;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .action-btn:hover {
            background-color: #1547c7;
            transform: translateY(-1px);
        }
        
        /* Responsive Adjustments */
        @media (max-width: 1024px) {
            .status-cards-container {
                gap: 10px;
            }
            
            .status-card {
                min-width: 140px;
                padding: 12px;
            }
        }
        
        @media (max-width: 768px) {
            .header-container {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .table-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
            
            .status-card {
                min-width: 120px;
            }
        }
        
        /* DataTable Customizations */
        .dataTables_wrapper .dataTables_filter input {
            border: 1px solid #e2e8f0 !important;
            border-radius: 6px !important;
            padding: 5px 10px !important;
        }
        
        .dataTables_wrapper .dataTables_length select {
            border: 1px solid #e2e8f0 !important;
            border-radius: 6px !important;
            padding: 5px !important;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border: 1px solid #e2e8f0 !important;
            border-radius: 6px !important;
            padding: 5px 10px !important;
            margin: 0 3px !important;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: #1b59f8 !important;
            color: white !important;
            border-color: #1b59f8 !important;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
            background: #e2e8f0 !important;
            color: #1e293b !important;
        }
        
        /* Link Styles */
        .order-link {
            color: #1b59f8;
            font-weight: 500;
            text-decoration: none;
            transition: color 0.2s;
        }
        
        .order-link:hover {
            color: #1547c7;
            text-decoration: underline;
        }
        
        /* Status Legend */
        .status-legend {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
            padding: 10px;
            background-color: #f8fafc;
            border-radius: 6px;
        }
        
        .legend-item {
            display: flex;
            align-items: center;
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 3px;
            margin-right: 5px;
            border: 1px solid rgba(0,0,0,0.1);
        }
    </style>

    <!-- Include Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    
    <!-- Include DataTables CSS and JS -->
    <link href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>

    <!-- Main Container -->
    <div class="order-management-container">
        <!-- Header Section -->
        <div class="header-container">
            <div>
                <h1 class="header-title">
                    Order Management
                    <span class="header-subtitle">/ All Orders</span>
                </h1>
            </div>
        </div>

        <!-- Status Cards -->
        <div class="status-cards-container">
            @php
                // Merge Delivered and Completed counts
                $completedCount = ($statusCounts['Delivered'] ?? 0) + ($statusCounts['Completed'] ?? 0);
                
                $statuses = [
                    'All' => $totalOrdersCount,
                    'Pending' => $statusCounts['Pending'] ?? 0,
                    'Accepted' => $statusCounts['Accepted'] ?? 0,
                    'Pickup In Progress' => $statusCounts['Pickup In Progress'] ?? 0,
                    'Picked Up' => $statusCounts['Picked Up'] ?? 0,
                    'At Vendor' => $statusCounts['At Vendor'] ?? 0,
                    'Ready for Delivery' => $statusCounts['Ready for Delivery'] ?? 0,
                    'Delivery In Progress' => $statusCounts['Delivery In Progress'] ?? 0,
                    'Completed' => $completedCount,
                    'Cancelled' => $statusCounts['Cancelled'] ?? 0,
                ];
            @endphp

            @foreach($statuses as $status => $count)
                <div class="status-card" onclick="filterTable('{{ $status }}')" id="card-{{ str_replace(' ', '-', $status) }}">
                    <div class="status-name">{{ $status }} Orders</div>
                    <div class="status-count">
                        {{ $count }}
                        @if($status === 'All')
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-500" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.586L7.707 9.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 10.586V7z" clip-rule="evenodd" />
                            </svg>
                        @endif
                    </div>
                </div>
            @endforeach
        </div>

        <!-- Status Legend -->
        <div class="status-legend">
            <div class="legend-item"><div class="legend-color bg-orange-100 border-orange-300"></div> Pending</div>
            <div class="legend-item"><div class="legend-color bg-blue-100 border-blue-300"></div> Accepted</div>
            <div class="legend-item"><div class="legend-color bg-cyan-100 border-cyan-300"></div> Pickup Related</div>
            <div class="legend-item"><div class="legend-color bg-purple-100 border-purple-300"></div> At Vendor</div>
            <div class="legend-item"><div class="legend-color bg-yellow-100 border-yellow-300"></div> Ready for Delivery</div>
            <div class="legend-item"><div class="legend-color bg-green-100 border-green-300"></div> Completed</div>
            <div class="legend-item"><div class="legend-color bg-red-100 border-red-300"></div> Cancelled</div>
        </div>

        <!-- Table Section -->
        <div class="orders-table-container">
            <div class="table-header">
                <h2 class="text-lg font-semibold text-gray-800" id="table-title">All Orders</h2>
                <div class="table-actions">
                    <button id="exportBtn" class="export-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        Export to Excel
                    </button>
                </div>
            </div>
            
            <div class="overflow-x-auto">
                <table id="ordersTable" class="w-full stripe hover" style="width:100%">
                    <thead>
                        <tr class="bg-gray-100 text-gray-600 uppercase text-sm">
                            <th class="px-6 py-3 text-left">Order ID</th>
                            <th class="px-6 py-3 text-left">Customer</th>
                            <th class="px-6 py-3 text-left">Contact</th>
                            <th class="px-6 py-3 text-left">Location</th>
                            <th class="px-6 py-3 text-left">Payment</th>
                            <th class="px-6 py-3 text-left">Status</th>
                            <th class="px-6 py-3 text-left">Items</th>
                            <th class="px-6 py-3 text-left">Amount</th>
                            <th class="px-6 py-3 text-left">Date</th>
                            <th class="px-6 py-3 text-left">Action</th>
                        </tr>
                    </thead>
                    <tbody class="text-sm">
                        @foreach ($formattedOrders as $order)
                            <tr class="border-b border-gray-100 hover:bg-gray-50">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <a href="{{ route('ordersShow', ['id' => $order['OrderID']]) }}" class="order-link">
                                        #{{ $order['OrderID'] }}
                                    </a>
                                </td>
                                <td class="px-6 py-4">{{ $order['user']['name'] }}</td>
                                <td class="px-6 py-4">{{ $order['user']['phone'] }}</td>
                                <td class="px-6 py-4">{{ Str::limit($order['user']['address'], 20) }}</td>
                                <td class="px-6 py-4">{{ $order['PaymentMode'] }}</td>
                                <td class="px-6 py-4">
                                    @php
                                        $statusClass = '';
                                        $displayStatus = $order['status'];
                                        
                                        // Convert "Delivered" to "Completed" for display
                                        if (str_contains($order['status'], 'Delivered')) {
                                            $displayStatus = 'Completed';
                                        }
                                        
                                        if(str_contains($order['status'], 'Pending')) $statusClass = 'badge-pending';
                                        elseif(str_contains($order['status'], 'Accepted')) $statusClass = 'badge-accepted';
                                        elseif(str_contains($order['status'], 'Pickup') || str_contains($order['status'], 'Picked')) $statusClass = 'badge-pickup';
                                        elseif(str_contains($order['status'], 'At Vendor')) $statusClass = 'badge-vendor';
                                        elseif(str_contains($order['status'], 'Ready for Delivery')) $statusClass = 'badge-ready';
                                        elseif(str_contains($order['status'], 'Delivered') || str_contains($order['status'], 'Completed')) $statusClass = 'badge-completed';
                                        elseif(str_contains($order['status'], 'Cancelled')) $statusClass = 'badge-cancelled';
                                    @endphp
                                    <span class="status-badge {{ $statusClass }}">{{ $displayStatus }}</span>
                                </td>
                                <td class="px-6 py-4">{{ $order['TotalItems'] }}</td>
                                <td class="px-6 py-4 font-medium">₹{{ number_format($order['UserTotalCost'], 2) }}</td>
                                <td class="px-6 py-4">{{ date('d M Y', strtotime($order['created_at'])) }}</td>
                                <td class="px-6 py-4">
                                    <a href="{{ route('ordersShow', ['id' => $order['OrderID']]) }}" class="action-btn">
                                        View
                                    </a>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            var table = $('#ordersTable').DataTable({
                responsive: true,
                dom: '<"top"lf>rt<"bottom"ip>',
                language: {
                    search: "_INPUT_",
                    searchPlaceholder: "Search orders...",
                    lengthMenu: "Show _MENU_ entries",
                    paginate: {
                        previous: "&lt;",
                        next: "&gt;"
                    }
                },
                columnDefs: [
                    { responsivePriority: 1, targets: 0 }, // Order ID
                    { responsivePriority: 2, targets: 5 }, // Status
                    { responsivePriority: 3, targets: 7 }, // Amount
                    { responsivePriority: 4, targets: 1 }, // Customer
                    { responsivePriority: 5, targets: 8 }  // Date
                ],
                initComplete: function() {
                    // Add custom class to search input
                    $('.dataTables_filter input').addClass('border border-gray-300 rounded-md px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500');
                    
                    // Add custom class to length select
                    $('.dataTables_length select').addClass('border border-gray-300 rounded-md px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500');
                }
            });

            // Export to Excel function
            $('#exportBtn').on('click', function() {
                // Get column headers
                var headers = [];
                $('#ordersTable thead th').each(function() {
                    headers.push($(this).text().trim());
                });

                // Get filtered data
                var tableData = [];
                table.rows({ filter: 'applied' }).every(function() {
                    var rowData = [];
                    $(this.node()).find('td').each(function() {
                        // Exclude the link from Order ID
                        if ($(this).find('.order-link').length) {
                            rowData.push($(this).find('.order-link').text().trim());
                        } else {
                            rowData.push($(this).text().trim());
                        }
                    });
                    tableData.push(rowData);
                });

                // Create workbook
                var wb = XLSX.utils.book_new();
                var ws = XLSX.utils.aoa_to_sheet([headers, ...tableData]);
                
                // Add worksheet to workbook
                XLSX.utils.book_append_sheet(wb, ws, 'Orders');
                
                // Generate and download the file
                XLSX.writeFile(wb, 'orders_export_' + new Date().toISOString().slice(0,10) + '.xlsx');
            });

            // Initialize the first card as active
            $('#card-All').addClass('active');
        });

        function filterTable(status) {
            var table = $('#ordersTable').DataTable();
            var tableTitle = $('#table-title');
            
            // Update active card
            $('.status-card').removeClass('active');
            $('#card-' + status.replace(/ /g, '-')).addClass('active');
            
            // Update table title
            tableTitle.text(status + (status === 'All' ? ' Orders' : ' Orders'));
            
            if (status === 'All') {
                table.column(5).search('').draw();
            } else if (status === 'Completed') {
                // Search for both "Completed" and "Delivered" when Completed is selected
                table.column(5).search('^(Completed|Delivered)$', true, false, true).draw();
            } else {
                table.column(5).search('^' + status + '$', true, false).draw();
            }
        }
    </script>
</x-app-layout>