
<link href="https://cdn.datatables.net/v/dt/dt-2.0.5/datatables.min.css" rel="stylesheet">
    <style>
        table.dataTable th.dt-type-numeric,
        table.dataTable th.dt-type-date,
        table.dataTable td.dt-type-numeric,
        table.dataTable td.dt-type-date {
            text-align: left;
        }

        .users-management {
            display: flex;
            flex-direction: column;
            width: 100%;
            height: auto;
        }

        .users-add-top {
            display: flex;
            width: auto;
            height: auto;
            margin-top: -30px;
        }

        .users-add-user {
            width: 227px;
            height: 51px;
            background: #75B1E8;
            border-radius: 8px;
            /* Add User */
            font-weight: 600;
            font-size: 20px;
            line-height: 24px;
            color: #FFFFFF;
            text-align: center;
            padding-top: 13px;
        }

        .users-total {
            width: 265.86px;
            height: 90px;
            background: white;
            border-radius: 8px;
            padding-top: 20px;
            padding-left: 20px;
            margin-left: -10px;
        }

        .users-total p,
        .users-total .users-count-top p {
            font-weight: 400;
            font-size: 14px;
            line-height: 16px;
            color: #8F9BB3;
        }

        .users-count-top {
            display: flex;
            justify-content: space-between;
        }

        .users-count-top img {
            margin-top: -15px;
            margin-right: 18px;
        }

        .users-total h6 {
            font-weight: 600;
            font-size: 20px;
            line-height: 24px;
            color: #222B45;
            margin-top: -5px;
            text-align: left;
        }

        .payemnt-status {
            width: 100%;
            height: auto;
            margin-top: 20px;
            border-radius: 8px;
            background: white;
            border: 1px solid #1b59f8;
            padding: 10px;
        }


        .payemnt-status-top {
            width: 100%;
            display: flex;
            margin-bottom: 15px;
        }

        .payemnt-status-top-left {
            display: flex;
            flex: 90%;
            flex-wrap: wrap;
        }

        .payment-status-box {
            width: fit-content;
            border-radius: 6px;
            border: 1px solid #D9DBDE;
            padding: 2px 5px;
            height: 30px;
            margin-right: 20px;
        }

        .payment-status-box p {
            font-size: 12px;
            color: #979797;
        }

        .payment-status-box span {
            background-color: #6788DD;
            padding: 3px 5px;
            border-radius: 4px;
            font-size: 11px;
            color: #ffffff;
            margin-left: 8px;
        }

        /*===============*/
        .payemnt-status-top-right {
            display: flex;
            flex: 10%;
            gap: 18px;
            margin-top: 13px;
        }

        .payemnt-status-top-right img {
            height: 20px;
        }

        .payemnt-status-top-right p {
            font-size: 16px;
            font-weight: 400;
            line-height: 17px;
            letter-spacing: 0px;
            color: #979797;
        }

        .staff-searchAdd .staff-search {
            margin-left: 17px;
        }

        table {
            caption-side: bottom;
            border-collapse: collapse;
            width: 100%;
        }

        table#dynamic-table {
            width: 80%;
            margin: auto;
            margin-top: 15px;
        }

        tr:nth-child(even) {
            background: #F1F3F9;
        }

        #t-head {
            background: #F1F3F9;
        }

        th input[type="checkbox"] {
            margin-right: 10px;
            /* Adjust this value as needed */
        }

        .payment-status-button {
            /* Badge */
            box-sizing: border-box;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            padding: 1.39086px 6.95431px;
            width: 80px;
            height: 20px;
            color: white;
            background: #5EAA3A;
            border: 0.695431px solid #93C5FD;
            border-radius: 2.78173px;
        }

        .payment-order .payment-order-completed {
            width: 280px;
            height: 90px;
            background-color: white;
            padding-top: 20px;
            padding-left: 16px;
            margin-left: 20px;
            border-radius: 20px;
        }

        .searchbaar {
            width: 320px;
            height: 38px;
            border: 1px solid rgb(181, 180, 180);
            border-radius: 6px
        }

        .searchbaar input {
            overflow: hidden;
            width: 70%;
            border: none;
            outline: none;
            font-size: 13px;
        }

        table .admin {
            width: 70px;
            height: Hug (14.78px)px;
            padding: 5px;
            border-radius: 2.78px;
            border: 0.7px;
            background: #FFFFFF;
            border: 0.7px solid #93C5FD;
            font-weight: 500;
            line-height: 11.13px;
            text-align: center;
            color: #00E0FF;
        }

        table .new_user {
            width: 70px;
            height: Hug (14.78px)px;
            padding: 5px;
            border-radius: 2.78px;
            border: 0.7px;
            background: #DBEAFE;
            border: 0.7px solid #93C5FD;
            font-weight: 500;
            line-height: 11.13px;
            text-align: center;
            color: #1E40AF;
        }

        table td button.premium {
            padding: 5px;
            width: 70px;

        }

        table .premium {
            width: 70px;
            padding: 5px;
            height: Hug (14.78px)px;
            padding: 5px;
            border-radius: 2.78px;
            border: 0.7px;
            font-weight: 500;
            line-height: 11.13px;
            text-align: center;
        }

        table .regular {
            width: 70px;
            height: Hug (14.78px)px;
            padding: 5px;
            border-radius: 2.78px;
            border: 0.7px;
            background: #5EAA3A;
            border: 0.7px solid #93C5FD;
            font-weight: 500;
            line-height: 11.13px;
            text-align: center;
            color: #FFFFFF;
        }

        table .check {
            margin-right: 10px;
            margin-top: 3px;
        }

        table .check a {
            text-decoration: none;
            color: black;
        }

        .pagination {
            border: none;
            padding: 10px;

        }

        .page-item {
            margin: 5px;

        }

        .nav-item .nav-link {
            background-color: transparent !important;
        }


        .nav-pills .nav-link.active .users-total,
        .show .nav-link .users-total {
            border: 1px solid #1B59F8;
        }

        .searchbaar input {
            overflow: hidden;
            width: 70%;
            border: none;
            outline: none;
            font-size: 13px;
            line-height: 35px;
        }
              table.dataTable thead>tr>th.dt-orderable-asc, table.dataTable thead>tr>th.dt-orderable-desc, table.dataTable thead>tr>td.dt-orderable-asc, table.dataTable thead>tr>td.dt-orderable-desc
      {
          background: #F1F3F9;
      }
     div.dt-container .dt-info
     {
         display:none;
     }
     div.dt-container .dt-paging
     {
         text-align:center;
     }
     div.dt-container .dt-paging .dt-paging-button.current
     {
         height:33px;
         width:39px;
         color: #FFFFFF;
         border: 1px solid #1B59F8 !important;
         padding:4px 6px;
     }
    .dt-search
    {
        display:none;
    }
    .dt-layout-cell dt-start
    {
        float:right;   
    }
    .dt-length
    {
        float:right;
        margin-top:-70px;
        display: flex;
        flex-direction: row;
        gap: 10px;
        align-items: center;
        
    }
    table.dataTable
    {
        margin-top:-20px !important;
    }
    #custom-search::-ms-clear {
        display: none;
    }
    #custom-search::-webkit-search-cancel-button {
        display: none;
    }
    .payemnt-status-top-left {
            display: flex;
            flex: 90%;
            flex-wrap:wrap;
        }

        .payment-status-box 
        {
            width:fit-content;
            border-radius:6px;
            border:1px solid #D9DBDE;
            padding:2px 5px;
            height:30px;
            margin-right:20px;
            gap:15px;
            display:none;
            justify-content:center;
            align-items:center;
        }
        .payment-status-box.active{
            display:flex;
            
        } 
        .payment-status-box p 
        {
            font-size:12px;
            color:#979797;
        }
         .payment-status-box  span 
         {
             background-color:#6788DD;
             padding:3px 5px;
             border-radius:4px;
             font-size:11px;
             color:#ffffff;
             margin-left:8px;
         }
         div.dt-container .dt-length {
            text-transform: capitalize;
         }
        
        #tog_svg {
            cursor: pointer;
        }
    </style>

        <div class="users-management">

                    <div class="payemnt-status">
                      <div class="payemnt-status-top-left d-flex align-items-center justify-content-between">
                          <div>
                               
                                    </div>
 <button class="text-white px-4 py-2 rounded" onclick="downloadTableAsExcel('example', 'user_data.xlsx')" style="
    padding: 5px 10px !important;
    margin-bottom: 25px;
    background: white;
    border:1px solid white;
    color:black !important;
    border-radius: 10px !important;
