@extends('layout.app')


@section('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>
                            @canany(['show-package-rate', 'specific_management_services'])

                                <th scope="col" class="text-center">
                                    Package Rate
                                </th>
                            @endcan

                            @canany(['show-package-rate', 'specific_management_services'])
                                @if (checkSettings('ResellerClientOnlineRecharge') == 'enable' &&
                                        checkSettings('setClientPaymentAmountToClient') != 'enable')
                                    <th scope="col" class="text-center">
                                        Client payment amount
                                    </th>
                                @endif
                            @endcan


                            @if (checkSettings('resseller-name-in-package') == 'enable')
                                @can('reseller-show-in-package')
                                    <th scope="col" class="text-center">Reseller Name</th>
                                @endcan
                            @endif
                            @can('ip-pool')
                                <th scope="col" class="text-center">
                                    @if (checkAPI())
                                        Profile Name
                                    @else
                                        Pool Name
                                    @endif
                                </th>
                            @endcan


                            <th scope="col" class="text-center">
                                Create Date
                            </th>
                            @can('pack-commission')
                                <th scope="col">
                                    Commission
                                </th>
                            @endcan
                            <th scope="col" class="text-center">

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

    </div>
@endsection

@section('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"
                }
            ];

            @canany(['show-package-rate', 'specific_management_services'])
                columns.push({
                    "data": "package_rate",
                    "name": "package_rate",
                    "orderable": true,
                    "searchable": true,
                    "className": "text-center"
                });
            @endcan

            @canany(['show-package-rate', 'specific_management_services'])
                @if (checkSettings('ResellerClientOnlineRecharge') == 'enable' &&
                        checkSettings('setClientPaymentAmountToClient') != 'enable')
                    columns.push({
                        "data": "client_payment_amount",
                        "name": "client_payment_amount",
                        "orderable": true,
                        "searchable": true,
                        "className": "text-center"
                    });
                @endif
            @endcan

            @if (checkSettings('resseller-name-in-package') == 'enable')
                @can('reseller-show-in-package')
                    columns.push({
                        "data": "reseller_name",
                        "name": "reseller_name",
                        "orderable": false,
                        "searchable": false,
                        "className": "overflow-auto"
                    });
                @endcan
            @endif

            @can('ip-pool')
                columns.push({
                    "data": "pool_name",
                    "name": "pool_name",
                    "orderable": true,
                    "searchable": true,
                    "className": "text-center"
                });
            @endcan

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

            @can('pack-commission')
                columns.push({
                    "data": "commission",
                    "name": "commission",
                    "orderable": true,
                    "searchable": true,
                    "className": "text-center"
                });
            @endcan

            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": "{{ 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>
@endsection
