<?php

namespace NextBricks;

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

class Next_Animator {
    public function init() {
        wp_enqueue_script('jquery-core'); //Load jQuery without jQuery migrate
        
        //Load animator at builder
        if (function_exists('bricks_is_builder')) {
            if (bricks_is_builder() && !bricks_is_builder_iframe()) {
                //Print animator HTML
                add_action('wp_footer', array($this, 'generate_input'), PHP_INT_MAX);
    
                //Load animator libraries
                wp_enqueue_script('draggable-js', NEXTBRICKS_PLUGIN_URL . 'local_assets/bc_draggable.min.js', array(), NEXTBRICKS_VERSION, false);
                wp_enqueue_script('popper-js', NEXTBRICKS_PLUGIN_URL . 'local_assets/tippy/bc_popper.min.js', array(), NEXTBRICKS_VERSION, false);
                wp_enqueue_script('tippy-js', NEXTBRICKS_PLUGIN_URL . 'local_assets/tippy/bc_tippy.min.js', array(), NEXTBRICKS_VERSION, false);
        
                //Load animator CSS & JS files
                wp_enqueue_style('nextanimator', NEXTBRICKS_PLUGIN_URL . 'features/nextanimator.css', array(), NEXTBRICKS_VERSION, false);
                wp_enqueue_script('nextanimator', NEXTBRICKS_PLUGIN_URL . 'features/nextanimator.js', array('bricks-scripts'), NEXTBRICKS_VERSION, false);  
                
                add_action('wp_enqueue_scripts', array($this, 'send_data_to_animator'));
            }
        }

        if (function_exists('bricks_is_frontend')) {
            //Load GSAP timelines at front right after all elements scripts
            if (bricks_is_frontend()) {
                //load CSS at front
                wp_enqueue_style( 'nextanimator_front_css', NEXTBRICKS_PLUGIN_URL . 'features/nextanimator_front.css', array('bricks-frontend'), NEXTBRICKS_VERSION, false );

                //add flickering class to from method animated elements
                add_action('wp_enqueue_scripts', array($this, 'set_custom_class'));

                add_action('wp_footer', array($this, 'enqueue_bc_animator_script'));
                add_action('wp_footer', array($this, 'send_data_to_front'));
            }
        }

        add_action('wp_ajax_get_data_from_animator', array($this, 'get_data_from_animator'));
        add_action('wp_ajax_nopriv_get_data_from_animator', array($this, 'get_data_from_animator'));
    }
    
    function set_custom_class() {
        $mi_variable = get_option('mi_variable', '');
        if (empty($mi_variable)) {
            return;
        }

        $decoded_json = stripslashes($mi_variable);
        $jsonObject = json_decode($decoded_json, true);

        // Verificar si el JSON es válido y tiene la estructura esperada
        if (json_last_error() !== JSON_ERROR_NONE || 
            !isset($jsonObject['animator']) || 
            !isset($jsonObject['animator']['folders']) || 
            !is_array($jsonObject['animator']['folders'])) {
            return;
        }

        // Loop folders
        foreach ($jsonObject['animator']['folders'] as $folder) {
            if (!isset($folder['folder']['timelines']) || !is_array($folder['folder']['timelines'])) {
                continue;
            }

            // Loop page transitions
            foreach ($folder['folder']['timelines'] as $timeline) {
                if (!isset($timeline['timeline']['animations']) || !is_array($timeline['timeline']['animations'])) {
                    continue;
                }

                foreach ($timeline['timeline']['animations'] as $animation) {
                    if (!isset($animation['animation'])) {
                        continue;
                    }

                    $animationData = $animation['animation'];
                    $animatedElement = null;

                    if (isset($animationData['element'])) {
                        if ($animationData['element'] === 'this' && isset($timeline['timeline']['trigger'])) {
                            $animatedElement = $timeline['timeline']['trigger'];
                        } elseif ($animationData['element'] !== 'this') {
                            $animatedElement = $animationData['element'];
                        }

                        if ($animatedElement !== null) {
                            $this->apply_class($animatedElement);
                        }
                    }
                }
            }
        }
    }

