<?php

namespace NextBricks;

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

class Next_PT {
    public function init() {
        wp_enqueue_script('jquery-core'); //Load jQuery without jQuery migrate

        //Load pt panel at builder
        if (function_exists('bricks_is_builder')) {
            if (bricks_is_builder() && !bricks_is_builder_iframe()) {
                //Print pt panel HTML
                add_action('wp_footer', array($this, 'generate_pt_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('nextpt', NEXTBRICKS_PLUGIN_URL . 'features/nextpt.css', array(), NEXTBRICKS_VERSION, false);
                wp_enqueue_script('nextpt', NEXTBRICKS_PLUGIN_URL . 'features/nextpt.js', array('bricks-scripts'), NEXTBRICKS_VERSION, false);  
                
                add_action('wp_enqueue_scripts', array($this, 'send_data_to_pt'));
            }
        }

        if (function_exists('bricks_is_frontend')) {
            if (bricks_is_frontend()) {
                //load CSS at front
                wp_enqueue_style( 'nextpt_front_css', NEXTBRICKS_PLUGIN_URL . 'features/nextpt_front.css', array('bricks-frontend'), NEXTBRICKS_VERSION, false );

                //Load barbajs and its plugins
                wp_enqueue_script('next-barba', NEXTBRICKS_PLUGIN_URL . 'local_assets/next_barba.min.js', array(), NEXTBRICKS_VERSION, true);
                wp_enqueue_script('next-barba-router', NEXTBRICKS_PLUGIN_URL . 'local_assets/next_barba_router.min.js', array(), NEXTBRICKS_VERSION, true);

                //Set barba data-attributes
                add_action('wp_enqueue_scripts', array($this, 'set_barba_data_attributes'), PHP_INT_MAX);

                add_action('wp_footer', array($this, 'enqueue_pt_front_script'));
                add_action('wp_footer', array($this, 'send_pt_data_to_front'));
            }
        }

        add_action('wp_ajax_get_data_from_pt', array($this, 'get_data_from_pt'));
        add_action('wp_ajax_nopriv_get_data_from_pt', array($this, 'get_data_from_pt'));
    }

    private function apply_barba_attribute($element_type, $selector, $attribute_value) {
        if (empty($selector)) {
            return;
        }

        // Check for id
        if (isset($selector[0]) && $selector[0] === '#') {
            add_filter('bricks/element/set_root_attributes', function($attributes, $element) use ($selector, $attribute_value) {
                if (isset($attributes['id']) && '#' . $attributes['id'] === $selector) {
                    $attributes['data-barba'] = $attribute_value;
                }
                return $attributes;
            }, 10, 2);
        }
        // Check for class
        elseif (isset($selector[0]) && $selector[0] === '.') {
            add_filter('bricks/element/set_root_attributes', function($attributes, $element) use ($selector, $attribute_value) {
                if (isset($attributes['class']) && is_array($attributes['class']) && 
                    in_array(substr($selector, 1), $attributes['class'])) {
                    $attributes['data-barba'] = $attribute_value;
                }
                return $attributes;
            }, 10, 2);
        }
        // Check for HTML tag
        else {
            switch ($selector) {
                case "body":
                case "header":
                case "main":
                case "footer":
                    $filter_name = $selector === "main" ? 'bricks/content/attributes' : "bricks/{$selector}/attributes";
                    add_filter($filter_name, function($attributes) use ($attribute_value) {
                        $attributes['data-barba'] = $attribute_value;
                        return $attributes;
                    });
                    break;
                default:
                    add_filter('bricks/element/set_root_attributes', function($attributes, $element) use ($selector, $attribute_value) {
                        if (isset($element->tag) && $element->tag === $selector) {
                            $attributes['data-barba'] = $attribute_value;
                        }
                        return $attributes;
                    }, 10, 2);
                    break;
            }
        }
    }

    function set_barba_data_attributes() {
        $pagetransitions_variable = get_option('pagetransitions_variable', '');
        if (empty($pagetransitions_variable)) {
            return;
        }

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

        // Verify if decode was successful and has required structure
        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'])) {
                    continue;
                }

                // Add barba data-tag at container
                if (isset($timeline['timeline']['container'])) {
                    $this->apply_barba_attribute('container', $timeline['timeline']['container'], 'container');
                }

                // Add barba data-tag at wrapper
                if (isset($timeline['timeline']['wrapper'])) {
                    $this->apply_barba_attribute('wrapper', $timeline['timeline']['wrapper'], 'wrapper');
                }
            }
        }
    }

    function get_data_from_pt() {
        if (isset($_POST['pagetransitions_variable'])) {
            $pagetransitions_variable = sanitize_text_field($_POST['pagetransitions_variable']);
            update_option('pagetransitions_variable', $pagetransitions_variable);
        }
        if (isset($_POST['PageTransitionsTheme'])) {
            $PageTransitionsTheme = sanitize_text_field($_POST['PageTransitionsTheme']);
            update_option('pagetransitions_theme', $PageTransitionsTheme);
        }
        wp_die();
    }

    function enqueue_pt_front_script() {
        wp_enqueue_script('nextpt-front', NEXTBRICKS_PLUGIN_URL . 'features/nextpt_front.js', array('bricks-scripts'), NEXTBRICKS_VERSION, true);
    }

    function send_pt_data_to_front() {
        // Get animator data
        $pagetransitions_variable = get_option('pagetransitions_variable', '');

        // Get post ID safely
        global $post;
        $post_id = isset($post) ? $post->ID : 0;

        // Get custom JS with default
        $custom_js = get_option('bc_pagetransitions_customjs', '');
    
        // Send data to JS
        wp_localize_script('nextpt-front', 'data_pagetransitions', array(
            'data_pagetransitions' => $pagetransitions_variable ?: '',
            'post_id' => absint($post_id),
            'ajaxurl' => admin_url('admin-ajax.php'),
            'customjs' => $custom_js
        ));
    }

    function send_data_to_pt() {
        // Send custom accent color with default
        $accent_color = get_option('bc_pagetransitions_color', '#0096FE');
        wp_localize_script('nextpt', 'PageTransitionsAccentColor', array(
            'accent_color' => sanitize_hex_color($accent_color) ?: '#0096FE'
        ));

        // Send custom shortcut with default
        $shortcut = get_option('bc_pagetransitions_shortcut', 'P');
        wp_localize_script('nextpt', 'PageTransitionsShortcut', array(
            'shortcut' => sanitize_text_field($shortcut)
        ));

        // Send stored theme with default
        $theme = get_option('pagetransitions_theme', 'dark');
        wp_localize_script('nextpt', 'data_pagetransitions_theme', array(
            'selected_theme' => sanitize_text_field($theme)
        ));

        // Get and send animator data
        $pagetransitions_variable = get_option('pagetransitions_variable', '');
        wp_localize_script('nextpt', 'data_pagetransitions', array(
            'data_pagetransitions' => $pagetransitions_variable ?: '',
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
    }

    function generate_pt_input() {
        echo '<div class="nb-ptanimator"></div>';
    }
}