"> Export
   <img src="IMAGES\Vector (2).svg" alt="">
</button>
                                
                                <div class="payment-status-box " style="margin-left:15px;">
                                    <p class="mb-0">All</p>
                                    <span>425</span>
                                </div>
                                <div class="payment-status-box ">
                                    <p class="mb-0">Returning</p>
                                     <span>425</span>
                                </div>
                                <div class="payment-status-box">
                                    <p class="mb-0">Imported</p>
                                    <span>425</span>
                                </div>
                                <div class="payment-status-box ">
                                    <p class="mb-0">Date</p>
                                    <span>425</span>
                                </div>
                                <div class="payment-status-box" >
                                    <p class="mb-0">User Type</p>
                                     <span>425</span>
                                </div>
                    </div>
                
                <script>
                    document.addEventListener("DOMContentLoaded", function() {
                    var tog_svg1 = document.getElementById('tog_svg1');
                    const divs = document.querySelectorAll(".payment-status-box");
                    tog_svg1.addEventListener('click', function() {
                        divs.forEach(function(di) {
                            di.classList.toggle("active");
                        });
                    });
                });

                </script>
                                

                     <div class="payemnt-status-top ">
                            <div class="search_icon" style="box-shadow: 0px 0px 0px 1px #68718229;width: 30%; height: 32px; margin: 15px 0 20px 0; display: flex; border-radius: 6px; align-items: center; padding: 0 10px; background-color: #FFFFFF;">
                              
                              
                    <span>
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M10.6821 11.7458C9.66576 12.5361 8.38866 13.0067 7.00167 13.0067C3.68704 13.0067 1 10.3189 1 7.00335C1 3.68779 3.68704 1 7.00167 1C10.3163 1 13.0033 3.68779 13.0033 7.00335C13.0033 8.39059 12.533 9.66794 11.743 10.6845L14.7799 13.7186C15.0731 14.0115 15.0734 14.4867 14.7806 14.7799C14.4878 15.0731 14.0128 15.0734 13.7196 14.7805L10.6821 11.7458ZM11.5029 7.00335C11.5029 9.49002 9.48765 11.5059 7.00167 11.5059C4.5157 11.5059 2.50042 9.49002 2.50042 7.00335C2.50042 4.51668 4.5157 2.50084 7.00167 2.50084C9.48765 2.50084 11.5029 4.51668 11.5029 7.00335Z" fill="#868FA0" />
                        </svg>
                    </span>
                    
                   

                    <input type="search" id="custom-search1" placeholder="Search..." aria-controls="example" style="border: none; outline: none; padding: 0 10px; color: #A1A9B8; font-size: 13px; width: 100%;">
                     
                        </div> 
                         
                        </div> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

