<x-app-layout>
    <!-- <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;
            margin-left: 1px;
        }

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

        .Dashboard_header header .header_box {
            border-bottom: 1px solid #ccc;

        }

        .Dashboard_header header .header_left_side .second {
            font-size: 14px;
            color: #4D4D4D;
            font-weight: 600;
        }

        .Dashboard_header header {
            border-bottom: none;
        }

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

        .Dashboard_header .user_container {
            margin-top: 100px !important;
        }

        /*.Dashboard_header header .header_left_side .second*/
        /*{*/
        /*    margin-right:15px;*/
        /*}*/
        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: -50px;
        }

        table.dataTable {
            margin-top: -20px !important;
        }

        #custom-search::-ms-clear {
            display: none;
        }

        #custom-search::-webkit-search-cancel-button {
            display: none;
        }

        div.dt-container .dt-input {
            border: 1px solid #68718229 !important;
            border-radius: 6px !important;
            outline: none !important;
        }

        table.dataTable thead th,
        table.dataTable tfoot th {
            color: #1D2433 !important;
            background-color: #F1F3F9 !important;
        }

        table.dataTable.display>tbody>tr:nth-child(even)>* {
            background-color: #F8F9FC !important;
        }

        table.dataTable.stripe>tbody>tr:nth-child(odd)>*,
        table.dataTable.display>tbody>tr:nth-child(odd)>*,
        table.dataTable.stripe>tbody>tr:nth-child(even)>*,
        table.dataTable.display>tbody>tr:nth-child(even)>*,
        table.dataTable>thead>tr>th,
        table.dataTable>thead>tr>td {
            border: none !important;
            box-shadow: none !important;
        }

        #tog_svg {
            cursor: pointer;
        }

         .delivery-combine1
    {
        display: flex;
        width:auto;
        height:auto;
        margin-top:-30px;
    }
    .add-delivery
    {
        font-size: 20px;
        font-weight: 700;
        line-height: 24px;
        text-align: left;
        color: #FFFFFF;
        background: #75B1E8;
        width: 227px;
        height: 51px;
        border-radius: 8px;
        padding-top:13px;
        padding-left:15px;
    }
    .delivery-request
    {
        font-size: 20px;
        font-weight: 700;
        line-height: 24px;
        text-align: left;
        color: #FFFFFF;
        background: #75B1E8;
        width: 280px;
        height: 51px;
        border-radius: 8px;
        padding-top:13px;
        padding-left:15px;
        margin-left: 30px;
    }
    </style>

    <header>
        <div class="d-flex justify-content-between header_box me-4">
            <h3>User Management/<span style="font-size:20px;color:#4D4D4D" id="heading-short">Total User</span></h3>
            <div class="header_left_side">

                <!--<span class="second" style="margin-right:18px"><svg xmlns="http://www.w3.org/2000/svg"  width="22" height="22" viewBox="0 0 24 24">-->
                <!--        <path fill="currentColor" d="M16.59 9H15V4c0-.55-.45-1-1-1h-4c-.55 0-1 .45-1 1v5H7.41c-.89 0-1.34 1.08-.71 1.71l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.63-.63.19-1.71-.7-1.71M5 19c0 .55.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1H6c-.55 0-1 .45-1 1" />-->
                <!--    </svg> Download</span>-->
            </div>
        </div>
    </header>

    <div class="user_container">
        <div class="users-management" style="margin-left:2px;">
<div class="delivery-combine1"  style="margin-top:40px;">
                    <a href="{{route('user_registration')}}"><div class="add-delivery">Add User</div></a>
                    <!--<a href="{{route('delivery_import')}}"><div class="add-delivery" style="margin-left: 30px">Import Agent File</div></a>-->
                    <!-- <a href="{{route('delivery_approve_request')}}"><div class="delivery-request">Approve Delivery Request</div></a> -->
                </div>
           
    <div class="users-add-top" style="margin-top:40px; margin-left:-5px;">
 
        <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active toggle-users" id="pills-home-tab" data-plan-id="all"
                        type="button" role="tab" aria-controls="pills-home" aria-selected="false">
                    <div class="users-total">
                        <div class="users-count-top">
                            <p class="txt">Total Users</p>
                        </div>
                        <h6>{{ $allUsers->count() }}</h6>
                    </div>
                </button>
            </li>
            @foreach ($subscriptionPlans as $plan)
                <li class="nav-item" role="presentation">
                    <button class="nav-link toggle-users" data-plan-id="{{ $plan->id }}"
                            type="button" role="tab" aria-controls="pills-basic" aria-selected="false">
                        <div class="users-total">
                            <div class="users-count-top">
                                <p class="txt">{{ $plan->name }} Users</p>
                            </div>
                            <h6>{{ $subscriptionUserCounts[$plan->id]->user_count ?? 0 }}</h6>
                        </div>
                    </button>
                </li>
            @endforeach
        </ul>
    </div>

    <!------- Tabs Content ----->
   <div class="tab-content" id="pills-tabContent">
    <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">
        <div id="all-users-table" class="mb-4">
            <h4>All Users</h4>
            <!-- Custom Search Input -->
            <input type="text" id="search-all-users" placeholder="Search..." class="form-control mb-2">
            <!-- Export Button -->
            <button id="export-all-users" class="btn btn-primary mb-3">Export</button>
            <table id="usersTable" class="table table-bordered display">
                <thead class="table-light">
                    <tr>
                        <th>User ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Wallet</th>
                        <th>Order Count</th>
                          <th>Total Sales</th>
                           <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($allUsers as $user)
                        <tr>
                            <td>{{ $user->user_id }}</td>
                            <td>{{ $user->name }}</td>
                            <td>{{ $user->email }}</td>
                            <td>{{ $user->phone_number ?? 'N/A' }}</td>
                            <td>{{ $user->wallet ?? 'N/A' }}</td>
                            <td>{{ $user->order_count }}</td>
                            <td>{{ $user->total_cost }}</td>
                             <td>   <a href="{{ route('usermanagement_userdetail', $user->user_id) }}">View Details</a></td>
                        

                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        @foreach ($subscriptionPlans as $plan)
            <div id="users-table-{{ $plan->id }}" class="users-table mb-4">
                <h4>All {{ $plan->name }} Users</h4>
                <!-- Custom Search Input -->
                <input type="text" id="search-users-{{ $plan->id }}" placeholder="Search..." class="form-control mb-2">
                <!-- Export Button -->
                <button id="export-users-{{ $plan->id }}" class="btn btn-primary mb-3">Export</button>
                <table class="table table-bordered display" id="data-table-{{ $plan->id }}">
                    <thead class="table-light">
                        <tr>
                            <th>User ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Wallet</th>
                            <th>Order Count</th>
                            <th>Total Sales</th>
                             <th>Action</th>
                            
                        </tr>
                    </thead>
                    <tbody>
                        @php $usersForPlan = $usersBySubscription[$plan->id] ?? []; @endphp
                        @if (count($usersForPlan) > 0)
                            @foreach ($usersForPlan as $user)
                                <tr>
                                    <td>{{ $user->user_id }}</td>
                                    <td>{{ $user->name }}</td>
                                    <td>{{ $user->email }}</td>
                                    <td>{{ $user->phone_number ?? 'N/A' }}</td>
                                    <td>{{ $user->wallet ?? 'N/A' }}</td>
                                    <td>{{ $user->order_count }}</td>
                                    <td>{{ $user->total_cost }}</td>
                                    <td><a href="{{ route('usermanagement_userdetail', $user->user_id) }}">View Details</a>
