$(document).ready(function() {
    $('.datatable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[0, 'desc']],
        language: {
            search: '<i class="fas fa-search"></i>',
            lengthMenu: 'Show _MENU_ entries',
            info: 'Showing _START_ to _END_ of _TOTAL_ entries',
            paginate: {previous: '<i class="fas fa-chevron-left"></i>', next: '<i class="fas fa-chevron-right"></i>'},
            emptyTable: 'No data available'
        }
    });

    $(document).on('click', '.btn-delete', function(e) {
        e.preventDefault();
        var url = $(this).data('url');
        var name = $(this).data('name') || 'this record';
        if (confirm('Are you sure you want to delete ' + name + '? This action cannot be undone.')) {
            window.location.href = url;
        }
    });

    $(document).on('click', '.btn-ajax-delete', function(e) {
        e.preventDefault();
        var url = $(this).data('url');
        var name = $(this).data('name') || 'this record';
        if (confirm('Are you sure you want to delete ' + name + '?')) {
            ajaxPost(url, 'csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) {
                    showAlert('success', data.message);
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    showAlert('danger', data.message);
                }
            });
        }
    });

    $(document).on('change', '.toggle-status', function(e) {
        e.preventDefault();
        var url = $(this).data('url');
        ajaxPost(url, 'csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (data.success) {
                showAlert('success', data.message);
                setTimeout(function() { location.reload(); }, 1000);
            } else {
                showAlert('danger', data.message);
            }
        });
    });

    $('form.ajax-form').on('submit', function(e) {
        e.preventDefault();
        var form = $(this);
        var url = form.attr('action');
        var data = new FormData(this);
        data.set('csrf_token', CSRF_TOKEN);

        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            processData: false,
            contentType: false,
            beforeSend: function() {
                form.find('button[type="submit"]').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Saving...');
            },
            success: function(response) {
                if (response.success) {
                    showAlert('success', response.message);
                    if (response.redirect) {
                        setTimeout(function() { window.location.href = response.redirect; }, 1000);
                    }
                } else {
                    showAlert('danger', response.message);
                }
            },
            error: function() {
                showAlert('danger', 'An error occurred. Please try again.');
            },
            complete: function() {
                form.find('button[type="submit"]').prop('disabled', false).html(form.data('submit-text') || '<i class="fas fa-save me-1"></i>Save');
            }
        });
    });

    function autoGenerateSlug(input, target) {
        $(input).on('keyup', function() {
            var val = $(this).val().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
            $(target).val(val);
        });
    }

    autoGenerateSlug('#name', '#slug');

    $(document).on('change', 'input[type="file"][data-preview]', function() {
        var preview = $($(this).data('preview'));
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                preview.attr('src', e.target.result);
            };
            reader.readAsDataURL(this.files[0]);
        }
    });

    $(document).on('click', '[data-bs-toggle="modal"][data-url]', function(e) {
        e.preventDefault();
        var url = $(this).data('url');
        var modal = $($(this).data('bs-target'));
        $.get(url, function(data) {
            modal.find('.modal-body').html(data);
            modal.modal('show');
        });
    });
});
