/**
 * Handles all AJAX interactions for the Tickets admin page.
 * This is the final, corrected version with all listeners.
 * @param {object} jQuery - jQuery
 */
jQuery(function(jQuery) {

    // The static wrappers for the page and the modal container
    var pageWrapper = jQuery('#em-tickets-page-wrapper');
    var modalContainer = jQuery('#modal-ticket-manager');

    // If the main wrapper doesn't exist, do nothing.
    if (!pageWrapper.length) {
        return;
    }

    // --- EVENT LISTENERS ---

    // 1. Listen for clicks on the main "Add New Ticket" button
    pageWrapper.on('click', '#add_new_ticket_btn', function(e) {
        e.preventDefault();
        jQuery.post(em_ticket_ajax_object.ajax_url, {
            action: 'em_get_add_ticket_form',
            nonce: em_ticket_ajax_object.add_form_nonce
        }).done(function(response) {
            if (response.success) {
                // Add backdrop if it doesn't exist
                if (!jQuery('.modal-backdrop').length) {
                    jQuery('body').append('<div class="modal-backdrop fade in"></div>');
                }
                // Show modal with proper classes
                modalContainer.html(response.data.html).addClass('in').show();
                jQuery('body').addClass('modal-open');
            } else {
                alert('Error: ' + (response.data.message || 'Could not load form.'));
            }
        });
    });

    // 2. Listen for the SUBMISSION of the "Add New Ticket" form INSIDE the modal
    modalContainer.on('submit', '#em_add_ticket_form', function(e) {
        e.preventDefault();
        var formData = jQuery(this).serialize();
        
        jQuery.post(em_ticket_ajax_object.ajax_url, {
            action: 'em_add_ticket',
            nonce: em_ticket_ajax_object.add_nonce,
            form_data: formData
        }).done(function(response) {
            if (response.success) {
                // Easiest way to see the new ticket is to reload the page
                location.reload(); 
            } else {
                alert('Error: ' + (response.data.message || 'Could not add ticket.'));
            }
        });
    });
    
    // 3. Listen for clicks on the "Delete" button for any ticket
    pageWrapper.on('click', '.ticket-delete-btn', function() {
        if (!confirm('Are you sure you want to delete this ticket?')) {
            return;
        }
        var ticket_id = jQuery(this).data('id');
        var row = jQuery('#record-' + ticket_id);
        
        jQuery.post(em_ticket_ajax_object.ajax_url, {
            action: 'em_delete_ticket',
            nonce: em_ticket_ajax_object.delete_nonce,
            id: ticket_id
        }).done(function(response) {
            if (response.success) {
                row.fadeOut(500, function() { jQuery(this).remove(); });
            }
        });
    });

    // 4. Listen for clicks on the "View" or "Edit" buttons
    pageWrapper.on('click', '.ticket-view-btn, .ticket-edit-btn', function(e) {
        e.preventDefault();
        var ticket_id = jQuery(this).data('id');
        var action_type = jQuery(this).hasClass('ticket-edit-btn') ? 'em_get_ticket_edit_form' : 'em_get_ticket_view';

        jQuery.post(em_ticket_ajax_object.ajax_url, {
            action: action_type,
            nonce: em_ticket_ajax_object.edit_nonce, // edit_nonce can be used for view too
            id: ticket_id
        }).done(function(response) {
            if (response.success) {
                // Add backdrop if it doesn't exist
                if (!jQuery('.modal-backdrop').length) {
                    jQuery('body').append('<div class="modal-backdrop fade in"></div>');
                }
                // Show modal with proper classes
                modalContainer.html(response.data.html).addClass('in').show();
                jQuery('body').addClass('modal-open');
            }
        });
    });
    
    // 5. Listen for the SUBMISSION of the "Update Ticket" form INSIDE the modal
    modalContainer.on('submit', '#em_ticket_update_form', function(e) {
        e.preventDefault();
        var formData = jQuery(this).serialize();
        var ticket_id = jQuery(this).find('#em_edit_ticket_id').val();

        jQuery.post(em_ticket_ajax_object.ajax_url, {
            action: 'em_update_ticket',
            nonce: em_ticket_ajax_object.update_nonce,
            id: ticket_id,
            form_data: formData
        }).done(function(response) {
            if (response.success) {
                location.reload();
            }
        });
    });

    // 6. Generic listener to close any modal
    jQuery('body').on('click', '.modal .close, .modal .close-modal, .modal-backdrop', function() {
        jQuery('.modal').removeClass('in').hide().html('');
        jQuery('.modal-backdrop').remove();
        jQuery('body').removeClass('modal-open');
    });

});