    function apply_class($animatedElement) {
        if (empty($animatedElement)) {
            return;
        }

        // Check for id
        if (isset($animatedElement[0]) && $animatedElement[0] === '#') {
            add_filter('bricks/element/set_root_attributes', function($attributes, $element) use ($animatedElement) {
                if (isset($attributes['id']) && ('#' . strval($attributes['id'])) === strval($animatedElement)) {
                    $attributes['data-animator'] = 'flickering';
                }
                return $attributes;
            }, 10, 2);
        } 
        // Check for class
        elseif (isset($animatedElement[0]) && $animatedElement[0] === '.') {
            add_filter('bricks/element/set_root_attributes', function($attributes, $element) use ($animatedElement) {
                if (isset($attributes['class']) && is_array($attributes['class']) && 
                    in_array(substr($animatedElement, 1), $attributes['class'])) {
                    $attributes['data-animator'] = 'flickering';
                }
                return $attributes;
            }, 10, 2);
        } 
        // If no id or class then check for tag
        else {
            switch ($animatedElement) {
                case "body":
                    add_filter('bricks/body/attributes', function($attributes) {
                        $attributes['data-animator'] = 'flickering';
                        return $attributes;
                    });
                    break;
                case "header":
                    add_filter('bricks/header/attributes', function($attributes) {
                        $attributes['data-animator'] = 'flickering';
                        return $attributes;
                    });
                    break;
                case "main":
                    add_filter('bricks/content/attributes', function($attributes) {
                        $attributes['data-animator'] = 'flickering';
                        return $attributes;
                    });
                    break;
                case "footer":
                    add_filter('bricks/footer/attributes', function($attributes) {
                        $attributes['data-animator'] = 'flickering';
                        return $attributes;
                    });
                    break;
                default:
                    add_filter('bricks/element/set_root_attributes', function($attributes, $element) use ($animatedElement) {
                        if (isset($element->tag) && $element->tag === $animatedElement) {
                            $attributes['data-animator'] = 'flickering';
                        }
                        return $attributes;
                    }, 10, 2);
                    break;
            }
        }
    }

    function enqueue_bc_animator_script() {
        wp_enqueue_script('nextanimator-front', NEXTBRICKS_PLUGIN_URL . 'features/nextanimator_front.js', array('bricks-scripts'), NEXTBRICKS_VERSION, true);
    }

    function get_data_from_animator() {
        if (isset($_POST['mi_variable'])) {
            $mi_variable = sanitize_text_field($_POST['mi_variable']); // Sanitizar input
            update_option('mi_variable', $mi_variable);
        }
        if (isset($_POST['CoreAnimatorTheme'])) {
            $CoreAnimatorTheme = sanitize_text_field($_POST['CoreAnimatorTheme']); // Sanitizar input
            update_option('core_animator_theme', $CoreAnimatorTheme);
        }
        wp_die();
    }

    function send_data_to_animator() {
        // Send custom accent color (declare #3858E9 as default)
        $accent_color = get_option('bc_core_animator_color', '#3858E9');
        wp_localize_script('nextanimator', 'AnimatorAccentColor', array(
            'accent_color' => sanitize_hex_color($accent_color) ?: '#3858E9'
        ));

        // Send custom shortcut
        $shortcut = get_option('bc_core_animator_shortcut', 'A');
        wp_localize_script('nextanimator', 'AnimatorShortcut', array(
            'shortcut' => sanitize_text_field($shortcut)
        ));

        // Send stored theme to JS
        $theme = get_option('core_animator_theme', 'dark');
        wp_localize_script('nextanimator', 'data_core_animator_theme', array(
            'selected_theme' => sanitize_text_field($theme)
        ));

        // Get animator data
        $mi_variable = get_option('mi_variable', '');
    
        // Send animator data to JS
        wp_localize_script('nextanimator', 'data_animator', array(
            'data_animations' => $mi_variable ?: '',  // Asegurar que nunca es null
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
    }

    function send_data_to_front() {
        // Get animator data
        $mi_variable = get_option('mi_variable', '');
        
        // Get also post id to check conditional display at timelines creation
        global $post;
        $post_id = isset($post) ? $post->ID : 0;
    
        // Send animator data to JS
        wp_localize_script('nextanimator-front', 'data_animator', array(
            'data_animations' => $mi_variable ?: '',  // Asegurar que nunca es null
            'post_id' => absint($post_id),
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
    }

    function generate_input() {
        // Print animator HTML at the builder
        echo '<div class="nb-animator"></div>';
    }
}