<x-app-layout>
    <x-slot name="header">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h2 class="h4 mb-0">SMS Configuration</h2>
            </div>
        <div>
            @can('sms.view')
                <a href="{{ route('admin.sms-templates.index') }}" class="btn btn-outline-secondary me-2">SMS Templates</a>
            @endcan
            @can('sms.create')
                <button class="btn btn-primary" id="createSmsGatewayButton">New Gateway</button>
            @endcan
        </div>
        </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="smsGatewaysTable" style="width:100%">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Provider</th>
                            <th>API URL</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>

    @include('admin.sms-gateways.partials.modal')

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const gatewayModal = new bootstrap.Modal(document.getElementById('smsGatewayModal'));
                const table = $('#smsGatewaysTable').DataTable({
                    processing: true,
                    serverSide: true,
                    responsive: true,
                    ajax: '{!! route('admin.sms-gateways.data') !!}',
                    columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'provider', name: 'provider' },
                        { data: 'api_url', name: 'api_url', orderable: false, searchable: false },
                        { data: 'status_label', name: 'status', orderable: false, searchable: false },
                        { data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-end' },
                    ]
                });

                $('#createSmsGatewayButton').on('click', function () {
                    $('#smsGatewayForm')[0].reset();
                    $('#smsGatewayForm').attr('action', '{!! route('admin.sms-gateways.store') !!}');
                    $('#smsGatewayForm').find('input[name=_method]').remove();
                    $('#smsGatewayModalLabel').text('Create SMS Gateway');
                    gatewayModal.show();
                });

                $(document).on('submit', '#smsGatewayForm', 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 () {
                            gatewayModal.hide();
                            table.ajax.reload(null, false);
                            showToast('SMS gateway saved successfully.', 'success');
                        },
                        error: function (xhr) {
                            handleFormErrors(xhr, form);
                        }
                    });
                });

                $(document).on('click', '.edit-gateway', function () {
                    const url = $(this).data('url');
                    $.get(url, function (response) {
                        const data = response.data;
                        $('#smsGatewayForm').attr('action', response.update_url);
                        if ($('#smsGatewayForm').find('input[name=_method]').length === 0) {
                            $('#smsGatewayForm').append('<input type="hidden" name="_method" value="PUT">');
                        }

                        $('#smsGatewayModalLabel').text('Edit SMS Gateway');
                        $('#smsGatewayForm input[name="name"]').val(data.name);
                        $('#smsGatewayForm select[name="provider"]').val(data.provider);
                        $('#smsGatewayForm input[name="api_url"]').val(data.api_url);
                        $('#smsGatewayForm input[name="api_key"]').val(data.api_key);
                        $('#smsGatewayForm input[name="sender_id"]').val(data.sender_id);
                        $('#smsGatewayForm select[name="status"]').val(data.status ? '1' : '0');
                        $('#smsGatewayForm textarea[name="settings"]').val(JSON.stringify(data.settings || {}, null, 2));
                        gatewayModal.show();
                    });
                });

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

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