<x-app-layout>
    <x-slot name="header">
        <div class="d-flex align-items-center justify-content-between">
            <h2 class="h4 mb-0">Customers</h2>
            @can('customer.create')
                <div class="d-flex flex-wrap gap-2">
                    <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#customerImportModal"><i class="fas fa-file-csv"></i> Import CSV</button>
                    <a href="{{ route('admin.customers.create') }}" class="btn btn-primary">Add Customer</a>
                </div>
            @endcan
        </div>
    </x-slot>

    @if(session('customer_import'))
        @php($import = session('customer_import'))
        <div class="alert alert-info d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-2">
            <div><strong>CSV Import:</strong> {{ $import['created'] }} customer added, {{ $import['packages_created'] }} package created, {{ $import['skipped'] }} skipped, {{ $import['failed'] }} failed.</div>
            <span>{{ $import['mikrotik_message'] }}</span>
        </div>
        @if(!empty($import['messages']))
            <details class="alert alert-warning"><summary class="fw-semibold">View skipped/error details</summary><ul class="mb-0 mt-2">@foreach(array_slice($import['messages'], 0, 50) as $message)<li>{{ $message }}</li>@endforeach</ul></details>
        @endif
    @endif

    <div class="card shadow-sm border-0">
        <div class="card-body">
            @can('customer.delete')
                <div class="d-flex align-items-center gap-2 mb-3">
                    <button type="button" id="bulkDeleteCustomers" class="btn btn-sm btn-outline-danger" disabled><i class="fas fa-trash-alt me-1"></i> Delete Selected</button>
                    <span id="selectedCustomerCount" class="small text-muted">0 selected</span>
                </div>
            @endcan
            <div class="table-responsive">
                <table id="customersTable" class="table table-striped table-hover align-middle" style="width:100%">
                    <thead>
                        <tr>
                            <th class="text-center"><input type="checkbox" id="selectAllCustomers" class="form-check-input" aria-label="Select all customers on this page"></th>
                            <th>Connection</th>
                            <th>Customer Code</th>
                            <th>Name</th>
                            <th>Phone</th>
                            <th>PPPoE Username</th>
                            <th>Package</th>
                            <th>Monthly Bill</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>

    @can('customer.create')
        <div class="modal fade" id="customerImportModal" tabindex="-1" aria-labelledby="customerImportModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <form action="{{ route('admin.customers.import') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="modal-header"><h5 class="modal-title" id="customerImportModalLabel">Customer CSV Import</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>
                        <div class="modal-body">
                            <div class="alert alert-light border">Download the template first and keep the column format unchanged. If a new package name is found, the software will create the package automatically.</div>
                            <div class="mb-3"><a class="btn btn-sm btn-outline-success" href="{{ route('admin.customers.import.template') }}"><i class="fas fa-download"></i> CSV Template Download</a></div>
                            <div class="mb-3"><label class="form-label" for="customerCsvFile">CSV File <span class="text-danger">*</span></label><input class="form-control @error('csv_file') is-invalid @enderror" id="customerCsvFile" name="csv_file" type="file" accept=".csv,text/csv" required><div class="form-text">Maximum 5 MB and 5,000 customers.</div>@error('csv_file')<div class="invalid-feedback">{{ $message }}</div>@enderror</div>
                            <div><label class="form-label" for="importMikrotikId">MikroTik Server</label><select class="form-select" id="importMikrotikId" name="mikrotik_id"><option value="">Software only</option>@foreach($mikrotiks as $mikrotik)<option value="{{ $mikrotik->id }}" @selected(old('mikrotik_id') == $mikrotik->id)>{{ $mikrotik->name }} — {{ $mikrotik->connected ? 'Connected' : 'Disconnected' }}</option>@endforeach</select><div class="form-text">If connected, PPPoE upload will run in the background. If disconnected, no router request will be sent.</div></div>
                        </div>
                        <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary"><i class="fas fa-upload"></i> Import Customers</button></div>
                    </form>
                </div>
            </div>
        </div>
    @endcan

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const customerTable = $('#customersTable').DataTable({
                    dom: '<"row align-items-center g-2 mb-2"<"col-md-3"l><"col-md-5 text-center text-md-start"B><"col-md-4 d-flex justify-content-md-end"f>><"row dt-layout-row"<"col-sm-12"tr>><"row"<"col-md-5"i><"col-md-7 text-md-end"p>>',
                    serverSide: true,
                    processing: true,
                    responsive: true,
                    autoWidth: false,
                    buttons: window.getDefaultDataTableButtons ? window.getDefaultDataTableButtons('Customers') : [],
                    ajax: {
                        url: '{!! route('admin.customers.data') !!}',
                        data: function (data) {
                            data.q = @json(request('q'));
                        }
                    },
                    columns: [
                        { data: 'select_box', name: 'select_box', orderable: false, searchable: false, className: 'text-center' },
                        { data: 'online_status', name: 'online_status', orderable: false, searchable: false },
                        { data: 'customer_code',orderable: true,
                            render: function(data, type, row) {
                                return `<a class="btn btn-sm btn-outline-success fw-semibold text-nowrap" title="Open Customer Ledger" href="{{ url('admin/customers') }}/${row.id}/ledger">${data}</a>`
                            }
                        },
                        { data: 'name', name: 'name' },
                        { data: 'contact_phone', name: 'contact_phone' },
                        { data: 'ip_address', name: 'ip_address' },
                        { data: 'package_name', name: 'package.name', orderable: false, searchable: false },
                        { data: 'monthly_bill', name: 'monthly_bill' },
                        { data: 'status_label', name: 'status', orderable: false, searchable: false },
                        { data: 'actions', name: 'actions', orderable: false, searchable: false },
                    ],
                    order: [[2, 'desc']],
                });

                const selectedCustomers = new Set();
                const bulkButton = document.getElementById('bulkDeleteCustomers');
                const selectedCount = document.getElementById('selectedCustomerCount');
                const selectAll = document.getElementById('selectAllCustomers');

                function updateBulkControls() {
                    if (bulkButton) bulkButton.disabled = selectedCustomers.size === 0;
                    if (selectedCount) selectedCount.textContent = `${selectedCustomers.size} selected`;
                    const visibleChecks = [...document.querySelectorAll('.customer-row-check')];
                    if (selectAll) {
                        selectAll.checked = visibleChecks.length > 0 && visibleChecks.every(check => selectedCustomers.has(check.value));
                        selectAll.indeterminate = visibleChecks.some(check => selectedCustomers.has(check.value)) && !selectAll.checked;
                    }
                }

                $('#customersTable').on('change', '.customer-row-check', function () {
                    this.checked ? selectedCustomers.add(this.value) : selectedCustomers.delete(this.value);
                    updateBulkControls();
                });

                selectAll?.addEventListener('change', function () {
                    document.querySelectorAll('.customer-row-check').forEach(check => {
                        check.checked = selectAll.checked;
                        selectAll.checked ? selectedCustomers.add(check.value) : selectedCustomers.delete(check.value);
                    });
                    updateBulkControls();
                });

                customerTable.on('draw', function () {
                    document.querySelectorAll('.customer-row-check').forEach(check => check.checked = selectedCustomers.has(check.value));
                    updateBulkControls();
                });

                bulkButton?.addEventListener('click', function () {
                    if (!selectedCustomers.size) return;
                    Swal.fire({
                        title: `Delete ${selectedCustomers.size} customer(s)?`,
                        text: 'They will move to Delete Log and assigned MikroTik secrets will be removed in the background.',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, delete',
                        confirmButtonColor: '#dc3545'
                    }).then(result => {
                        if (!result.isConfirmed) return;
                        bulkButton.disabled = true;
                        axios.delete(@json(route('admin.customers.bulk-destroy')), { data: { customer_ids: [...selectedCustomers] } })
                            .then(response => {
                                selectedCustomers.clear();
                                customerTable.ajax.reload(null, false);
                                window.showToast?.(`${response.data.deleted} customer(s) moved to Delete Log.`, 'success');
                            })
                            .catch(error => {
                                window.showToast?.(error.response?.data?.message || 'Unable to delete selected customers.', 'error');
                            })
                            .finally(() => { bulkButton.disabled = false; updateBulkControls(); });
                    });
                });

                $('#customersTable').on('click', '.delete-customer', function () {
                    const customerId = $(this).data('id');

                    const button = $(this);
                    Swal.fire({
                        title: 'Delete customer?',
                        text: 'Customer will move to Delete Log and the MikroTik secret will be removed in the background.',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, delete',
                        confirmButtonColor: '#dc3545'
                    }).then(function (result) {
                        if (!result.isConfirmed) return;
                        button.prop('disabled', true);
                        axios.delete(`{{ url('admin/customers') }}/${customerId}`)
                            .then(function (response) {
                                customerTable.ajax.reload(null, false);
                                showToast(response.data.message || 'Customer moved to Delete Log.', 'success');
                            })
                            .catch(function (error) {
                                button.prop('disabled', false);
                                showToast(error.response?.data?.message || 'Customer could not be deleted.', 'error');
                            });
                    });
                });

            });
        </script>
    @endpush
</x-app-layout>