<table class="display" style="width:100%" id="example">
   
    <thead>
         
        <tr>
            <th>User</th>
            <th>Phone</th>
            <th>Email</th>
            <th>ID</th>
            <th>Wallet</th>
            <th>Status</th>
            <th>Address</th>
            <th>Total Orders</th>
            <th>Total Sales</th>
        </tr>
    </thead>
    <tbody id="searchResults">
        @foreach ($users as $user)
        <tr data-user-id="{{ $user->ID }}">
            <td>{{ $user->name }}</td>
            <td>{{ $user->phone }}</td>
            <td>{{ $user->email }}</td>
            <td>{{ $user->ID }}</td>
            <td>{{ $user->Wallet }}</td>
            <td>
                @if($user->status == 'B')
                    <button style="box-sizing: border-box;
                                            display: flex;
                                            flex-direction: row;
                                            justify-content: center;
                                            align-items: center;
                                            padding: 1.39086px 6.95431px;
                                            width: 80px;
                                            height: 20px;
                                            background: #DBEAFE;
                                            border: 0.695431px solid #93C5FD;
                                            border-radius: 2.78173px;
                                            color: #1E40AF;">Basic</button>
                @elseif($user->status == 'P')
                    <button style="background: #2D2828; color: #F7B261;">Premium</button>
                @elseif($user->status == 'R')
                    <button style="background: #5EAA3A; color: #fff;">Regular</button>
                @elseif($user->status == 'N')
                    <button style="background: #FFD580; color: red;">Vip</button>
                @else
                    New User
                @endif
            </td>
            <td class="address text-lg font-semibold truncate">Loading...</td>
            <td >{{ $user->total_order }}</td>
            <td class="total-sales">Loading...</td>
        </tr>
        @endforeach
    </tbody>
