/**
 * Extra Config JavaScript
 * Handles admin interface interactions
 *
 * @package AIAutoTool
 * @since 1.0.0
 */

(function($) {
    'use strict';
    
    /**
     * Extra Config Admin Handler
     */
    const ExtraConfigAdmin = {
        
        /**
         * Initialize
         */
        init: function() {
            this.bindEvents();
        },
        
        /**
         * Bind events
         */
        bindEvents: function() {
            // Database cleanup actions
            $('.aiautotool-db-action').on('click', this.handleDatabaseAction);
            
            // Export/Import settings (if buttons exist)
            $('#aiautotool-export-settings').on('click', this.handleExport);
            $('#aiautotool-import-settings').on('click', this.handleImport);
            $('#aiautotool-reset-settings').on('click', this.handleReset);
            
            // Form validation
            $('#aiautotool-extra-config-form').on('submit', this.handleFormSubmit);
        },
        
        /**
         * Handle database action
         */
        handleDatabaseAction: function(e) {
            e.preventDefault();
            
            const $button = $(this);
            const action = $button.data('action');
            const $result = $('#aiautotool-db-action-result');
            
            // Get confirmation message
            let confirmMessage = '';
            switch (action) {
                case 'revisions':
                    confirmMessage = aiautotoolExtraConfig.strings.confirm_delete_revisions;
                    break;
                case 'drafts':
                    confirmMessage = aiautotoolExtraConfig.strings.confirm_delete_drafts;
                    break;
                case 'trash':
                    confirmMessage = aiautotoolExtraConfig.strings.confirm_delete_trash;
                    break;
            }
            
            // Confirm action
            if (!confirm(confirmMessage)) {
                return;
            }
            
            // Disable button and show loading
            $button.prop('disabled', true);
            const originalText = $button.html();
            $button.html('<i class="fa-solid fa-spinner fa-spin"></i> ' + aiautotoolExtraConfig.strings.deleting);
            
            // Clear previous results
            $result.html('');
            
            // Send AJAX request
            $.ajax({
                url: aiautotoolExtraConfig.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'aiautotool_extra_config_delete_' + action,
                    nonce: aiautotoolExtraConfig.nonce
                },
                success: function(response) {
                    $button.prop('disabled', false);
                    $button.html(originalText);
                    
                    if (response.success) {
                        $result.html('<div class="notice notice-success is-dismissible"><p>' + response.data.message + '</p></div>');
                    } else {
                        $result.html('<div class="notice notice-error is-dismissible"><p>' + response.data.message + '</p></div>');
                    }
                    
                    // Auto-hide message after 5 seconds
                    setTimeout(function() {
                        $result.find('.notice').fadeOut(function() {
                            $(this).remove();
                        });
                    }, 5000);
                },
                error: function(xhr, status, error) {
                    $button.prop('disabled', false);
                    $button.html(originalText);
                    
                    $result.html('<div class="notice notice-error is-dismissible"><p>' + aiautotoolExtraConfig.strings.error + ' ' + error + '</p></div>');
                }
            });
        },
        
        /**
         * Handle export settings
         */
        handleExport: function(e) {
            e.preventDefault();
            
            $.ajax({
                url: aiautotoolExtraConfig.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'aiautotool_extra_config_export_settings',
                    nonce: aiautotoolExtraConfig.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Create download
                        const blob = new Blob([response.data.data], { type: 'application/json' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = response.data.filename;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                        
                        alert(response.data.message);
                    } else {
                        alert(aiautotoolExtraConfig.strings.error + ' ' + response.data.message);
                    }
                },
                error: function() {
                    alert(aiautotoolExtraConfig.strings.error);
                }
            });
        },
        
        /**
         * Handle import settings
         */
        handleImport: function(e) {
            e.preventDefault();
            
            // Create file input
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            
            input.onchange = function(e) {
                const file = e.target.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const contents = e.target.result;
                    
                    $.ajax({
                        url: aiautotoolExtraConfig.ajaxUrl,
                        type: 'POST',
                        data: {
                            action: 'aiautotool_extra_config_import_settings',
                            nonce: aiautotoolExtraConfig.nonce,
                            settings_data: contents
                        },
                        success: function(response) {
                            if (response.success) {
                                alert(response.data.message);
                                location.reload();
                            } else {
                                alert(aiautotoolExtraConfig.strings.error + ' ' + response.data.message);
                            }
                        },
                        error: function() {
                            alert(aiautotoolExtraConfig.strings.error);
                        }
                    });
                };
                reader.readAsText(file);
            };
            
            input.click();
        },
        
        /**
         * Handle reset settings
         */
        handleReset: function(e) {
            e.preventDefault();
            
            if (!confirm(aiautotoolExtraConfig.strings.confirm_reset_settings)) {
                return;
            }
            
            $.ajax({
                url: aiautotoolExtraConfig.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'aiautotool_extra_config_reset_settings',
                    nonce: aiautotoolExtraConfig.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        location.reload();
                    } else {
                        alert(aiautotoolExtraConfig.strings.error + ' ' + response.data.message);
                    }
                },
                error: function() {
                    alert(aiautotoolExtraConfig.strings.error);
                }
            });
        },
        
        /**
         * Handle form submit
         */
        handleFormSubmit: function(e) {
            // Validate number inputs
            const $numberInputs = $(this).find('input[type="number"]');
            let isValid = true;
            
            $numberInputs.each(function() {
                const $input = $(this);
                const value = parseInt($input.val());
                const min = parseInt($input.attr('min'));
                const max = parseInt($input.attr('max'));
                
                if (isNaN(value) || value < min || value > max) {
                    isValid = false;
                    $input.addClass('error');
                    
                    // Add error message
                    if (!$input.next('.error-message').length) {
                        $input.after('<span class="error-message" style="color: red; display: block; margin-top: 5px;">Value must be between ' + min + ' and ' + max + '</span>');
                    }
                } else {
                    $input.removeClass('error');
                    $input.next('.error-message').remove();
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                alert('Please fix the errors in the form before submitting.');
                return false;
            }
        }
    };
    
    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        ExtraConfigAdmin.init();
    });
    
})(jQuery);


