<?php
/**
 * AYSA Elementor Content Handler 
 * Handles content updates for Elementor-built pages and products
 */

if (!defined('ABSPATH')) {
    exit;
}

class AYSA_Elementor_Handler {

    private function get_project_id_for_wallet() {
        return max(0, intval(get_option('aysa_project_id', 0)));
    }

    private function track_wallet_usage($action_key, $reference, $fallback_cost_cents, $meta = array(), $endpoint = '') {
        if (!function_exists('aysa_get_wallet_manager')) {
            return;
        }

        $project_id = $this->get_project_id_for_wallet();
        if ($project_id <= 0) {
            return;
        }

        $wallet_manager = aysa_get_wallet_manager();
        if (!$wallet_manager || !method_exists($wallet_manager, 'track_action_usage')) {
            return;
        }

        $wallet_manager->track_action_usage($project_id, $action_key, $reference, array(
            'meta' => is_array($meta) ? $meta : array(),
            'fallback_cost_cents' => max(0, intval($fallback_cost_cents)),
            'endpoint' => $endpoint,
            'billing_authority' => 'plugin_wallet',
        ));
    }
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('init', array($this, 'init'));
        add_action('wp_ajax_aysa_update_elementor_content', array($this, 'handle_ajax_update'));
        add_action('wp_ajax_aysa_get_elementor_content', array($this, 'handle_ajax_get_content'));
    }
    
    /**
     * Initialize the handler
     */
    public function init() {
        // Add JavaScript for Elementor integration
        add_action('admin_enqueue_scripts', array($this, 'enqueue_elementor_scripts'));
    }
    
    /**
     * Enqueue Elementor integration scripts
     */
    public function enqueue_elementor_scripts($hook) {
        // Only load on post/product/category edit pages
        if (!in_array($hook, ['post.php', 'post-new.php', 'edit-tags.php', 'term.php'])) {
            return;
        }
        
        wp_enqueue_script(
            'aysa-elementor-handler',
            plugin_dir_url(__FILE__) . '../admin/js/aysa-elementor-handler.js',
            array('jquery'),
            '1.0.0',
            true
        );
        
        // Pass data to JavaScript
        wp_localize_script('aysa-elementor-handler', 'aysaElementorAjax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('aysa_elementor_nonce'),
            'is_elementor_active' => $this->is_elementor_plugin_active()
        ));
    }
    
    /**
     * Check if Elementor plugin is active
     */
    public function is_elementor_plugin_active() {
        return class_exists('\Elementor\Plugin');
    }
    
    /**
     * Check if Elementor is active on a specific post/page
     */
    public function is_elementor_active_on_post($post_id) {
        if (!$this->is_elementor_plugin_active()) {
            return false;
        }
        
        $elementor_data = get_post_meta($post_id, '_elementor_data', true);
        return !empty($elementor_data);
    }
    
    /**
     * Get Elementor content from a post
     */
    public function get_elementor_content($post_id, $content_type = 'description') {
        if (!$this->is_elementor_active_on_post($post_id)) {
            return false;
        }
        
        $elementor_data = get_post_meta($post_id, '_elementor_data', true);
        if (empty($elementor_data)) {
            return false;
        }
        
        $data = json_decode($elementor_data, true);
        if (!$data) {
            return false;
        }
        
        return $this->extract_content_from_elements($data, $content_type);
    }
    
    /**
     * Update Elementor content
     */
    public function update_elementor_content($post_id, $new_content, $content_type = 'description') {
        if (!$this->is_elementor_active_on_post($post_id)) {
            return false;
        }
        
        $elementor_data = get_post_meta($post_id, '_elementor_data', true);
        if (empty($elementor_data)) {
            return false;
        }
        
        $data = json_decode($elementor_data, true);
        if (!$data) {
            return false;
        }
        
        // Update content in Elementor structure
        $updated_data = $this->update_content_in_elements($data, $new_content, $content_type);
        
        if ($updated_data !== $data) {
            // Save updated data
            update_post_meta($post_id, '_elementor_data', wp_slash(json_encode($updated_data)));
            
            // Update Elementor version to force cache refresh
            if (defined('ELEMENTOR_VERSION')) {
                update_post_meta($post_id, '_elementor_version', ELEMENTOR_VERSION);
            }
            
            // Clear Elementor cache
            $this->clear_elementor_cache($post_id);
            
            return true;
        }
        
        return false;
    }
    
    /**
     * Extract content from Elementor elements recursively
     */
    private function extract_content_from_elements($elements, $content_type) {
        foreach ($elements as $element) {
            // Check if this element contains the content we're looking for
            if (isset($element['widgetType'])) {
                $content = $this->extract_content_from_widget($element, $content_type);
                if ($content !== false) {
                    return $content;
                }
            }
            
            // Search in child elements
            if (isset($element['elements']) && is_array($element['elements'])) {
                $content = $this->extract_content_from_elements($element['elements'], $content_type);
                if ($content !== false) {
                    return $content;
                }
            }
        }
        
        return false;
    }
    
    /**
     * Extract content from a specific widget
     */
    private function extract_content_from_widget($element, $content_type) {
        $widget_type = $element['widgetType'];
        $settings = isset($element['settings']) ? $element['settings'] : array();
        
        // Map content types to widget types and settings
        $widget_mappings = array(
            'description' => array(
                'woocommerce-product-content' => 'content',
                'text-editor' => 'editor',
                'heading' => 'title',
                'theme-post-content' => 'content'
            ),
            'short_description' => array(
                'woocommerce-product-short-description' => 'content',
                'text-editor' => 'editor'
            ),
            'title' => array(
                'heading' => 'title',
                'theme-post-title' => 'title',
                'woocommerce-product-title' => 'title'
            )
        );
        
        if (isset($widget_mappings[$content_type])) {
            foreach ($widget_mappings[$content_type] as $widget => $setting) {
                if ($widget_type === $widget && isset($settings[$setting])) {
                    return $settings[$setting];
                }
            }
        }
        
        return false;
    }
    
    /**
     * Update content in Elementor elements recursively
     */
    private function update_content_in_elements($elements, $new_content, $content_type) {
        foreach ($elements as &$element) {
            // Update content in this element if it matches
            if (isset($element['widgetType'])) {
                $element = $this->update_content_in_widget($element, $new_content, $content_type);
            }
            
            // Update child elements
            if (isset($element['elements']) && is_array($element['elements'])) {
                $element['elements'] = $this->update_content_in_elements($element['elements'], $new_content, $content_type);
            }
        }
        
        return $elements;
    }
    
    /**
     * Update content in a specific widget
     */
    private function update_content_in_widget($element, $new_content, $content_type) {
        $widget_type = $element['widgetType'];
        
        // Map content types to widget types and settings
        $widget_mappings = array(
            'description' => array(
                'woocommerce-product-content' => 'content',
                'text-editor' => 'editor',
                'theme-post-content' => 'content'
            ),
            'short_description' => array(
                'woocommerce-product-short-description' => 'content',
                'text-editor' => 'editor'
            ),
            'title' => array(
                'heading' => 'title',
                'theme-post-title' => 'title',
                'woocommerce-product-title' => 'title'
            )
        );
        
        if (isset($widget_mappings[$content_type])) {
            foreach ($widget_mappings[$content_type] as $widget => $setting) {
                if ($widget_type === $widget) {
                    if (!isset($element['settings'])) {
                        $element['settings'] = array();
                    }
                    $element['settings'][$setting] = $new_content;
                    break;
                }
            }
        }
        
        return $element;
    }
    
    /**
     * Clear Elementor cache
     */
    private function clear_elementor_cache($post_id = null) {
        if (!$this->is_elementor_plugin_active()) {
            return;
        }
        
        try {
            // Clear Elementor cache
            if (class_exists('\Elementor\Plugin')) {
                \Elementor\Plugin::$instance->files_manager->clear_cache();
                
                // If specific post ID provided, clear its cache
                if ($post_id) {
                    \Elementor\Plugin::$instance->posts_css_manager->clear_cache();
                }
            }
        } catch (Exception $e) {
            aysa_debug_log('AYSA Elementor Handler: Error clearing cache - ' . $e->getMessage());
        }
    }
    
    /**
     * Handle AJAX request to update Elementor content
     */
    public function handle_ajax_update() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field((string) wp_unslash($_POST['nonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, 'aysa_elementor_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $post_id = isset($_POST['post_id']) ? intval((string) wp_unslash($_POST['post_id'])) : 0;
        $content_type = isset($_POST['content_type']) ? sanitize_text_field((string) wp_unslash($_POST['content_type'])) : '';
        $new_content = isset($_POST['new_content']) ? wp_kses_post((string) wp_unslash($_POST['new_content'])) : '';
        
        if (!$post_id || empty($content_type) || empty($new_content)) {
            wp_send_json_error('Invalid data');
        }

        if (!current_user_can('edit_post', $post_id)) {
            wp_send_json_error('Post permission denied', 403);
        }
        
        // Update both WordPress and Elementor content
        $results = array();
        
        // Update WordPress post content
        if ($content_type === 'description') {
            $results['wordpress'] = wp_update_post(array(
                'ID' => $post_id,
                'post_content' => $new_content
            ));
        } elseif ($content_type === 'short_description') {
            $results['wordpress'] = wp_update_post(array(
                'ID' => $post_id,
                'post_excerpt' => $new_content
            ));
        }
        
        // Update Elementor content
        $results['elementor'] = $this->update_elementor_content($post_id, $new_content, $content_type);
        
        // Clear caches
        wp_cache_delete($post_id, 'posts');
        
        if ($results['wordpress'] || $results['elementor']) {
            $this->track_wallet_usage(
                'aysa_update_elementor_content',
                'elementor_update:' . $post_id . ':' . $content_type,
                5,
                array(
                    'module' => 'on_page_optimization',
                    'post_id' => intval($post_id),
                    'content_type' => $content_type,
                    'updated_wordpress' => !empty($results['wordpress']),
                    'updated_elementor' => !empty($results['elementor']),
                ),
                '/wp_ajax/aysa_update_elementor_content'
            );

            wp_send_json_success(array(
                'message' => 'Content updated successfully',
                'results' => $results
            ));
        } else {
            wp_send_json_error('Failed to update content');
        }
    }
    
    /**
     * Handle AJAX request to get Elementor content
     */
    public function handle_ajax_get_content() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field((string) wp_unslash($_POST['nonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, 'aysa_elementor_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $post_id = isset($_POST['post_id']) ? intval((string) wp_unslash($_POST['post_id'])) : 0;
        $content_type = isset($_POST['content_type']) ? sanitize_text_field((string) wp_unslash($_POST['content_type'])) : '';
        
        if (!$post_id || empty($content_type)) {
            wp_send_json_error('Invalid data');
        }

        if (!current_user_can('edit_post', $post_id)) {
            wp_send_json_error('Post permission denied', 403);
        }
        
        $content = array();
        
        // Get WordPress content
        $post = get_post($post_id);
        if ($post) {
            if ($content_type === 'description') {
                $content['wordpress'] = $post->post_content;
            } elseif ($content_type === 'short_description') {
                $content['wordpress'] = $post->post_excerpt;
            }
        }
        
        // Get Elementor content
        $content['elementor'] = $this->get_elementor_content($post_id, $content_type);
        $content['is_elementor_active'] = $this->is_elementor_active_on_post($post_id);
        
        wp_send_json_success($content);
    }
    
    /**
     * Get instance
     */
    public static function get_instance() {
        static $instance = null;
        if (null === $instance) {
            $instance = new self();
        }
        return $instance;
    }
}

// Initialize the handler
AYSA_Elementor_Handler::get_instance(); 