</table>


<script>
    // Function to fetch user orders asynchronously
    async function fetchUserOrders(userId) {
        const ordersUrl = `https://drycleaneo.com/CleaneoUser/api/user-orders/${userId}`;

        try {
            const ordersResponse = await fetch(ordersUrl);

            if (!ordersResponse.ok) {
                throw new Error('Network response was not ok');
            }

            const ordersData = await ordersResponse.json();

            // Calculate total sales for the user
            let totalSales = ordersData.reduce((sum, order) => sum + parseFloat(order.UserTotalCost), 0);

            return {
                totalOrders: ordersData.length || 0,
                totalSales: totalSales.toFixed(2)
            };
        } catch (error) {
            console.error('Fetch error:', error);
            return {
                totalOrders: 'Error',
                totalSales: 'Error'
            };
        }
    }

    // Function to fetch user address asynchronously
    async function fetchAddress(userId) {
        const addressUrl = `https://drycleaneo.com/CleaneoUser/api/showAddress/${userId}`;

        try {
            const addressResponse = await fetch(addressUrl);

            if (!addressResponse.ok) {
                throw new Error('Null');
            }

            const addressData = await addressResponse.json();

            return addressData[0].Caddress || 'Null';
        } catch (error) {
            console.error('Fetch error:', error);
            return 'Null';
        }
    }

    // Function to populate user details in the table
    async function populateUserDetails() {
        const userRows = document.querySelectorAll('#example tbody tr');
        for (const row of userRows) {
            const userId = row.getAttribute('data-user-id');
            const addressCell = row.querySelector('.address');
            const totalOrdersCell = row.querySelector('.total-orders');
            const totalSalesCell = row.querySelector('.total-sales');

            // Check if data is already loaded or error
            if (addressCell.textContent !== 'Loading...' && totalOrdersCell.textContent !== 'Loading...' && totalSalesCell.textContent !== 'Loading...') {
                continue; // Skip fetching if data is already loaded
            }

            // Fetch total orders and total sales
            const userData = await fetchUserOrders(userId);

            // Update total orders and total sales cells
            if (totalOrdersCell) {
                totalOrdersCell.textContent = userData.totalOrders;
            }
            if (totalSalesCell) {
                totalSalesCell.textContent = userData.totalSales;
            }

            // Fetch address
            const address = await fetchAddress(userId);

            // Update address cell within the user row
            if (addressCell) {
                addressCell.textContent = address;
            }
        }
    }

    // Function to download table as Excel
    async function downloadTableAsExcel(tableId, filename = 'user_data.xlsx') {
        // Ensure the table is populated with the latest data
        await populateUserDetails();

        // Retrieve all rows from the table
        let table = document.getElementById(tableId);
        let rows = Array.from(table.querySelectorAll('tbody tr'));

        // Prepare data array for XLSX conversion
        let data = rows.map(row => {
            return [
                row.querySelector('td:nth-child(1)').textContent, // User
                row.querySelector('td:nth-child(2)').textContent, // Phone
                row.querySelector('td:nth-child(3)').textContent, // Email
              
                row.querySelector('td:nth-child(5)').textContent, // Wallet

                row.querySelector('.address').textContent,         // Address
                row.querySelector('.total-orders').textContent,    // Total Orders
                row.querySelector('.total-sales').textContent      // Total Sales
            ];
        });

        // Create a new workbook and sheet with the data
        let wb = XLSX.utils.book_new();
        let ws = XLSX.utils.aoa_to_sheet(data);
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        // Convert workbook to binary string and save as Excel file
        let wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

        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;
        }

        saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), filename);
    }

    // Initial population of user details and set interval to refresh every 5 seconds
    $(document).ready(function () {
        populateUserDetails(); // Populate details initially
        setInterval(populateUserDetails, 5000); // Refresh details every 5 seconds
    });
