<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h2 class="h4 mb-0">MikroTik Routers</h2>
            </div>
            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('mikrotik.create')): ?>
                <button class="btn btn-primary" id="createMikrotikButton">Add MikroTik</button>
            <?php endif; ?>
        </div>
     <?php $__env->endSlot(); ?>

    <div class="card shadow-sm border-0">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="mikrotiksTable" style="width:100%">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>IP Address</th>
                            <th>API Port</th>
                            <th>Username</th>
                            <th>SSL</th>
                            <th>Status</th>
                            <th>Connection Status</th>
                            <th>Response Time</th>
                            <th>Last Checked</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>

    <?php echo $__env->make('admin.mikrotiks.partials.modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

    <?php $__env->startPush('scripts'); ?>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const mikrotikModal = new bootstrap.Modal(document.getElementById('mikrotikModal'));
                const updatePortCommand = function () {
                    const port = Math.min(65535, Math.max(1, parseInt($('#mikrotikApiPort').val(), 10) || 8728));
                    $('#mikrotikPortCommand').text('/ip service set [find name=api] disabled=no port=' + port);
                };
                const table = $('#mikrotiksTable').DataTable({
                    processing: true,
                    serverSide: true,
                    responsive: true,
                    ajax: '<?php echo route('admin.mikrotiks.data'); ?>',
                    columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'ip_address', name: 'ip_address' },
                        { data: 'api_port', name: 'api_port' },
                        { data: 'username', name: 'username' },
                        { data: 'ssl_label', name: 'ssl_enabled', orderable: false, searchable: false },
                        { data: 'status_label', name: 'status', orderable: false, searchable: false },
                        { data: 'connection_status', name: 'connected', orderable: false, searchable: false },
                        { data: 'response_time', name: 'response_time_ms', orderable: false, searchable: false },
                        { data: 'last_checked', name: 'last_checked_at', orderable: false, searchable: false },
                        { data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-end' },
                    ]
                });

                setInterval(function () {
                    table.ajax.reload(null, false);
                }, 30000);

                function clearConnectionResult() {
                    $('#mikrotikConnectionResult').removeClass('alert-success alert-danger').addClass('d-none').text('');
                    $('#connection-tested').val('0');
                }

                function showConnectionResult(message, success) {
                    $('#mikrotikConnectionResult')
                        .removeClass('d-none alert-success alert-danger')
                        .addClass(success ? 'alert-success' : 'alert-danger')
                        .text(message);
                    $('#connection-tested').val(success ? '1' : '0');
                }

                function testMikrotikConnection(callback) {
                    clearConnectionResult();
                    const form = $('#mikrotikForm');
                    const data = form.serialize();
                    const button = $('#checkMikrotikConnectionButton');
                    button.prop('disabled', true).find('.button-label').addClass('d-none');
                    button.find('.button-loader').removeClass('d-none');

                    $.ajax({
                        url: '<?php echo route('admin.mikrotiks.connection_check'); ?>',
                        method: 'POST',
                        data: data,
                        success: function (response) {
                            showConnectionResult('✅ Connected to MikroTik API.', true);
                            callback(true);
                        },
                        error: function (xhr) {
                            const message = xhr.responseJSON?.message || xhr.responseJSON?.data?.message || 'Connection failed. Check server details.';
                            showConnectionResult('🔴 ' + message, false);
                            callback(false);
                        },
                        complete: function () {
                            button.prop('disabled', false).find('.button-label').removeClass('d-none');
                            button.find('.button-loader').addClass('d-none');
                        }
                    });
                }

                $('#createMikrotikButton').on('click', function () {
                    $('#mikrotikForm')[0].reset();
                    $('#mikrotikForm').attr('action', '<?php echo route('admin.mikrotiks.store'); ?>');
                    $('#mikrotikForm').find('input[name=_method]').remove();
                    $('#mikrotikId').val('');
                    $('#mikrotikForm select[name="ssl_enabled"]').val('0');
                    $('#mikrotikForm select[name="status"]').val('1');
                    $('#mikrotikForm input[name="is_default"]').prop('checked', false);
                    $('#mikrotikPassword').prop('required', true).val('').attr('placeholder', 'Enter API password');
                    $('#mikrotikPasswordHelp').text('Required for a new server.');
                    clearConnectionResult();
                    $('#mikrotikModalLabel').text('Add MikroTik Router');
                    mikrotikModal.show();
                });

                $(document).on('submit', '#mikrotikForm', function (e) {
                    e.preventDefault();
                    const form = $(this);
                    // The save URL is calculated from the selected router. This
                    // prevents a connection-test endpoint from ever becoming the
                    // target of an edit (PUT) request.
                    const routerId = String($('#mikrotikId').val() || '').trim();
                    const action = routerId
                        ? '<?php echo e(url('admin/mikrotiks')); ?>/' + encodeURIComponent(routerId)
                        : '<?php echo route('admin.mikrotiks.store'); ?>';
                    const proceed = function () {
                        const data = form.serialize();
                        const saveButton = $('#saveMikrotikButton');
                        saveButton.prop('disabled', true).find('.button-label').addClass('d-none');
                        saveButton.find('.button-loader').removeClass('d-none');

                        $.ajax({
                            url: action,
                            method: 'POST',
                            data: data,
                            success: function () {
                                mikrotikModal.hide();
                                table.ajax.reload(null, false);
                                showToast('Server saved. Connection verification is running in the background.', 'success');
                            },
                            error: function (xhr) {
                                handleFormErrors(xhr, form);
                            },
                            complete: function () {
                                saveButton.prop('disabled', false).find('.button-label').removeClass('d-none');
                                saveButton.find('.button-loader').addClass('d-none');
                            }
                        });
                    };

                    if ($('#connection-tested').val() !== '1') {
                        testMikrotikConnection(function (success) {
                            if (success) {
                                proceed();
                            } else {
                                Swal.fire({
                                    title: 'Connection unavailable',
                                    text: 'MikroTik connection could not be verified. Save the server as disconnected?',
                                    icon: 'warning',
                                    showCancelButton: true,
                                    confirmButtonText: 'Save anyway',
                                    cancelButtonText: 'Cancel',
                                }).then(function (result) {
                                    if (result.isConfirmed) {
                                        proceed();
                                    }
                                });
                            }
                        });
                    } else {
                        proceed();
                    }
                });

                $('#checkMikrotikConnectionButton').on('click', function () {
                    testMikrotikConnection(function () {
                        // no-op, result rendered inside the modal
                    });
                });

                $(document).on('input', '#mikrotikApiPort', updatePortCommand);
                $('#copyMikrotikPortCommand').on('click', async function () {
                    updatePortCommand();
                    try {
                        await navigator.clipboard.writeText($('#mikrotikPortCommand').text());
                        showToast('RouterOS command copied.', 'success');
                    } catch (error) {
                        showToast('Select the command and copy it manually.', 'warning');
                    }
                });

                $('#toggleMikrotikPassword').on('click', function () {
                    const input = document.getElementById('mikrotikPassword');
                    input.type = input.type === 'password' ? 'text' : 'password';
                    $(this).find('i').toggleClass('fa-eye fa-eye-slash');
                });

                $(document).on('change', '#mikrotikForm input, #mikrotikForm select, #mikrotikForm textarea', function () {
                    if ($(this).attr('name') !== '_method') {
                        $('#connection-tested').val('0');
                        $('#mikrotikConnectionResult').addClass('d-none');
                    }
                });

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

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

                        $('#mikrotikId').val(data.id);
                        $('#mikrotikModalLabel').text('Edit MikroTik Router');
                        $('#mikrotikForm input[name="name"]').val(data.name);
                        $('#mikrotikForm input[name="ip_address"]').val(data.ip_address);
                        $('#mikrotikForm input[name="api_port"]').val(data.api_port);
                        $('#mikrotikForm input[name="username"]').val(data.username);
                        $('#mikrotikForm input[name="password"]').val('');
                        $('#mikrotikPassword').prop('required', false).attr('placeholder', 'Leave blank to keep current password');
                        $('#mikrotikPasswordHelp').text('Leave blank to keep the existing API password.');
                        $('#mikrotikForm select[name="ssl_enabled"]').val(data.ssl_enabled ? '1' : '0');
                        $('#mikrotikForm select[name="status"]').val(data.status ? '1' : '0');
                        $('#mikrotikForm input[name="is_default"]').prop('checked', data.is_default ? true : false);
                        $('#mikrotikForm textarea[name="remarks"]').val(data.remarks);
                        clearConnectionResult();
                        updatePortCommand();
                        mikrotikModal.show();
                    }).fail(function (xhr) {
                        showToast(xhr.responseJSON?.message || 'MikroTik server details could not be loaded.', 'error');
                    });
                });

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

                    $.ajax({
                        url: $(this).data('url'),
                        method: 'DELETE',
                        success: function () {
                            table.ajax.reload(null, false);
                            showToast('Server removed successfully.', 'success');
                        }
                    });
                });

                $(document).on('click', '.toggle-mikrotik', function () {
                    const button = $(this);
                    const enabled = Number(button.data('enabled')) === 1;
                    const action = enabled ? 'enable' : 'disable';

                    Swal.fire({
                        title: (enabled ? 'Enable' : 'Disable') + ' MikroTik?',
                        text: enabled
                            ? 'Background connection and sync will start for ' + button.data('name') + '.'
                            : 'Background sync will stop. No configuration will be deleted from the router.',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: enabled ? 'Yes, enable' : 'Yes, disable',
                        cancelButtonText: 'Cancel',
                        confirmButtonColor: enabled ? '#198754' : '#dc3545',
                    }).then(function (result) {
                        if (!result.isConfirmed) return;

                        button.prop('disabled', true);
                        $.ajax({
                            url: button.data('url'),
                            method: 'PATCH',
                            data: { enabled: enabled ? 1 : 0 },
                            success: function (response) {
                                showToast(response.message || ('Server ' + action + 'd successfully.'), 'success');
                                table.ajax.reload(null, false);
                            },
                            error: function (xhr) {
                                showToast(xhr.responseJSON?.message || ('Server could not be ' + action + 'd.'), 'error');
                            },
                            complete: function () {
                                button.prop('disabled', false);
                            }
                        });
                    });
                });
            });
        </script>
    <?php $__env->stopPush(); ?>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php /**PATH D:\herd\billing\laravel-app\resources\views\admin\mikrotiks\index.blade.php ENDPATH**/ ?>