<?php

namespace Unlockafe_addons\Editor;

use Elementor\Controls_Manager;
use Elementor\Core\Base\Module;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Elementor Text Generator Module.
 *
 * Handles the text generator integration with Elementor editor
 *
 * @since 1.0.0
 */
class Text_Generator_Module {

    /**
     * Module instance
     *
     * @var null|Module
     */
    private static $instance = null;

    /**
     * Constructor
     */
    private function __construct() {
        // Register the module with Elementor
        add_action('elementor/editor/before_enqueue_scripts', [$this, 'enqueue_editor_scripts']);
        
        // Add editor button to the editor panel
        add_action('elementor/editor/after_enqueue_styles', [$this, 'enqueue_editor_styles']);
        
        // Add editor templates
        add_action('elementor/editor/footer', [$this, 'render_editor_templates']);
        
        // Register custom controls
        add_action('elementor/controls/register', [$this, 'register_controls']);
    }

    /**
     * Get instance
     *
     * @return Text_Generator_Module
     */
    public static function getInstance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Enqueue editor scripts
     */
    public function enqueue_editor_scripts() {
        // Create assets directories if they don't exist
        if (!file_exists(UNLOCKAFE_ADDONS_DIR . '/assets/editor/js')) {
            wp_mkdir_p(UNLOCKAFE_ADDONS_DIR . '/assets/editor/js');
        }
        
        // Ensure the front-end JS files are loaded in the editor
        wp_enqueue_script(
            'unlockafe-text-generator',
            UNLOCKAFE_ASSETS . 'front-end/js/text-generator.js',
            ['jquery'],
            UNLOCKAFE_VERSION,
            true
        );
        
        // Enqueue the editor module JS
        wp_enqueue_script(
            'unlockafe-text-generator-module',
            UNLOCKAFE_ASSETS . 'editor/js/text-generator-module.js',
            ['jquery', 'elementor-editor'],
            UNLOCKAFE_VERSION,
            true
        );
        
        // Get current settings to properly configure the editor
        $settings_instance = \Unlockafe_addons\Admin\Text_Generator_Settings::getInstance();
        $settings = $settings_instance->get_settings();
        
        // Localize the script with necessary data
        wp_localize_script(
            'unlockafe-text-generator-module',
            'unlockafe_text_generator_module',
            [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('unlockafe_text_generator_nonce'),
                'api_provider' => $settings['api_provider'],
                'i18n' => [
                    'generate_text' => __('Generate Text', 'unlock-addons-for-elementor'),
                    'generating' => __('Generating...', 'unlock-addons-for-elementor'),
                    'error' => __('Error', 'unlock-addons-for-elementor'),
                ]
            ]
        );
        
        // Add an inline script to directly initialize our module - this helps ensure it's loaded correctly
        wp_add_inline_script('unlockafe-text-generator-module', '
            jQuery(document).ready(function() {
                console.log("Text Generator Module inline script initialized");
                // Make sure our button is clickable by re-binding the events
                jQuery(document).on("click", ".unlockafe-generate-text-button", function(e) {
                    e.preventDefault();
                    console.log("Button clicked - inline handler");
                    if (window.TextGeneratorModule) {
                        window.TextGeneratorModule.openModal(e);
                    } else {
                        alert("Text Generator Module not loaded. Please refresh the page.");
                    }
                    return false;
                });
            });
        ');
    }

    /**
     * Enqueue editor styles
     */
    public function enqueue_editor_styles() {
        wp_enqueue_style(
            'unlockafe-text-generator-editor',
            UNLOCKAFE_ASSETS . 'editor/css/text-generator-editor.css',
            [],
            UNLOCKAFE_VERSION
        );
    }

    /**
     * Render editor templates
     * 
     * Adds the text generator modal template to the editor
     */
    public function render_editor_templates() {
        ?>
        <script type="text/template" id="tmpl-unlockafe-text-generator-modal">
            <div class="dialog-widget dialog-lightbox-widget dialog-type-buttons dialog-type-lightbox elementor-templates-modal unlockafe-text-generator-modal">
                <div class="dialog-widget-content dialog-lightbox-widget-content">
                    <div class="dialog-header dialog-lightbox-header">
                        <div class="elementor-templates-modal__header">
                            <div class="elementor-templates-modal__header__logo-area">
                                <div class="elementor-templates-modal__header__logo">
                                    <span class="elementor-templates-modal__header__logo__icon-wrapper">
                                        <i class="eicon-text"></i>
                                    </span>
                                    <span class="elementor-templates-modal__header__logo__title"><?php echo esc_html__('Text Generator', 'unlock-addons-for-elementor'); ?></span>
                                </div>
                            </div>
                            <div class="elementor-templates-modal__header__items-area">
                                <div class="elementor-templates-modal__header__close elementor-templates-modal__header__close--normal elementor-templates-modal__header__item">
                                    <i class="eicon-close" aria-hidden="true"></i>
                                    <span class="elementor-screen-only"><?php echo esc_html__('Close', 'unlock-addons-for-elementor'); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="dialog-message dialog-lightbox-message">
                        <div class="dialog-content dialog-lightbox-content">
                            <div class="unlockafe-text-generator-modal-body">
                                <div class="unlockafe-modal-form-group">
                                    <label class="unlockafe-modal-label"><?php echo esc_html__('Topic', 'unlock-addons-for-elementor'); ?></label>
                                    <input type="text" class="unlockafe-modal-input unlockafe-modal-topic" placeholder="<?php echo esc_attr__('Enter a topic', 'unlock-addons-for-elementor'); ?>">
                                </div>
                                
                                <div class="unlockafe-modal-form-group">
                                    <label class="unlockafe-modal-label"><?php echo esc_html__('Length', 'unlock-addons-for-elementor'); ?></label>
                                    <select class="unlockafe-modal-select unlockafe-modal-length">
                                        <option value="short"><?php echo esc_html__('Short (100-200 words)', 'unlock-addons-for-elementor'); ?></option>
                                        <option value="medium" selected><?php echo esc_html__('Medium (200-500 words)', 'unlock-addons-for-elementor'); ?></option>
                                        <option value="long"><?php echo esc_html__('Long (500+ words)', 'unlock-addons-for-elementor'); ?></option>
                                    </select>
                                </div>
                                
                                <div class="unlockafe-modal-form-group">
                                    <label class="unlockafe-modal-label"><?php echo esc_html__('Tone', 'unlock-addons-for-elementor'); ?></label>
                                    <select class="unlockafe-modal-select unlockafe-modal-tone">
                                        <option value="professional"><?php echo esc_html__('Professional', 'unlock-addons-for-elementor'); ?></option>
                                        <option value="casual" selected><?php echo esc_html__('Casual', 'unlock-addons-for-elementor'); ?></option>
                                        <option value="formal"><?php echo esc_html__('Formal', 'unlock-addons-for-elementor'); ?></option>
                                        <option value="friendly"><?php echo esc_html__('Friendly', 'unlock-addons-for-elementor'); ?></option>
                                        <option value="persuasive"><?php echo esc_html__('Persuasive', 'unlock-addons-for-elementor'); ?></option>
                                    </select>
                                </div>
                                
                                <div class="unlockafe-modal-form-group">
                                    <label class="unlockafe-modal-label"><?php echo esc_html__('Additional Instructions (Optional)', 'unlock-addons-for-elementor'); ?></label>
                                    <textarea class="unlockafe-modal-textarea unlockafe-modal-instructions" placeholder="<?php echo esc_attr__('Any specific instructions for the text generator', 'unlock-addons-for-elementor'); ?>"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="dialog-buttons-wrapper dialog-lightbox-buttons-wrapper">
                        <div class="unlockafe-modal-footer">
                            <button class="elementor-button elementor-button-default unlockafe-modal-cancel"><?php echo esc_html__('Cancel', 'unlock-addons-for-elementor'); ?></button>
                            <button class="elementor-button elementor-button-success unlockafe-modal-submit"><?php echo esc_html__('Generate Text', 'unlock-addons-for-elementor'); ?></button>
                        </div>
                    </div>
                </div>
            </div>
        </script>
        <?php
    }

    /**
     * Register controls
     *
     * @param Controls_Manager $controls_manager
     */
    public function register_controls($controls_manager) {
        // Here we can register custom controls if needed
    }
}

// Initialize the module
Text_Generator_Module::getInstance();
