<?php namespace Webien\SearchAddon\SearchResult;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Text_Shadow;
use Elementor\Group_Control_Typography;

class Widget extends \Elementor\Widget_Base
{
    public function get_name()
    {
        return 'webien-search-addon-result';
    }

    public function get_title()
    {
        return 'Webien Sökresultat';
    }

    public function get_icon() {
        return 'eicon-post-list';
    }

    public function get_categories() {
        return ['webien'];
    }

    protected function _register_controls()
    {
        $relevanssi_post_types = get_option('relevanssi_index_post_types');

        // Remove the bogus post_type
        if (($key = array_search('bogus', $relevanssi_post_types)) !== false) {
            unset($relevanssi_post_types[$key]);
        }

        $this->start_controls_section(
            'section_content',
            [
                'label' => __('Allmänt', 'webien'),
            ]
        );
        $this->add_control(
            'list_type',
            [
                'label' => __('Välj vad du vill visa', 'webien'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'result' => __('Resultatlista', 'webien'),
                    'filter' => __('Filtrering', 'webien'),
                ],
                'default' => 'result',
            ]
        );
        $this->add_responsive_control(
            'columns',
            [
                'label'   => __('Kolumner', 'webien'),
                'type'    => \Elementor\Controls_Manager::SELECT,
                'default' => 1,
                'options' => array(
                    1  => 1,
                    2  => 2,
                    3  => 3,
                    4  => 4,
                    5  => 5,
                ),
                'condition' => [
                    'list_type' => 'result'
                ],
            ]

        );

        $this->add_control(
            'filter_lineup',
            [
                'label' => __('Uppställning', 'webien'),
                'type' => \Elementor\Controls_Manager::CHOOSE,
                'options' => [
                    'horisontal' => [
                        'title' => __('Horisontell', 'webien'),
                        'icon' => 'eicon-ellipsis-h',
                    ],
                    'vertical' => [
                        'title' => __('Vertikal', 'webien'),
                        'icon' => 'eicon-ellipsis-v',
                    ],
                ],
                'default' => 'horisontal',
                'toggle' => true,
                'condition' => [
                    'list_type' => 'filter'
                ],
            ]
        );
        $this->add_control(
            'text_align',
            [
                'label' => __('Linjering', 'webien'),
                'type' => \Elementor\Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => __( 'Vänster', 'plugin-domain' ),
                        'icon' => 'fa fa-align-left',
                    ],
                    'center' => [
                        'title' => __( 'Centrerat', 'plugin-domain' ),
                        'icon' => 'fa fa-align-center',
                    ],
                    'right' => [
                        'title' => __( 'Höger', 'plugin-domain' ),
                        'icon' => 'fa fa-align-right',
                    ],
                ],
                'default' => 'left',
                'toggle' => true,
                'condition' => [
                    'list_type' => 'filter'
                ],
            ]
        );

        $this->add_control(
            'show_as_tabs',
            [
                'label'     => __( 'Visa som tabbar' , 'webien-search-addon' ),
                'type'      => \Elementor\Controls_Manager::SWITCHER,
                'default'   => 'yes',
                'condition' => [
                    'filter_lineup' => 'horisontal',
                    'list_type' => 'filter'
                ],
            ]
        );


        $this->end_controls_section();



        /** Start Post Types */
        $this->start_controls_section(
            'section_post_types',
            [
                'label' => __('Posttyper', 'webien-search-addon'),
            ]
        );
        $this->add_control(
            'post_type_info',
            [
                'label' => '',
                'type' => \Elementor\Controls_Manager::RAW_HTML,
                'raw' => __( 'Posttyper som aldrig ska komma med i söket kan hanteras via Relevanssi inställningar eller när posttypen registreras. Välj här vilka övriga posttyper som ska <span style="color: #000;">exkluderas</span> i denna lista.', 'webien' ),
                'content_classes' => 'elementor-control-field-description',
            ]
        );

        foreach ($relevanssi_post_types as $post_type) {
            $pt = get_post_type_object($post_type);
            $label = $pt->label;

            $this->add_control(
                'post_type_exclude_'.$post_type,
                [
                    'label'     => __( $label , 'webien-search-addon' ),
                    'type'      => \Elementor\Controls_Manager::SWITCHER,
                    'default'   => 'no'
                ]
            );

        }

        $this->end_controls_section();
        /** End Post Types */




        //----------------- Tabs taken from elementor tabs

        $this->start_controls_section(
            'section_tabs_style',
            [
                'label' => __( 'Tabs', 'elementor' ),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );


        $this->add_control(
            'border_width',
            [
                'label' => __( 'Border Width', 'elementor' ),
                'type' => Controls_Manager::SLIDER,
                'default' => [
                    'size' => 1,
                ],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 10,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} a.pt, {{WRAPPER}} a.pt.active:before, {{WRAPPER}} a.pt.active:after' => 'border-width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'border_color',
            [
                'label' => __( 'Border Color', 'elementor' ),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} a.pt.active, {{WRAPPER}} a.pt.active:before, {{WRAPPER}} a.pt.active:after' => 'border-color: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();

        //----------------- Inner tabs item

        // The style section controls for inner button is copied straight up from The global kit settings, some fixes to target correct markup..
        // web/app/plugins/elementor/core/kits/documents/kit.php


        // Use an array for better readability.
        $button_selectors = [
            '{{WRAPPER}} a.pt'
        ];

        $button_hover_selectors = [
            '{{WRAPPER}} a.pt:hover',
            '{{WRAPPER}} a.pt:focus'
        ];

        $button_selector = implode( ',', $button_selectors );
        $button_hover_selector = implode( ',', $button_hover_selectors );

        $this->start_controls_section(
            'section_buttons',
            [
                'label' => __( 'Buttons', 'elementor' ),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'label' => __( 'Typography', 'elementor' ),
                'name' => 'button_typography',
                'selector' => $button_selector,
            ]
        );

        $this->add_group_control(
            Group_Control_Text_Shadow::get_type(),
            [
                'name' => 'button_text_shadow',
                'selector' => $button_selector,
            ]
        );

        $this->start_controls_tabs( 'tabs_button_style' );

        $this->start_controls_tab(
            'tab_button_normal',
            [
                'label' => __( 'Normal', 'elementor' ),
            ]
        );

        $this->add_control(
            'button_text_color',
            [
                'label' => __( 'Text Color', 'elementor' ),
                'type' => Controls_Manager::COLOR,
                'dynamic' => [],
                'selectors' => [
                    $button_selector => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'button_background_color',
            [
                'label' => __( 'Background Color', 'elementor' ),
                'type' => Controls_Manager::COLOR,
                'dynamic' => [],
                'selectors' => [
                    $button_selector => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'button_box_shadow',
                'selector' => $button_selector,
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'button_border',
                'selector' => $button_selector,
                'fields_options' => [
                    'color' => [
                        'dynamic' => [],
                    ],
                ],
            ]
        );

        $this->add_control(
            'button_border_radius',
            [
                'label' => __( 'Border Radius', 'elementor' ),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%' ],
                'selectors' => [
                    $button_selector => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'tab_button_hover',
            [
                'label' => __( 'Hover', 'elementor' ),
            ]
        );

        $this->add_control(
            'button_hover_text_color',
            [
                'label' => __( 'Text Color', 'elementor' ),
                'type' => Controls_Manager::COLOR,
                'dynamic' => [],
                'selectors' => [
                    $button_hover_selector => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'button_hover_background_color',
            [
                'label' => __( 'Background Color', 'elementor' ),
                'type' => Controls_Manager::COLOR,
                'dynamic' => [],
                'selectors' => [
                    $button_hover_selector => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'button_hover_box_shadow',
                'selector' => $button_hover_selector,
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'button_hover_border',
                'selector' => $button_hover_selector,
                'fields_options' => [
                    'color' => [
                        'dynamic' => [],
                    ],
                ],
            ]
        );

        $this->add_control(
            'button_hover_border_radius',
            [
                'label' => __( 'Border Radius', 'elementor' ),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%' ],
                'selectors' => [
                    $button_hover_selector => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_tab();

        $this->end_controls_tabs();

        $this->add_responsive_control(
            'button_padding',
            [
                'label' => __( 'Padding', 'elementor' ),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', 'em', '%' ],
                'selectors' => [
                    $button_selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
                'separator' => 'before',
            ]
        );

        $this->end_controls_section();
    }




    protected function render()
    {

        if( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
            $this->setup_preview_query();
        } else {
            // Do normal operation for front end
            $param_search_word = isset($_GET['s']) ? $_GET['s'] : '';
            $param_post_types = isset($_GET['pt']) ? $_GET['pt'] : '';
            $variables = isset($_GET['var']) ? $_GET['var'] : [];

            // Return if no search param is present
            if(!isset($_GET['s'])){
                echo ' <b>' . $this->get_title() . '</b>' . __(' visas endast när en sökning är gjord.', 'webien'); return;
                return;
            }
        }


        if(!empty($variables)){
            $variables = explode('|', $variables);
            foreach($variables as $param){
                $arr = explode('=', $param);
                $param_variables[$arr[0]] = $arr[1];
            };
        }

        /*
                // Check that Relevanssi is installed..
                $relevanssi = self::$relevanssi_active;

                if (!$relevanssi) {
                    echo __('Relevanssi är inte aktiverat.. aktivera innan du kan använda', 'webien') . ' <b>' . $widget->get_title() . '</b>!'; return;
                    return;
                }
        */
        $settings = $this->get_settings_for_display();


        // Get the hits from relevanssi
        $hits = \Webien\SearchAddon\SearchAddon::$relevanssi_hits;

        // Get post types of each hit (used to be served by relevanssi..)
        $hits_post_types = [];
        foreach ($hits as $hit){
            array_push($hits_post_types, $hit->post_type);
        }


        global $wp_query;
        $total_count = count($hits_post_types);
        $post_types = [];

        foreach($hits_post_types as $post_type){

            $pt = get_post_type_object($post_type);

            if (isset($post_types[$pt->label])) {
                $post_types[$pt->label]['amount']++;
            }
            else {
                $post_types[$pt->label]['title'] = apply_filters( 'webien/search/modify_post_type_title', $pt->label, $pt ); // Filter if name needs to change

                $post_types[$pt->label]['slug'] = $post_type;
                $post_types[$pt->label]['amount'] = 1;
            }
        }

        // If we have results, allso add the "All" tab
        if(!empty($post_types)){
            $post_types['any']['title'] = apply_filters( 'webien/search/modify_post_type_title', __('Alla', 'webien'), false );
            $post_types['any']['slug'] = 'any';

            // If Relevanssi throttle is reached add a + to count
            if($total_count === (int)get_option( 'relevanssi_throttle_limit') ){
                $total_count = $total_count.'+';
            }

            $post_types['any']['amount'] = $total_count;
        }

        // Move the all to the front
        $lastvalue = end($post_types);
        $lastkey = key($post_types);

        $arr1 = [$lastkey=>$lastvalue];
        array_pop($post_types);
        $post_types = !empty($post_types) ? array_merge($arr1,$post_types) : [];

        // Filter option to
        $post_types = apply_filters( 'webien/search/modify_post_type_array', $post_types);

        // Check the excluded post types
        $relevanssi_post_types = get_option('relevanssi_index_post_types');

        // Remove the bogus post_type
        if (($key = array_search('bogus', $relevanssi_post_types)) !== false) {
            unset($relevanssi_post_types[$key]);
        }

        $exclude_post_types = [];
        foreach ($relevanssi_post_types as $index => $post_type) {
            if ($settings['post_type_exclude_'.$post_type] === 'yes') {
                $exclude_post_types[] = $post_type;
            }
        }

        if ($settings['list_type'] === 'result') {

            $col_desktop = !empty($settings['columns']) ? ' col-desktop-'.$settings['columns'] : '';
            $col_tablet = !empty($settings['columns_tablet']) ? ' col-tablet-'.$settings['columns_tablet'] : '';
            $col_mobile = !empty($settings['columns_mobile']) ? ' col-mobile-'.$settings['columns_mobile'] : '';

            $html = '';
            $html .= '<div class="webien-search-result'.$col_desktop.$col_tablet.$col_mobile.'" 
                data-quantity="' .  /*$settings['results_quantity'] . */ '"
                data-result-quantity="' . /* $settings['results_quantity_manual'] . */ '"
                data-post-types-templates="' . /* htmlspecialchars(json_encode($post_types_templates), ENT_QUOTES, 'UTF-8') . */ '"
                data-variables="{}">';

            //$res = $this->get_sql_posts();

            // create a container for each post type where the results can be ordered in
            $pt_html = '';
            $tab_html = '';
            $post_html = '';

            // Slice array so we dont't parse all
            $per_page = $wp_query->query_vars['posts_per_page'];

            // If we have post type param then we need to skip some of the results
            if(!empty($param_post_types) && $param_post_types !== 'any'){
                $arr = [];
                foreach($hits as $hit){
                    if ($hit->post_type === $param_post_types) {
                        array_push($arr, $hit);
                    }
                }
                $hits = $arr;
            }

            // Limit to per/page number
            $results = array_slice($hits, 0, $per_page);

            // For some external widgets such as Dynamic Fileds from Jet. They have to have query acces of the posts to perform correctly
            // Lets set up the posts from a wp_query.. bloated solution..
            $ids = [];
            foreach($results as $res){
                array_push($ids, $res->ID);
            }

            $args = [
                'post_type' => 'any',
                'numberposts' => -1,
                'post__in' => $ids,
                'post_status' => ['publish', 'inherit']
            ];


            $post_query = new \WP_Query($args);


            if($post_query->have_posts() ) {
                while ($post_query->have_posts()) {
                    $post_query->the_post();


                    // Skip if excluded
                    if(in_array(get_post_type(), $exclude_post_types)){
                        continue;
                    }

                    $postId = get_the_ID();

                    // Loop posts
                    //foreach($results as $post) {

                    // Get template and check if we should use default link
                    $templateId = get_field('webien_search_template_' . get_post_type($postId), 'option');
                    $noLink = get_field('webien_search_template_leave_link_' . get_post_type($postId), 'option') ?: false;

                    /** Try to load template */
                    if ($templateId) {
                        $template = \Elementor\Plugin::instance()->elements_manager->create_element_instance(
                            [
                                'elType' => 'widget',
                                'widgetType' => 'template',
                                'id' => 'template',
                                'settings' => [
                                    'template_id' => $templateId
                                ],
                            ],
                            []
                        );



                        ob_start();
                        $template->print_element();

                        // remove inner links if needed
                        $markup = ob_get_clean();

                        if(!$noLink){
                            $post_html .= '<a href="' . get_permalink($postId) . '" class="item">';
                            $markup = str_replace('<a ', '<span ', $markup);
                            $markup = str_replace('</a>', '</span>', $markup);
                        } else {
                            $post_html .= '<span class="item">';
                        }

                        $post_html .= $markup;
                    }
                    else {
                        /** If we could not load template then use standard markup */
                        $post_html .= '<a href="' . get_permalink($postId) . '" class="item">';
                        $post_html .= '<div class="standard-markup ' . $post->post_type . '">';
                        $post_html .= '<h6>' . get_the_title($postId) . '</h6>';
                        $post_html .= '<p>' . get_the_excerpt($postId) . '</p>';
                        $post_html .= '</div>';
                    }

                    if(!$noLink){
                        $post_html .= '</a>';
                    } else {
                        $post_html .= '</span>';
                    }


                }
            };
            wp_reset_postdata();
            wp_reset_query();


            foreach($post_types as $pt){

                $active = '';
                $inner_html = '';

                if($pt['slug'] === $param_post_types){
                    $active = ' active';
                    $inner_html = $post_html;
                }
                if($pt['slug'] === 'any' && empty($param_post_types)){

                    $active = ' active';
                    $inner_html = $post_html;
                }
                $tab_html .= '<div class="result '.$pt['slug'].$active.'" data-total="'.$pt['amount'].'" data-pt="'.$pt['slug'].'">'.$inner_html.'</div>';
            }


            $html .= $tab_html;

            if(empty($post_html)){
                $html = '<p>' .__('Inga resultat..', 'webien') . '</p>';
            }

            $content = $html;
        }



        if ($settings['list_type'] === 'filter') {

            $html = '';

            $value = isset($wp_query->query['s']) && !empty($wp_query->query['s']) ? $wp_query->query['s'] : false;

            $tabs = isset($settings['show_as_tabs']) && $settings['show_as_tabs'] === 'yes' ? ' show-as-tabs':'';

            $html .= '<div class="webien-search-filter'.$tabs.' lineup-' . $settings['filter_lineup'] . ' text-align-' . $settings['text_align'] . '" 
            data-search-value="' . urlencode($value) . '"
            data-quantity="20"
            data-result-quantity="20"
            >';

            foreach ($post_types as $pt) {
                // Skip if excluded
                if(in_array($pt['slug'], $exclude_post_types)){
                    continue;
                }


                ob_start();
                include(WEBIEN_SEARCH_ADDON_PLUGIN_PATH . '/src/templates/result-filter.php');
                $html .= ob_get_clean();
            }

            $html .= '</div>';

            $content = $html;
        }

        echo $content;

    }


    protected function _content_template() {

    }

    // Elementor preview stuff
    public function setup_preview_query()
    {

        // Get popular search word, can't seem to access this through Elementor document settings any more..
        global $wpdb;
        $sql = "SELECT term FROM wp_relevanssi ORDER by content DESC LIMIT 1";

        $search_word = $wpdb->get_var($sql);

        $args = [
            's' => $search_word,
            'posts_per_page' => 20,
            'post_type' => 'any',
            'post_status' => 'publish'
        ];

        $query = new \WP_Query();
        $query->parse_query($args);

        relevanssi_do_query($query);
    }

}