<x-app-layout>
    <x-slot name="header">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h2 class="h4 mb-0">Packages</h2>
            </div>
            @can('package.create')
                <button class="btn btn-primary" id="createPackageButton">New Package</button>
            @endcan
        </div>
    </x-slot>

    <div class="card shadow-sm border-0">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="packagesTable" style="width:100%">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>MikroTik</th>
                            <th>Profile</th>
                            <th>Speed</th>
                            <th>Price</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>

    @include('admin.packages.partials.modal')

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const packageModal = new bootstrap.Modal(document.getElementById('packageModal'));

                const table = $('#packagesTable').DataTable({
                    processing: true,
                    serverSide: true,
                    responsive: true,
                    ajax: '{!! route('admin.packages.data') !!}',
                    columns: [
                        {data: 'id', name: 'id'},
                        {data: 'name', name: 'name'},
                        {data: 'mikrotik_name', name: 'mikrotik_name', orderable: false, searchable: false},
                        {data: 'profile_name', name: 'mikrotik_profile_name'},
                        {data: 'net_speed', name: 'net_speed'},
                        {data: 'price', name: 'price'},
                        {data: 'status_label', name: 'status', orderable: false, searchable: false},
                        {data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-end'},
                    ]
                });

                function loadMikrotikPackageProfiles(serverId, selectedName) {
                    const $profileSelect = $('#packageForm select[name="mikrotik_profile_name"]');
                    const $help = $('#mikrotik-profile-help');
                    if (!serverId) {
                        $profileSelect.prop('disabled', true).html('<option value="">Select MikroTik first</option>');
                        $help.text('This can be saved as a software-only package.').removeClass('text-danger').addClass('text-muted');
                        return;
                    }
                    $profileSelect.prop('disabled', true).html('<option>Loading profiles...</option>');
                    $.get('{!! route('admin.packages.mikrotik-profiles') !!}', {mikrotik_id: serverId}, function (response) {
                        $profileSelect.empty();
                        if (response.profiles?.length) {
                            $profileSelect.append('<option value="">Select a connected MikroTik profile</option>');
                            response.profiles.forEach(function (profile) {
                                const option = $('<option>')
                                    .val(profile.name)
                                    .text(profile.name + (profile.rate ? ' (' + profile.rate + ')' : ''))
                                    .attr('data-rate', profile.rate || '')
                                    .attr('data-server-id', response.server.id);
                                $profileSelect.append(option);
                            });
                            $profileSelect.prop('disabled', false);
                            $help.text('Loaded ' + response.profiles.length + ' profiles from ' + (response.server.name || 'MikroTik') + ' (' + response.source + ')').removeClass('text-danger').addClass('text-muted');
                            if (selectedName) {
                                $profileSelect.val(selectedName);
                            }
                        } else {
                            $profileSelect.append('<option value="">No profile found</option>');
                            $profileSelect.prop('disabled', true);
                            $help.text(response.message || 'No connected MikroTik server found.').removeClass('text-muted').addClass('text-danger');
                        }
                    }).fail(function (xhr) {
                        $profileSelect.empty().append('<option value="">Unable to load profiles</option>').prop('disabled', true);
                        $help.text(xhr.responseJSON?.message || 'Unable to load MikroTik profiles.').removeClass('text-muted').addClass('text-danger');
                    });
                }

                $('#createPackageButton').on('click', function () {
                    $('#packageForm')[0].reset();
                    $('#packageForm').attr('action', '{!! route('admin.packages.store') !!}');
                    $('#packageForm').find('input[name=_method]').remove();
                    $('#packageMikrotikServerId').val('');
                    $('#packageModalLabel').text('Create Package');
                    loadMikrotikPackageProfiles('');
                    packageModal.show();
                });

                $(document).on('submit', '#packageForm', function (e) {
                    e.preventDefault();
                    const form = $(this);
                    const action = form.attr('action');
                    const method = form.find('input[name=_method]').val() || 'POST';
                    const data = form.serialize();

                    $.ajax({
                        url: action,
                        method: method,
                        data: data,
                        success: function () {
                            packageModal.hide();
                            table.ajax.reload(null, false);
                            showToast('Package saved successfully.', 'success');
                        },
                        error: function (xhr) {
                            handleFormErrors(xhr, form);
                        }
                    });
                });

                $(document).on('click', '.edit-package', function () {
                    const url = $(this).data('url');

                    $.get(url, function (response) {
                        const packageData = response.data;

                        $('#packageForm').attr('action', response.update_url);
                        if ($('#packageForm').find('input[name=_method]').length === 0) {
                            $('#packageForm').append('<input type="hidden" name="_method" value="PUT">');
                        }

                        $('#packageMikrotikServerId').val(packageData.mikrotik_server_id || '');
                        $('#packageModalLabel').text('Edit Package');
                        $('#packageForm input[name="name"]').val(packageData.name);
                        $('#packageForm input[name="net_speed"]').val(packageData.net_speed);
                        $('#packageForm input[name="price"]').val(packageData.price);
                        $('#packageForm textarea[name="description"]').val(packageData.description);
                        $('#packageForm select[name="status"]').val(packageData.status ? '1' : '0');
                        loadMikrotikPackageProfiles(packageData.mikrotik_server_id, packageData.mikrotik_profile_name);
                        packageModal.show();
                    });
                });

                $(document).on('change', '#packageForm select[name="mikrotik_profile_name"]', function () {
                    const selected = $(this).find('option:selected');
                    const rate = selected.data('rate') || '';
                    if (selected.val()) {
                        $('#packageForm input[name="net_speed"]').val(rate);
                    }
                });

                $(document).on('change', '#packageMikrotikServerId', function () {
                    loadMikrotikPackageProfiles($(this).val(), '');
                });

                $(document).on('click', '.delete-package', function () {
                    if (!confirm('Are you sure you want to delete this package?')) {
                        return;
                    }

                    $.ajax({
                        url: $(this).data('url'),
                        method: 'DELETE',
                        success: function () {
                            table.ajax.reload(null, false);
                            showToast('Package removed successfully.', 'success');
                        }
                    });
                });
            });
        </script>
    @endpush
</x-app-layout>

