<?php

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

if (!class_exists('Pakrco_Elementor_Control')) :

    /**
     * The Pakrco Elementor Integration class
     */
    class Pakrco_Elementor_Control {

        public function __construct() {

            add_action('elementor/ajax/register_actions', [$this, 'register_ajax_actions']);
            add_action('elementor/controls/controls_registered', [$this, 'on_controls_registered']);
        }

        public function ajax_posts_filter_autocomplete(array $data) {
            if (empty($data['q'])) {
                throw new \Exception('Bad Request');
            }

            $results = [];

            $query_params = [
                'post_type'      => 'product',
                's'              => $data['q'],
                'posts_per_page' => -1,
            ];

            $query = new WP_Query($query_params);

            foreach ($query->posts as $post) {

                $results[] = [
                    'id'   => $post->ID,
                    'text' => esc_html($post->post_title),
                ];
            }

            return [
                'results' => $results,
            ];
        }

        public function ajax_query_control_value_product($request) {
            $ids = (array)$request['id'];

            $results = [];
            $query   = new \WP_Query(
                [
                    'post_type'      => 'any',
                    'post__in'       => $ids,
                    'posts_per_page' => -1,
                ]
            );

            foreach ($query->posts as $post) {
                $results[$post->ID] = esc_html($post->post_title);
            }
            return $results;
        }

        public function ajax_query_control_value_page($request) {
            $ids = (array)$request['id'];
            $results = [];

            foreach ( $ids as $data_key => $sel_value ) {
                if ( strpos( $sel_value, 'post-' ) !== false ) {
                    $post_id    = (int) str_replace( 'post-', '', $sel_value );
                    $post_title = get_the_title( $post_id );
                    $results[$sel_value] = esc_html($post_title);
                }

                // taxonomy options.
                if ( strpos( $sel_value, 'tax-' ) !== false ) {
                    $tax_data = explode( '-', $sel_value );

                    $tax_id    = (int) str_replace( 'tax-', '', $sel_value );
                    $term      = get_term( $tax_id );
                    $term_name = '';

                    if ( ! is_wp_error( $term ) ) {
                        $term_taxonomy = ucfirst( str_replace( '_', ' ', $term->taxonomy ) );

                        if ( isset( $tax_data[2] ) && 'single' === $tax_data[2] ) {
                            $term_name = 'All singulars from ' . $term->name;
                        } else {
                            $term_name = $term->name . ' - ' . $term_taxonomy;
                        }
                    }
                    $results[$sel_value] = esc_html($term_name);

                }
            }

            return $results;
        }

        public function ajax_get_posts_by_query(array $value) {
            if (empty($value['q'])) {
                throw new \Exception('Bad Request');
            }
            $search_string = $value['q'];
            $data          = array();
            $result        = array();

            $args = array(
                'public'   => true,
                '_builtin' => false,
            );

            $output     = 'names'; // names or objects, note names is the default.
            $operator   = 'and'; // also supports 'or'.
            $post_types = get_post_types( $args, $output, $operator );

            unset( $post_types['elementor-hf'] ); //Exclude EHF templates.

            $post_types['Posts'] = 'post';
            $post_types['Pages'] = 'page';

            foreach ( $post_types as $key => $post_type ) {
                $data = array();

                add_filter( 'posts_search', array( $this, 'search_only_titles' ), 10, 2 );

                $query = new \WP_Query(
                    array(
                        's'              => $search_string,
                        'post_type'      => $post_type,
                        'posts_per_page' => - 1,
                    )
                );

                if ( $query->have_posts() ) {
                    while ( $query->have_posts() ) {
                        $query->the_post();
                        $title  = get_the_title();
                        $title .= ( 0 != $query->post->post_parent ) ? ' (' . get_the_title( $query->post->post_parent ) . ')' : '';
                        $id     = get_the_id();
                        $data[] = array(
                            'id'   => 'post-' . $id,
                            'text' => $title,
                        );
                    }
                }

                if ( is_array( $data ) && ! empty( $data ) ) {
                    $result[] = array(
                        'text'     => $key,
                        'children' => $data,
                    );
                }
            }

            $data = array();

            wp_reset_postdata();

            $args = array(
                'public' => true,
            );

            $output     = 'objects'; // names or objects, note names is the default.
            $operator   = 'and'; // also supports 'or'.
            $taxonomies = get_taxonomies( $args, $output, $operator );

            foreach ( $taxonomies as $taxonomy ) {
                $terms = get_terms(
                    $taxonomy->name,
                    array(
                        'orderby'    => 'count',
                        'hide_empty' => 0,
                        'name__like' => $search_string,
                    )
                );

                $data = array();

                $label = ucwords( $taxonomy->label );

                if ( ! empty( $terms ) ) {
                    foreach ( $terms as $term ) {
                        $term_taxonomy_name = ucfirst( str_replace( '_', ' ', $taxonomy->name ) );

                        $data[] = array(
                            'id'   => 'tax-' . $term->term_id,
                            'text' => $term->name . ' archive page',
                        );

                        $data[] = array(
                            'id'   => 'tax-' . $term->term_id . '-single-' . $taxonomy->name,
                            'text' => 'All singulars from ' . $term->name,
                        );
                    }
                }

                if ( is_array( $data ) && ! empty( $data ) ) {
                    $result[] = array(
                        'text'     => $label,
                        'children' => $data,
                    );
                }
            }

            // return the result in json.
            return [
                'results' => $result
            ];
        }

        public function register_ajax_actions($ajax_manager) {
            $ajax_manager->register_ajax_action('panel_posts_control_filter_product', [$this, 'ajax_posts_filter_autocomplete']);
            $ajax_manager->register_ajax_action('query_control_value_product', [$this, 'ajax_query_control_value_product']);
            $ajax_manager->register_ajax_action('panel_posts_control_filter_page', [$this, 'ajax_get_posts_by_query']);
            $ajax_manager->register_ajax_action('query_control_value_page', [$this, 'ajax_query_control_value_page']);
        }

        public function on_controls_registered() {
            $this->register_control();
        }

        private function register_control() {
            require get_theme_file_path('includes/elementor/elementor-control/product-control.php');
            require get_theme_file_path('includes/elementor/elementor-control/specific-page-control.php');

            require get_theme_file_path('includes/elementor/elementor-control/group-control-text-gradient.php');
            require get_theme_file_path('includes/elementor/elementor-control/group-control-text-stroke.php');

            $controls_manager = \Elementor\Plugin::instance()->controls_manager;
            $controls_manager->register_control('products', new Products_Control());
            $controls_manager->register_control('specific-page', new Specific_Page_Control());

            $controls_manager->add_group_control( Group_Control_Text_Gradient::get_type(), new Group_Control_Text_Gradient() );
            $controls_manager->add_group_control( Group_Control_Text_Stroke::get_type(), new Group_Control_Text_Stroke() );
        }

    }

endif;

return new Pakrco_Elementor_Control();
