/**
 * Document Generator for Easy Invoice
 * Handles PDF and HTML invoice generation
 */
(function($) {
    'use strict';

    // Document Generator object
    window.EasyInvoiceDocument = {
        // Default settings
        settings: {
            invoiceId: 0,
            ajaxUrl: '',
            nonce: '',
            format: 'pdf' // pdf or html
        },

        // Initialize the document generator
        init: function() {
    
            
            // Load settings if available from localized data
            if (typeof easyInvoiceDocument !== 'undefined') {
                this.settings.invoiceId = easyInvoiceDocument.invoiceId || 0;
                this.settings.ajaxUrl = easyInvoiceDocument.ajaxUrl || '';
                this.settings.nonce = easyInvoiceDocument.nonce || '';
                this.settings.format = easyInvoiceDocument.format || 'pdf';
            }
            
            // Set up event handlers
            this.setupEventHandlers();
        },

        // Set up event handlers for document-related elements
        setupEventHandlers: function() {
            var self = this;
            
            // Generate PDF button
            $('#generate_pdf').on('click', function(e) {
                e.preventDefault();
                self.generateDocument('pdf');
            });
            
            // Generate HTML button
            $('#generate_html').on('click', function(e) {
                e.preventDefault();
                self.generateDocument('html');
            });
            
            // Send invoice button
            $('#send_invoice').on('click', function(e) {
                e.preventDefault();
                self.sendInvoice();
            });
            
            // Preview invoice button
            $('#preview_invoice').on('click', function(e) {
                e.preventDefault();
                self.previewInvoice();
            });
        },

        // Generate document (PDF or HTML)
        generateDocument: function(format) {
            var self = this;
            var invoiceId = this.settings.invoiceId;
            
            // If no invoice ID, try to get it from the form
            if (!invoiceId) {
                invoiceId = $('#invoice_id').val();
            }
            
            // If still no invoice ID, show error
            if (!invoiceId) {
                this.showMessage('Please save the invoice before generating a document.', 'error');
                return;
            }
            
            // Show loading message
            this.showMessage('Generating ' + format.toUpperCase() + ' document...', 'info');
            
            // Make AJAX request to generate document
            $.ajax({
                url: this.settings.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'easy_invoice_generate_document',
                    invoice_id: invoiceId,
                    format: format,
                    nonce: this.settings.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Show success message
                        self.showMessage(response.data.message, 'success');
                        
                        // If download URL is provided, open it in a new tab
                        if (response.data.download_url) {
                            window.open(response.data.download_url, '_blank');
                        }
                    } else {
                        // Show error message
                        self.showMessage(response.data.message || 'An error occurred while generating the document.', 'error');
                    }
                },
                error: function() {
                    // Show error message
                    self.showMessage('An error occurred while generating the document.', 'error');
                }
            });
        },

        // Send invoice to client via email
        sendInvoice: function() {
            var self = this;
            var invoiceId = this.settings.invoiceId;
            
            // If no invoice ID, try to get it from the form
            if (!invoiceId) {
                invoiceId = $('#invoice_id').val();
            }
            
            // If still no invoice ID, show error
            if (!invoiceId) {
                this.showMessage('Please save the invoice before sending it.', 'error');
                return;
            }
            
            // Show confirmation dialog
            if (!confirm('Are you sure you want to send this invoice to the client?')) {
                return;
            }
            
            // Show loading message
            this.showMessage('Sending invoice...', 'info');
            
            // Make AJAX request to send invoice
            $.ajax({
                url: this.settings.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'easy_invoice_send_invoice',
                    invoice_id: invoiceId,
                    nonce: this.settings.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Show success message
                        self.showMessage(response.data.message, 'success');
                    } else {
                        // Show error message
                        self.showMessage(response.data.message || 'An error occurred while sending the invoice.', 'error');
                    }
                },
                error: function() {
                    // Show error message
                    self.showMessage('An error occurred while sending the invoice.', 'error');
                }
            });
        },

        // Preview invoice in a modal
        previewInvoice: function() {
            var self = this;
            var invoiceId = this.settings.invoiceId;
            
            // If no invoice ID, try to get it from the form
            if (!invoiceId) {
                invoiceId = $('#invoice_id').val();
            }
            
            // If still no invoice ID, show error
            if (!invoiceId) {
                this.showMessage('Please save the invoice before previewing it.', 'error');
                return;
            }
            
            // Show loading message
            this.showMessage('Loading preview...', 'info');
            
            // Make AJAX request to get invoice preview
            $.ajax({
                url: this.settings.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'easy_invoice_preview_invoice',
                    invoice_id: invoiceId,
                    nonce: this.settings.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Show preview in modal
                        self.showPreviewModal(response.data.html);
                        
                        // Clear the info message
                        self.clearMessage();
                    } else {
                        // Show error message
                        self.showMessage(response.data.message || 'An error occurred while loading the preview.', 'error');
                    }
                },
                error: function() {
                    // Show error message
                    self.showMessage('An error occurred while loading the preview.', 'error');
                }
            });
        },

        // Show preview modal
        showPreviewModal: function(html) {
            // Create modal if it doesn't exist
            if ($('#invoice-preview-modal').length === 0) {
                $('body').append(
                    '<div id="invoice-preview-modal" class="modal">' +
                    '   <div class="modal-content">' +
                    '       <span class="close">&times;</span>' +
                    '       <div id="invoice-preview-content"></div>' +
                    '   </div>' +
                    '</div>'
                );
                
                // Close modal when clicking on close button
                $('#invoice-preview-modal .close').on('click', function() {
                    $('#invoice-preview-modal').hide();
                });
                
                // Close modal when clicking outside the content
                $(window).on('click', function(e) {
                    if ($(e.target).is('#invoice-preview-modal')) {
                        $('#invoice-preview-modal').hide();
                    }
                });
            }
            
            // Set the content
            $('#invoice-preview-content').html(html);
            
            // Show the modal
            $('#invoice-preview-modal').show();
        },

        // Show message
        showMessage: function(message, type) {
            // Create message container if it doesn't exist
            if ($('#invoice-message').length === 0) {
                $('.easy-invoice-container').prepend('<div id="invoice-message"></div>');
            }
            
            // Set message class based on type
            var messageClass = 'notice';
            switch (type) {
                case 'success':
                    messageClass = 'notice notice-success';
                    break;
                case 'error':
                    messageClass = 'notice notice-error';
                    break;
                case 'warning':
                    messageClass = 'notice notice-warning';
                    break;
                case 'info':
                    messageClass = 'notice notice-info';
                    break;
            }
            
            // Set the message
            $('#invoice-message').html('<p class="' + messageClass + '">' + message + '</p>');
            
            // Auto-clear success and info messages after 5 seconds
            if (type === 'success' || type === 'info') {
                setTimeout(function() {
                    $('#invoice-message p').fadeOut(500, function() {
                        $(this).remove();
                    });
                }, 5000);
            }
        },

        // Clear message
        clearMessage: function() {
            $('#invoice-message').empty();
        }
    };

    // Initialize document generator when document is ready
    $(document).ready(function() {
        EasyInvoiceDocument.init();
    });

})(jQuery); 