@php($permissions = userPermissions())
<div id="result" style="min-height:500px; position: relative;">
    <div class="mb-3 text-right">
        <button type="button" id="exportExcelBtn" class="btn btn-success btn-sm">
            <i class="fa fa-file-excel"></i> Export to Excel
        </button>
    </div>
    <div class="table-responsive" style="max-height: calc(100vh - 250px); overflow-y: auto;">
        <table class="table table-striped table-bordered" id="dataTable">
            <thead>
                <tr style="background:#78716C !important; color:white;">
                    <th name="userid">userId</th>
                    <th name="clients_name" style="width: 180px !important;">Name</th>
                    <th name="contact_no">Contact</th>
                    <th name="clients_status">Status</th>
                    <th name="package_name">Package</th>
                    <th name="popname">Pop</th>
                    <th name="reseller_name">Reseller</th>
                    <th name="expire_date">Expire Date</th>
                    <th name="down_bandwidth">Down Load</th>
                    <th name="up_bandwidth">Up Load</th>
                    <th name="total">Total</th>
                    <th name="bandwidth_limit">Extra Limit</th>
                </tr>
            </thead>
            <tbody>
                {{-- Data will be loaded via server-side processing --}}
            </tbody>
        </table>
    </div>
</div>

<style>
    /* sidebar scroller start*/
    .overflow-custome {
        overflow-y: scroll;
    }

    .overflow-custome::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 6px rgba(56, 15, 15, 0.3);
        background-color: #f5f5f5;
    }

    .overflow-custome::-webkit-scrollbar {
        width: 6px;
        background-color: #f5f5f5;
    }

    .overflow-custome::-webkit-scrollbar-thumb {
        background-color: #330a0a;
        border: 2px solid #555555;
    }

    /* sidebar scroller end*/

    /* DataTables custom styling */
    #dataTable_wrapper .dataTables_filter input {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 5px 10px;
    }

    #dataTable_wrapper .dataTables_length select {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 5px;
    }

    /* Sticky table header */
    #result {
        position: relative;
    }

    #result .table-responsive {
        position: relative;
        max-height: calc(100vh - 250px);
        overflow-y: auto;
        overflow-x: auto;
    }

    /* Sticky header - works when parent has overflow */
    #dataTable thead {
        position: sticky;
        top: 0;
        z-index: 1000;
        background-color: #78716C !important;
    }

    #dataTable thead th {
        position: sticky;
        top: 0;
        background-color: #78716C !important;
        color: white !important;
        z-index: 1001;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        border-bottom: 2px solid rgba(255, 255, 255, 0.2);
    }

    /* Ensure header row maintains background */
    #dataTable thead tr {
        background-color: #78716C !important;
        position: sticky;
        top: 0;
    }
</style>

@if (request()->path() == 'admin/clients')
    <style>
        /* Sorting styles for Expire column */
        .table th a {
            color: white !important;
            text-decoration: none !important;
            display: inline-block;
        }

        .table th a:hover {
            color: #ffc107 !important;
            text-decoration: none !important;
        }

        .table th a i {
            margin-left: 5px;
            font-size: 12px;
        }

        .table th a .fa-sort {
            opacity: 0.5;
        }

        .table th a:hover .fa-sort {
            opacity: 1;
        }
    </style>
@endif

