<?php $__env->startSection('content'); ?>
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table id="dataTable" class="display">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="text-center">
                                ID
                            </th>
                            <th scope="col" class="text-center">
                                Package Name
                            </th>
                            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->any(['show-package-rate', 'specific_management_services'])): ?>

                                <th scope="col" class="text-center">
                                    Package Rate
                                </th>
                            <?php endif; ?>

                            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->any(['show-package-rate', 'specific_management_services'])): ?>
                                <?php if(checkSettings('ResellerClientOnlineRecharge') == 'enable' && checkSettings('setClientPaymentAmountToClient') != 'enable' ): ?>
                                    <th scope="col" class="text-center">
                                        Client payment amount
                                    </th>
                                <?php endif; ?>
                            <?php endif; ?>


                            <?php if(checkSettings('resseller-name-in-package') == 'enable'): ?>
                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('reseller-show-in-package')): ?>
                                    <th scope="col" class="text-center">Reseller Name</th>
                                <?php endif; ?>
                            <?php endif; ?>
                            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('ip-pool')): ?>
                                <th scope="col" class="text-center">
                                    <?php if(checkAPI()): ?>
                                        Profile Name
                                    <?php else: ?>
                                        Pool Name
                                    <?php endif; ?>
                                </th>
                            <?php endif; ?>


                            <th scope="col" class="text-center">
                                Create Date
                            </th>
                            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('pack-commission')): ?>
                                <th scope="col">
                                    Commission
                                </th>
                            <?php endif; ?>
                            <th scope="col" class="text-center">

                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be loaded via AJAX -->
                    </tbody>
                </table>
            </div>
        </div>

    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('ajax'); ?>
<script>
    $(document).ready(function() {
        // Destroy existing DataTable instance if it exists
        if ($.fn.DataTable.isDataTable('#dataTable')) {
            $('#dataTable').DataTable().destroy();
        }

        // Build columns array dynamically
        var columns = [
            { "data": "id", "name": "id", "orderable": true, "searchable": true, "className": "text-center" },
            { "data": "package_name", "name": "package_name", "orderable": true, "searchable": true, "className": "text-center" }
        ];

        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->any(['show-package-rate', 'specific_management_services'])): ?>
            columns.push({ "data": "package_rate", "name": "package_rate", "orderable": true, "searchable": true, "className": "text-center" });
        <?php endif; ?>

        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->any(['show-package-rate', 'specific_management_services'])): ?>
            <?php if(checkSettings('ResellerClientOnlineRecharge') == 'enable' && checkSettings('setClientPaymentAmountToClient') != 'enable'): ?>
                columns.push({ "data": "client_payment_amount", "name": "client_payment_amount", "orderable": true, "searchable": true, "className": "text-center" });
            <?php endif; ?>
        <?php endif; ?>

        <?php if(checkSettings('resseller-name-in-package') == 'enable'): ?>
            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('reseller-show-in-package')): ?>
                columns.push({ "data": "reseller_name", "name": "reseller_name", "orderable": false, "searchable": false, "className": "overflow-auto" });
            <?php endif; ?>
        <?php endif; ?>

        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('ip-pool')): ?>
            columns.push({ "data": "pool_name", "name": "pool_name", "orderable": true, "searchable": true, "className": "text-center" });
        <?php endif; ?>

        columns.push({ "data": "created_at", "name": "created_at", "orderable": true, "searchable": false, "className": "text-center" });

        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('pack-commission')): ?>
            columns.push({ "data": "commission", "name": "commission", "orderable": true, "searchable": true, "className": "text-center" });
        <?php endif; ?>

        columns.push({ "data": "action", "name": "action", "orderable": false, "searchable": false, "className": "text-center" });

        // Initialize server-side DataTables
        var table = $('#dataTable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "<?php echo e(route('packages.data')); ?>",
                "type": "GET",
                "error": function(xhr, error, code) {
                    console.log('Error:', error, code);
                    alert('Error loading data. Please refresh the page.');
                }
            },
            "columns": columns,
            "order": [[0, "desc"]],
            "pageLength": 100,
            "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
            "searchDelay": 500,
            "language": {
                "processing": "Loading packages...",
                "emptyTable": "No packages found",
                "zeroRecords": "No matching packages found"
            },
            "dom": '<"top"lf>rt<"bottom"ip><"clear">',
            "drawCallback": function(settings) {
                // Re-initialize any tooltips or other plugins if needed
            }
        });

        // Handle delete form submission with DataTables refresh
        $(document).on('submit', 'form.delete-package-form', function(e) {
            e.preventDefault();
            if (!confirm('are you want to delete the package?')) {
                return;
            }

            var form = $(this);
            var url = form.attr('action');
            var method = form.find('input[name="_method"]').val();
            var token = form.find('input[name="_token"]').val();

            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: {
                    _method: method,
                    _token: token
                },
                success: function(response) {
                    table.ajax.reload(null, false); // Reload table without resetting pagination
                    var msg = (response && response.message) ? response.message : 'Packages Delete successfull';
                    if (window.toastr) {
                        toastr.success(msg, 'Success');
                    } else {
                        console.log('SUCCESS:', msg);
                    }
                },
                error: function(xhr) {
                    table.ajax.reload(null, false);
                    var msg = 'Error deleting package';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        msg = xhr.responseJSON.message;
                    }
                    if (window.toastr) {
                        toastr.error(msg, 'Error');
                    } else {
                        console.error('ERROR:', msg);
                    }
                }
            });
        });
    });
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layout.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /var/www/html/crp/radius-circle/resources/views/packages/index.blade.php ENDPATH**/ ?>