<x-app-layout>
    <x-slot name="header">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h2 class="h4 mb-0">Online / Offline Status</h2>
            </div>
            @can('online_status.create')
                <button class="btn btn-primary" id="createStatusButton">Add Status</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="onlineStatusTable" style="width:100%">
                    <thead>
                        <tr>
                            <th>Customer ID</th>
                            <th>Customer Name</th>
                            <th>Status</th>
                            <th>Last Seen</th>
                            <th>Source</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>

    @include('admin.online-statuses.partials.modal')

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const statusModal = new bootstrap.Modal(document.getElementById('statusModal'));
                const table = $('#onlineStatusTable').DataTable({
                    processing: true,
                    serverSide: true,
                    responsive: true,
                    ajax: '{!! route('admin.online-statuses.data') !!}',
                    columns: [
                        { data: 'customer_code', name: 'customer_code', orderable: false, searchable: true },
                        { data: 'customer_name', name: 'customer_name', orderable: false, searchable: true },
                        { data: 'status_label', name: 'online', orderable: false, searchable: false },
                        { data: 'last_seen', name: 'last_seen' },
                        { data: 'source', name: 'source' },
                        { data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-end' },
                    ]
                });

                $('#createStatusButton').on('click', function () {
                    $('#statusForm')[0].reset();
                    $('#statusForm').attr('action', '{!! route('admin.online-statuses.store') !!}');
                    $('#statusForm').find('input[name=_method]').remove();
                    $('#statusModalLabel').text('Add Customer Status');
                    statusModal.show();
                });

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

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

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

                        $('#statusModalLabel').text('Edit Customer Status');
                        $('#statusForm select[name="customer_id"]').val(data.customer_id);
                        $('#statusForm select[name="online"]').val(data.online ? '1' : '0');
                        $('#statusForm input[name="last_seen"]').val(data.last_seen ? data.last_seen.substring(0, 16) : '');
                        $('#statusForm input[name="source"]').val(data.source);
                        $('#statusForm textarea[name="remark"]').val(data.remark);
                        statusModal.show();
                    });
                });

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

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