<script>
    (function() {
        function initDataTable() {
            // Destroy existing DataTable instance if it exists
            if ($.fn.DataTable && $.fn.DataTable.isDataTable('#dataTable')) {
                $('#dataTable').DataTable().destroy();
            }

            // Get filter parameters from parent container
            var container = $('#customer_list_body');
            var packageId = container.data('package-id') || '';
            var reseller = container.data('reseller') || 'all';
            var pop = container.data('pop') || 'all';
            var minimumUsage = container.data('minimum-usage') || '';

            // Check if table exists and DataTable is available
            if ($('#dataTable').length && $.fn.DataTable) {
                $('#dataTable').DataTable({
                    "processing": true,
                    "serverSide": true,
                    "responsive": true,
                    "pageLength": 100,
                    "lengthMenu": [
                        [10, 25, 50, 100, 200, 500],
                        [10, 25, 50, 100, 200, 500]
                    ],
                    "order": [
                        [10, "desc"]
                    ],
                    "ajax": {
                        "url": "{{ route('get_all_customer_by_package_datatable') }}",
                        "type": "GET",
                        "data": function(d) {
                            // Read values dynamically on each request
                            var container = $('#customer_list_body');
                            var packageId = container.data('package-id');
                            var reseller =$('#reseller').val();
                            var pop = $('#pop').val();
                            var minimumUsage = container.data('minimum-usage');

                            // Only set if value exists, otherwise send null/undefined
                            if (packageId !== undefined && packageId !== null && packageId !== '') {
                                d.package_id = packageId;
                            }
                            if (reseller !== undefined && reseller !== null && reseller !== '') {
                                d.reseller = reseller;
                            }
                            if (pop !== undefined && pop !== null && pop !== '') {
                                d.pop = pop;
                            }
                            if (minimumUsage !== undefined && minimumUsage !== null && minimumUsage !==
                                '') {
                                d.minimum_usage = minimumUsage;
                            }
                        },
                        "error": function(xhr, error, code) {
                            console.log('Error:', error, code);
                            toastr.error('Error loading data. Please refresh the page.');
                        }
                    },
                    "columns": [{
                            "data": "userid",
                            "name": "userid"
                        },
                        {
                            "data": "clients_name",
                            "name": "clients_name"
                        },
                        {
                            "data": "contact_no",
                            "name": "contact_no"
                        },
                        {
                            "data": "clients_status",
                            "name": "clients_status"
                        },
                        {
                            "data": "package_name",
                            "name": "package_name"
                        },
                        {
                            "data": "popname",
                            "name": "popname"
                        },
                        {
                            "data": "reseller_name",
                            "name": "reseller_name"
                        },
                        {
                            "data": "expire_date",
                            "name": "expire_date"
                        },
                        {
                            "data": "down_bandwidth",
                            "name": "down_bandwidth",
                            "render": function(data, type, row) {
                                if (type === 'display') {
                                    var mb = parseFloat(data);
                                    if (mb === 0 || isNaN(mb)) return '0 MB';
                                    if (mb >= 1024) {
                                        return (mb / 1024).toFixed(2) + ' GB';
                                    }
                                    return mb.toFixed(2) + ' MB';
                                }
                                return data;
                            }
                        },
                        {
                            "data": "up_bandwidth",
                            "name": "up_bandwidth",
                            "render": function(data, type, row) {
                                if (type === 'display') {
                                    var mb = parseFloat(data);
                                    if (mb === 0 || isNaN(mb)) return '0 MB';
                                    if (mb >= 1024) {
                                        return (mb / 1024).toFixed(2) + ' GB';
                                    }
                                    return mb.toFixed(2) + ' MB';
                                }
                                return data;
                            }
                        },
                        {
                            "data": "total",
                            "name": "total",
                            "render": function(data, type, row) {
                                if (type === 'display') {
                                    var mb = parseFloat(data);
                                    if (mb === 0 || isNaN(mb)) return '0 MB';
                                    if (mb >= 1024) {
                                        return (mb / 1024).toFixed(2) + ' GB';
                                    }
                                    return mb.toFixed(2) + ' MB';
                                }
                                return data;
                            }
                        },
                        {
                            "data": "bandwidth_limit",
                            "name": "bandwidth_limit"
                        }
                    ],
                    "language": {
                        "search": "Search:",
                        "lengthMenu": "Show _MENU_ entries",
                        "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                        "infoEmpty": "Showing 0 to 0 of 0 entries",
                        "infoFiltered": "(filtered from _MAX_ total entries)",
                        "processing": "Loading clients...",
                        "paginate": {
                            "first": "First",
                            "last": "Last",
                            "next": "Next",
                            "previous": "Previous"
                        }
                    },
                    "dom": "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
                        "<'row'<'col-sm-12'tr>>" +
                        "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>"
                });
            }
        }

        // Try to initialize immediately
        if (typeof jQuery !== 'undefined' && typeof $.fn.DataTable !== 'undefined') {
            initDataTable();
        } else {
            // Wait for jQuery and DataTable to be available
            $(document).ready(function() {
                setTimeout(initDataTable, 100);
            });
        }

        // Export to Excel button handler
        $(document).on('click', '#exportExcelBtn', function() {
            var container = $('#customer_list_body');
            var packageId = container.data('package-id') || '';
            var reseller = $('#reseller').val();
            var pop = $('#pop').val();
            var minimumUsage = $('#minimum_usage').val();

            // Build export URL with parameters
            var exportUrl = '{{ route('export_clients_by_package') }}';
            var params = [];

            if (packageId) params.push('package_id=' + encodeURIComponent(packageId));
            if (reseller && reseller !== 'all') params.push('reseller=' + encodeURIComponent(reseller));
            if (pop && pop !== 'all') params.push('pop=' + encodeURIComponent(pop));
            if (minimumUsage) params.push('minimum_usage=' + encodeURIComponent(minimumUsage));

            if (params.length > 0) {
                exportUrl += '?' + params.join('&');
            }

            // Show loading
            $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Exporting...');

            // Create a temporary link to download the file
            var link = document.createElement('a');
            link.href = exportUrl;
            link.download = '';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            // Reset button after a delay
            setTimeout(function() {
                $('#exportExcelBtn').prop('disabled', false).html(
                    '<i class="fa fa-file-excel"></i> Export to Excel');
            }, 2000);
        });
    })();
</script>
