<x-app-layout>
    @php
        $isSoftware = ($mode ?? 'software') === 'software';
        $pageTitle = $isSoftware ? 'PPPoE Software Unmatching' : 'PPPoE MikroTik Unmatching';
        $bulkDirection = $isSoftware ? 'upload' : 'import';
    @endphp
    <x-slot name="header"><div class="d-flex align-items-center justify-content-between"><h2 class="h4 mb-0">{{ $pageTitle }}</h2></div></x-slot>

    <div class="card shadow-sm border-0">
        <div class="card-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                <h3 class="h6 mb-0">{{ $isSoftware ? 'Software customers missing from MikroTik' : 'MikroTik secrets missing from software' }}</h3>
                @can('mikrotik.update')
                    <button type="button" id="syncAllButton" class="btn {{ $isSoftware ? 'btn-primary' : 'btn-success' }}">
                        <i class="fas fa-plus me-1"></i> {{ $isSoftware ? 'Upload All to MikroTik' : 'Import All to Software' }}
                    </button>
                @endcan
            </div>
            <div class="table-responsive">
                <table class="table table-hover" id="mikrotikPppUnmatchingTable" style="width:100%">
                    <thead><tr><th>Customer ID</th><th>Customer Name</th><th>PPPoE Username</th><th>Router</th><th>Router IP</th><th>Action</th></tr></thead>
                </table>
            </div>
        </div>
    </div>

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const mode = @json($mode ?? 'software');
                const table = $('#mikrotikPppUnmatchingTable').DataTable({
                    processing: true, serverSide: false, deferRender: true, responsive: true,
                    ajax: {
                        url: @json(route('admin.mikrotik.pppoe-unmatching.data')),
                        data: function (data) { data.mode = mode; },
                        dataSrc: function (json) { return Array.isArray(json?.data) ? json.data : []; },
                        error: function (xhr) {
                            $('#mikrotikPppUnmatchingTable_processing').hide();
                            window.showToast?.(xhr.responseJSON?.message || 'Unmatching list could not be loaded.', 'error');
                        }
                    },
                    columns: [
                        { data: 'customer_code', name: 'customer_code', defaultContent: '—' },
                        { data: 'customer_name', name: 'customer_name', defaultContent: '—' },
                        { data: 'identifier', name: 'identifier' },
                        { data: 'router_name', name: 'router_name' },
                        { data: 'router_ip', name: 'router_ip' },
                        { data: 'sync_action', name: 'sync_action', orderable: false, searchable: false },
                    ]
                });
                const bulkUrl = mode === 'software' ? @json(route('admin.mikrotik.pppoe-unmatching.upload-customers')) : @json(route('admin.mikrotik.pppoe-unmatching.import-secrets'));

                $('#syncAllButton').on('click', async function () {
                    const button = this;
                    const confirmation = await Swal.fire({title: mode === 'software' ? 'Upload all unmatched customers?' : 'Import all unmatched secrets?', icon: 'question', showCancelButton: true, confirmButtonText: 'Yes, continue'});
                    if (!confirmation.isConfirmed) return;
                    button.disabled = true;
                    try {
                        const response = await axios.post(bulkUrl);
                        const result = response.data.data;
                        await Swal.fire('Completed', `Created: ${result.created} | Skipped: ${result.skipped} | Failed: ${result.failed}`, result.failed ? 'warning' : 'success');
                        table.ajax.reload(null, false);
                    } catch (error) {
                        Swal.fire('Failed', error.response?.data?.message || 'Sync could not be completed.', 'error');
                    } finally { button.disabled = false; }
                });

                $('#mikrotikPppUnmatchingTable').on('click', '.individual-sync', async function () {
                    const button = this;
                    const payload = mode === 'software'
                        ? {customer_id: button.dataset.customerId}
                        : {router_id: button.dataset.routerId, identifier: button.dataset.identifier};
                    button.disabled = true;
                    try {
                        const response = await axios.post(button.dataset.url, payload);
                        window.showToast?.(response.data.message, 'success');
                        setTimeout(() => table.ajax.reload(null, false), mode === 'software' ? 1200 : 100);
                    } catch (error) {
                        window.showToast?.(error.response?.data?.message || 'Individual sync failed.', 'error');
                    } finally { button.disabled = false; }
                });

                window.setInterval(() => table.ajax.reload(null, false), 30000);
            });
        </script>
    @endpush
</x-app-layout>