</td>
                                    
                                </tr>
                            @endforeach
                        @else
                           
                        @endif
                    </tbody>
                </table>
            </div>
        @endforeach
    </div>
</div>

</div>

<script>
$(document).ready(function() {
    // Initialize DataTable for all users with ordering enabled only for the last column
    let allUsersTable = $('#usersTable').DataTable({
        "ordering": true, // Enable ordering globally
    "autoWidth": false,
    "order": [[6, "desc"]], // Set default order by "Total Sales" column in descending order
    
    });
    
    // Initialize DataTables for each subscription plan with ordering on the last column only
    let planTables = {};
    @foreach ($subscriptionPlans as $plan)
        planTables[{{ $plan->id }}] = $('#data-table-{{ $plan->id }}').DataTable({
            "ordering": true,
        "autoWidth": false,
        "order": [[6, "desc"]], // Default order by "Total Sales" column in descending order
        
        });
    @endforeach

    // Custom Search for All Users
    $('#search-all-users').on('keyup', function() {
        allUsersTable.search(this.value).draw();
    });

    // Custom Search for Subscription Plan Users
    @foreach ($subscriptionPlans as $plan)
        $('#search-users-{{ $plan->id }}').on('keyup', function() {
            planTables[{{ $plan->id }}].search(this.value).draw();
        });
    @endforeach

    // Export functionality
    function exportTableToCSV(filename, tableId) {
        let csv = [];
        let rows = document.querySelectorAll(tableId + ' tr');

        for (let i = 0; i < rows.length; i++) {
            let row = [];
            let cols = rows[i].querySelectorAll('td, th');
            for (let j = 0; j < cols.length; j++) {
                row.push(cols[j].innerText);
            }
            csv.push(row.join(','));        
        }

        // Create a downloadable CSV file
        let csvFile = new Blob([csv.join('\n')], { type: 'text/csv' });
        let downloadLink = document.createElement('a');
        downloadLink.download = filename;
        downloadLink.href = window.URL.createObjectURL(csvFile);
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
        downloadLink.click();
    }

    // Event listeners for Export buttons
    $('#export-all-users').on('click', function() {
        exportTableToCSV('all_users.csv', '#usersTable');
    });

    @foreach ($subscriptionPlans as $plan)
        $('#export-users-{{ $plan->id }}').on('click', function() {
            exportTableToCSV('{{ $plan->name }}_users.csv', '#data-table-{{ $plan->id }}');
        });
    @endforeach

    // Show and hide tables based on the selected tab
    $('.nav-link').click(function() {
        const planId = $(this).data('plan-id');
        $('.users-table').hide();
        $('#all-users-table').toggle(planId === "all");
        $('#users-table-' + planId).toggle(planId !== "all");

        // Refresh DataTable width calculation
        if (planId !== "all") {
            planTables[planId].columns.adjust();
        }

        // Update active tab styling
        $('.nav-link').removeClass('active');
        $(this).addClass('active');
    });
});

</script>



<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<style>
    .users-table {
        display: none; /* Initially hide all subscription tables */
    }
</style>

        <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() {
                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>
            const navItems = document.querySelectorAll('.nav-item');

            navItems.forEach(navItem => {
                navItem.addEventListener('click', function() {
                    let txtElement = this.querySelector('.txt');

                    let txtValue = txtElement.textContent.trim();

                    document.getElementById('heading-short').innerHTML = txtValue;
                });
            });
        </script>


</x-app-layout>
