/**
 * Event Summary Certificate Actions JavaScript
 * 
 * Handles certificate actions for the Event Summary page
 */

(function($) {
    'use strict';
    
    // Initialize certificate actions when document is ready
    $(document).ready(function() {
        // Set up certificate action modal
        initCertificateModal();
        
        // Set up certificate action handlers
        initCertificateActions();
    });
    
    // Initialize certificate modal
    function initCertificateModal() {
        // Check if modal exists, create it if not
        if ($('#hvac-certificate-modal').length === 0) {
            var modalHtml = `
                <div id="hvac-certificate-modal" class="hvac-modal">
                    <div class="hvac-modal-content">
                        <span class="hvac-modal-close">&times;</span>
                        <div class="hvac-modal-body">
                            <iframe id="hvac-certificate-preview" style="width: 100%; height: 500px;"></iframe>
                        </div>
                    </div>
                </div>
            `;
            $('body').append(modalHtml);
            
            // Add modal close functionality
            $('.hvac-modal-close').on('click', function() {
                $('#hvac-certificate-modal').hide();
            });
            
            // Close modal when clicking outside
            $(window).on('click', function(event) {
                if ($(event.target).is('#hvac-certificate-modal')) {
                    $('#hvac-certificate-modal').hide();
                }
            });
        }
    }
    
    // Initialize certificate action handlers
    function initCertificateActions() {
        // View certificate action
        $('.hvac-view-certificate').on('click', function(e) {
            e.preventDefault();
            
            var eventId = $(this).data('event');
            var attendeeId = $(this).data('attendee');
            
            // Show modal with loading indicator
            var modal = $('#hvac-certificate-modal');
            var iframe = $('#hvac-certificate-preview');
            iframe.attr('src', '');
            
            var loadingHtml = '<div class="hvac-loading">Loading certificate...</div>';
            $('.hvac-modal-body').append(loadingHtml);
            modal.show();
            
            // Fetch certificate URL via AJAX
            $.ajax({
                url: hvacEventSummary.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'hvac_get_certificate_url',
                    event_id: eventId,
                    attendee_id: attendeeId,
                    nonce: hvacEventSummary.certificateNonce
                },
                success: function(response) {
                    $('.hvac-loading').remove();
                    
                    if (response.success && response.data.url) {
                        iframe.attr('src', response.data.url);
                    } else {
                        $('.hvac-modal-body').append('<div class="hvac-error">Error: ' + (response.data.message || 'Could not load certificate') + '</div>');
                    }
                },
                error: function() {
                    $('.hvac-loading').remove();
                    $('.hvac-modal-body').append('<div class="hvac-error">Error: Could not connect to the server</div>');
                }
            });
        });
        
        // Email certificate action
        $('.hvac-email-certificate').on('click', function(e) {
            e.preventDefault();
            
            var eventId = $(this).data('event');
            var attendeeId = $(this).data('attendee');
            var button = $(this);
            
            if (confirm('Send this certificate to the attendee via email?')) {
                // Show loading state
                button.text('Sending...').addClass('hvac-loading');
                
                // Send email via AJAX
                $.ajax({
                    url: hvacEventSummary.ajaxUrl,
                    method: 'POST',
                    data: {
                        action: 'hvac_email_certificate',
                        event_id: eventId,
                        attendee_id: attendeeId,
                        nonce: hvacEventSummary.certificateNonce
                    },
                    success: function(response) {
                        button.removeClass('hvac-loading');
                        
                        if (response.success) {
                            button.closest('td').find('.certificate-status').text('Sent');
                            alert('Certificate was sent successfully.');
                        } else {
                            button.text('Email');
                            alert('Error: ' + (response.data.message || 'Failed to send certificate.'));
                        }
                    },
                    error: function() {
                        button.removeClass('hvac-loading').text('Email');
                        alert('Error: Could not connect to the server.');
                    }
                });
            }
        });
        
        // Revoke certificate action
        $('.hvac-revoke-certificate').on('click', function(e) {
            e.preventDefault();
            
            var eventId = $(this).data('event');
            var attendeeId = $(this).data('attendee');
            var button = $(this);
            var cell = button.closest('td');
            
            // Ask for a reason
            var reason = prompt('Please enter a reason for revoking this certificate:');
            
            if (reason !== null) { // Null means the user clicked Cancel
                // Show loading state
                button.text('Revoking...').addClass('hvac-loading');
                
                // Revoke certificate via AJAX
                $.ajax({
                    url: hvacEventSummary.ajaxUrl,
                    method: 'POST',
                    data: {
                        action: 'hvac_revoke_certificate',
                        event_id: eventId,
                        attendee_id: attendeeId,
                        reason: reason,
                        nonce: hvacEventSummary.certificateNonce
                    },
                    success: function(response) {
                        button.removeClass('hvac-loading');
                        
                        if (response.success) {
                            // Update cell content to show revoked status
                            cell.html('Revoked');
                            alert('Certificate was revoked successfully.');
                        } else {
                            button.text('Revoke');
                            alert('Error: ' + (response.data.message || 'Failed to revoke certificate.'));
                        }
                    },
                    error: function() {
                        button.removeClass('hvac-loading').text('Revoke');
                        alert('Error: Could not connect to the server.');
                    }
                });
            }
        });
    }
})(jQuery);