<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Orders Table</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.7.2/css/buttons.dataTables.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .status-P { background-color: #ffdddd; } /* Pending */
        .status-R { background-color: #ffffdd; } /* Pickup by delivery agent */
        .status-OP { background-color: #ddffdd; } /* Order reached to vendor */
        .status-RP { background-color: #ddddff; } /* Order in progress */
        .status-OW { background-color: #ffeedd; } /* Order ready to deliver */
        .status-OD { background-color: #ddffee; } /* Order picked by delivery agent */
        .status-WE { background-color: #eeeeee; } /* Order delivered to user */
        tr:hover { background-color: #f1f1f1; } /* Hover effect */
        .btn-icon { display: flex; align-items: center; gap: 4px; }
    </style>
</head>
<body class="bg-gray-100 p-6">


    <!-- Filter and Search Section -->
    <div class="mb-6">
        <div class="mb-4 flex gap-4 flex-wrap">
            <button id="filterAll" class="btn-icon px-4 py-2 bg-blue-500 text-white rounded">
                <i class="fas fa-filter"></i> All
            </button>
            <button id="filterPending" class="btn-icon px-4 py-2 bg-red-500 text-white rounded">
                <i class="fas fa-hourglass-half"></i> Pending
            </button>
            <button id="filterPickup" class="btn-icon px-4 py-2 bg-yellow-500 text-white rounded">
                <i class="fas fa-truck"></i> Pickup
            </button>
            <button id="filterReached" class="btn-icon px-4 py-2 bg-green-500 text-white rounded">
                <i class="fas fa-store"></i> Reached
            </button>
            <button id="filterInProgress" class="btn-icon px-4 py-2 bg-blue-500 text-white rounded">
                <i class="fas fa-cogs"></i> In Progress
            </button>
            <button id="filterReady" class="btn-icon px-4 py-2 bg-purple-500 text-white rounded">
                <i class="fas fa-box-open"></i> Ready
            </button>
            <button id="filterPicked" class="btn-icon px-4 py-2 bg-green-500 text-white rounded">
                <i class="fas fa-handshake"></i> Picked
            </button>
            <button id="filterDelivered" class="btn-icon px-4 py-2 bg-gray-500 text-white rounded">
                <i class="fas fa-check-double"></i> Delivered
            </button>
            <input id="searchInput" type="text" placeholder="Search orders..." class="px-4 py-2 border rounded w-full max-w-xs mt-2">
            <button id="downloadButton" class="btn-icon px-4 py-2 bg-teal-500 bg-black text-white rounded">
            <i class="fas fa-download"></i> Export
        </button>
        </div>
    </div>

    <div class="mb-4 flex justify-end">
        
    </div>

    <div class="overflow-x-auto">
        <table id="ordersTable" class="min-w-full bg-white border border-gray-200">
            <thead class="bg-gray-100">
                <tr>
                    <th class="px-4 py-2">Orders</th>
                    <th class="px-4 py-2">User</th>
                    <th class="px-4 py-2">Mobile Number</th>
                    <th class="px-4 py-2">Location</th>
                    <th class="px-4 py-2">Payment</th>
                    <th class="px-4 py-2">Status</th>
                    <th class="px-4 py-2">Total Items</th>
                    <th class="px-4 py-2">Total Sales</th>
                    <th class="px-4 py-2">Date</th>
                </tr>
            </thead>
            <tbody id="ordersTableBody">
            </tbody>
            <tfoot class="bg-gray-100">
                <tr>
                    <td colspan="6" class="px-4 py-2 font-bold">Total</td>
                    <td id="totalItems" class="px-4 py-2">0</td>
                    <td id="totalSales" class="px-4 py-2">0</td>
                    <td class="px-4 py-2"></td>
                </tr>
            </tfoot>
        </table>
    </div>

    <!-- DataTables Buttons Extension Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.7.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.7.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.7.2/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/js/all.min.js"></script>

<script>
    // Cache to store fetched locations
    const locationCache = new Map();

    async function fetchAllUsers() {
        try {
            const response = await fetch('http://localhost:8000fetch_all_users');
            const usersData = await response.json();
            if (usersData.success) {
                return usersData.data.reduce((acc, user) => {
                    acc[user.ID] = user;
                    return acc;
                }, {});
            }
            return {};
        } catch (error) {
            console.error('Error fetching users:', error);
            return {};
        }
    }

    async function fetchOrders() {
        try {
            const response = await fetch('http://localhost:8000order_apis');
            const data = await response.json();
            const users = await fetchAllUsers();
            const tableBody = document.querySelector('#ordersTableBody');
            let totalItemsCount = 0;
            let totalSalesAmount = 0;

            tableBody.innerHTML = '';

            const statusDescriptions = {
                'P': 'Pending',
                'R': 'Pickup',
                'OP': 'Reached',
                'RP': 'In Progress',
                'OW': 'Ready',
                'OD': 'Picked',
                'WE': 'Delivered'
            };

            const statusClasses = {
                'P': 'status-P',
                'R': 'status-R',
                'OP': 'status-OP',
                'RP': 'status-RP',
                'OW': 'status-OW',
                'OD': 'status-OD',
                'WE': 'status-WE'
            };

            for (const status in data.statusCounts) {
                const orders = data.statusCounts[status].orders;

                orders.forEach(order => {
                    const row = document.createElement('tr');
                    const user = users[order.userID] || {};
                    const userName = user.name || 'N/A';
                    const userMobile = user.phone || 'N/A';

                    let totalItems = 0;
                    let totalKg = 0;
                    let totalCost = 0;

                    if (order.Items) {
                        const items = JSON.parse(order.Items);
                        if (Array.isArray(items) && items.length > 0) {
                            totalItems = items.reduce((sum, item) => sum + (item.quantity || 0), 0);
                        }
                    }

                    if (totalItems === 0 && order.itemsbykg) {
                        const itemsByKg = JSON.parse(order.itemsbykg);
                        if (Array.isArray(itemsByKg) && itemsByKg.length > 0) {
                            totalKg = itemsByKg.reduce((sum, item) => sum + (item.kg || 0), 0);
                            totalItems = itemsByKg.reduce((sum, item) => sum + (item.count || 0), 0);
                            totalCost = itemsByKg.reduce((sum, item) => sum + (item.total_cost || 0), 0);
                        }
                    }

                    row.innerHTML = `
                        <td class="px-4 py-2 border">
    <a href="http://localhost:8000orderDetails/${order.OrderID}" class="text-blue-500 hover:underline">
        ${order.OrderID}
    </a>
</td>

                        <td class="px-4 py-2 border">${userName}</td>
                        <td class="px-4 py-2 border">${userMobile}</td>
                        <td class="px-4 py-2 border location-cell" data-lat="${order.UserLatitude}" data-lng="${order.UserLongitude}">Fetching location...</td>
                        <td class="px-4 py-2 border">${order.PaymentMode || 'N/A'}</td>
                        <td class="px-4 py-2 border ${statusClasses[status]}">${statusDescriptions[status] || status}</td>
                        <td class="px-4 py-2 border">${totalItems > 0 ? `${totalItems}` : `${totalKg} kg`}</td>
                        <td class="px-4 py-2 border">${order.UserTotalCost}</td>
                        <td class="px-4 py-2 border">${order.PickupDate || 'N/A'}</td>
                    `;

                    tableBody.appendChild(row);

                    totalItemsCount += totalItems > 0 ? totalItems : totalKg;
                    totalSalesAmount += totalCost || parseFloat(order.UserTotalCost) || 0;
                });
            }

            document.getElementById('totalItems').textContent = `${totalItemsCount} ${totalItemsCount > 0 ? '' : 'kg'}`;
            document.getElementById('totalSales').textContent = totalSalesAmount.toFixed(2);

            initializeDataTable();

            // Fetch and update location for each order
            updateLocations();

        } catch (error) {
            console.error('Error fetching orders:', error);
        }
    }

    function initializeDataTable() {
        const table = $('#ordersTable').DataTable({
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'excelHtml5',
                    text: '<i class="fas fa-file-excel"></i> Download Excel',
                    className: 'px-4 py-2 bg-green-500 text-white rounded'
                },
                {
                    extend: 'csvHtml5',
                    text: '<i class="fas fa-file-csv"></i> Download CSV',
                    className: 'px-4 py-2 bg-blue-500 text-white rounded'
                },
                {
                    extend: 'print',
                    text: '<i class="fas fa-print"></i> Print',
                    className: 'px-4 py-2 bg-yellow-500 text-white rounded'
                }
            ],
                searching: true,
            paging: true,
            info: true,
            autoWidth: false,
            ordering: true,
                 order: [[0, 'desc']], // Orders the table by the 1st column (OrderID) in descending order
            drawCallback: function () {
                updateLocations(); // Update locations whenever table is redrawn
            }
        });

        customFilters(table);
    }

    function customFilters(table) {
        $('#filterAll').on('click', function () {
            table.columns(5).search('').draw();
        });

        $('#filterPending').on('click', function () {
            table.columns(5).search('Pending').draw();
        });

        $('#filterPickup').on('click', function () {
            table.columns(5).search('Pickup').draw();
        });

        $('#filterReached').on('click', function () {
            table.columns(5).search('Reached').draw();
        });

        $('#filterInProgress').on('click', function () {
            table.columns(5).search('In Progress').draw();
        });

        $('#filterReady').on('click', function () {
            table.columns(5).search('Ready').draw();
        });

        $('#filterPicked').on('click', function () {
            table.columns(5).search('Picked').draw();
        });

        $('#filterDelivered').on('click', function () {
            table.columns(5).search('Delivered').draw();
        });

        $('#searchInput').on('keyup', function () {
            table.search(this.value).draw();
        });

        $('#downloadAll').on('click', function () {
            table.button('.buttons-excel').trigger();
        });
    }

    async function getLocationFromLatLng(latitude, longitude) {
        const key = `${latitude},${longitude}`;
        if (locationCache.has(key)) {
            return locationCache.get(key);
        }

        const apiKey = 'AIzaSyAlcZM-RHySJIQmUwOaJmJCVPZcuMKS70Y';
        const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${apiKey}`;

        try {
            const response = await fetch(url);
            const data = await response.json();
            if (data.status === 'OK') {
                const location = data.results[0].formatted_address;
                locationCache.set(key, location); // Cache the location
                return location;
            } else {
                return 'Location not found';
            }
        } catch (error) {
            console.error('Error fetching location:', error);
            return 'Error fetching location';
        }
    }

   async function updateLocations() {
        const locationCells = document.querySelectorAll('.location-cell');
        for (const cell of locationCells) {
            const latitude = cell.getAttribute('data-lat');
            const longitude = cell.getAttribute('data-lng');
            const location = await getLocationFromLatLng(latitude, longitude);
            cell.innerText = location;
        }
    }

    window.onload = fetchOrders;
</script>




<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

<script>
    async function downloadTableAsExcel(tableId, filename = 'Orders.xlsx') {
        // Get the table element by its ID
        let table = document.getElementById(tableId);

        // If the table does not exist, exit the function
        if (!table) {
            console.error(`Table with ID "${tableId}" not found.`);
            return;
        }

        // Get all rows in the table
        let rows = Array.from(table.querySelectorAll('tbody tr'));

        // Map the rows to extract the cell data
        let data = rows.map(row => {
            return Array.from(row.querySelectorAll('td')).map(td => td.textContent);
        });

        // Create a new workbook and worksheet
        let wb = XLSX.utils.book_new();
        let ws = XLSX.utils.aoa_to_sheet(data);

        // Append the worksheet to the workbook
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        // Write the workbook to binary format
        let wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

        // Convert binary string to array buffer
        function s2ab(s) {
            let buf = new ArrayBuffer(s.length);
            let view = new Uint8Array(buf);
            for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }

        // Save the workbook as a file
        saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), filename);
    }

    // Bind the download functionality to a button click
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('downloadButton').addEventListener('click', () => {
            downloadTableAsExcel('ordersTable');
        });
    });
</script>
</body>
</html>
<?php /**PATH /home/u152672654/domains/drycleaneo.com/public_html/admin/resources/views/components/totalOrder.blade.php ENDPATH**/ ?>