</script>

</body>
</html>

                    </div>
                 
        </div>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
       
        var searchInput = document.getElementById('custom-search1');
        
        var tableBody = document.getElementById('searchResults');

        searchInput.addEventListener('input', function () {
            var searchText = this.value.toLowerCase();
            var rows = tableBody.getElementsByTagName('tr');

            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                var rowData = row.innerText.toLowerCase();

                if (rowData.includes(searchText)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            }
        });
    });
</script> 
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var searchInputs = document.querySelectorAll('.searchInput'); // Select all elements with class "searchInput-2"

            searchInputs.forEach(function(searchInput) {
                // Add event listener to input for filtering
                searchInput.addEventListener('input', function() {
                    var filter = searchInput.value.toUpperCase();
                    var tables = document.querySelectorAll('.searchResults'); // Select all elements with class "searchResults-two"

                    tables.forEach(function(table) {
                        var rows = table.getElementsByTagName('tr');

                        // Loop through all table rows, and hide those who don't match the search query
                        for (var i = 0; i < rows.length; i++) {
                            var cells = rows[i].getElementsByTagName('td');
                            var found = false;
                            for (var j = 0; j < cells.length; j++) {
                                var cell = cells[j];
                                if (cell) {
                                    var textValue = cell.textContent || cell.innerText;
                                    if (textValue.toUpperCase().indexOf(filter) > -1) {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                            if (found) {
                                rows[i].style.display = '';
                            } else {
                                rows[i].style.display = 'none';
                            }
                        }
                    });
                });
            });
        });
    </script>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        // Get the search input
        var searchInput = document.getElementById('custom-search1');
        // Get the table body
        var tableBody = document.getElementById('searchResults');

        // Add event listener for input changes
        searchInput.addEventListener('input', function () {
            var searchText = this.value.toLowerCase();
            // Get all rows of the table
            var rows = tableBody.getElementsByTagName('tr');

            // Loop through all rows
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                var rowData = row.innerText.toLowerCase();

                // If the row data contains the search text, display the row, otherwise hide it
                if (rowData.includes(searchText)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            }
        });
    });
</script> 
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const selectAllCheckboxes = document.querySelectorAll(".selectAll");

            selectAllCheckboxes.forEach(function(selectAllCheckbox) {
                const checkboxes = selectAllCheckbox.closest('table').querySelectorAll(".check");

                selectAllCheckbox.addEventListener("change", function() {
                    checkboxes.forEach(function(checkbox) {
                        checkbox.checked = selectAllCheckbox.checked;
                    });
                });
            });
        });
    </script>
      <script>
    document.addEventListener('DOMContentLoaded', function () {
        // Get the search input
        var searchInput = document.getElementById('custom-search');
        // Get the table body
        var tableBody = document.getElementById('searchResults');

        // Add event listener for input changes
        searchInput.addEventListener('input', function () {
            var searchText = this.value.toLowerCase();
            // Get all rows of the table
            var rows = tableBody.getElementsByTagName('tr');

            // Loop through all rows
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                var rowData = row.innerText.toLowerCase();

                // If the row data contains the search text, display the row, otherwise hide it
                if (rowData.includes(searchText)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            }
        });
    });
</script>
     <script>
        // new DataTable('#example', {
        //     info: true,
        //     ordering: true,
        //     paging: true,
        //     showNEntries: false
        // });
        // document.getElementByClassName("input.form-control.form-control-sm").placeholder = "Search...";

        // let ck = document.getElementById('globalCheck');
        // ck.addEventListener("click", function() {
        //     let checkboxes = document.querySelectorAll('#example tr input[type="checkbox"]');

        //     checkboxes.forEach(function(checkbox) {
        //         checkbox.checked = true;
        //         console.log(checkbox);
        //     });
        // });
    </script>
    <script>
        new DataTable('#basic', {
            layout: {
                bottomEnd: {
                    paging: {
                        boundaryNumbers: false
                    }
                }
            }
        });
    </script>

    <script src="https://cdn.datatables.net/v/dt/dt-2.0.5/datatables.min.js"></script>
