<?php namespace Webien\Elementor\Widgets\Tabs;

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;
use Elementor\Scheme_Typography;

class Widget extends \Elementor\Widget_Base
{

    public function get_name()
    {
        return 'webien_tabs';
    }

    public function get_title()
    {
        return __('Webien tabbar', 'webien');
    }

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

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

    public function get_script_depends() {
        return ['webien-tabs'];
    }

    public function get_style_depends() {
        return [];
    }

    protected function is_dynamic_content(): bool {
        return true;
    }

    protected function register_controls()
    {

        $this->start_controls_section(
            'section_content',
            [
                'label' => __('Allmänt', 'webien'),
            ]
        );
        $this->add_control(
            'content_type',
            [
                'label' => __('Innehåll baserat på', 'webien'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'current_page' => __('Aktuell sida', 'webien'),
                    'taxonomy' => __('Taxanomi', 'webien'),
                    'manual' => __('Manuellt urval', 'webien'),
                ],
                'default' => 'current_page',
            ]
        );

        $this->add_control(
            'manual_posts',
            [
                'label'   => __('Inkludera poster', 'webien'),
                'description'   => __( 'Ange post id:n på de poster du vill inkludera oberoende av posttyp. Separera med kommatecken.' , 'webien' ),
                'type'    => \Elementor\Controls_Manager::TEXT,
                'default' => __('', 'webien'),
                'condition' => [
                    'content_type' => 'manual',
                ],
            ]
        );

        $taxonomies = get_taxonomies([], 'objects');
        $options = [];
        foreach ( $taxonomies as $taxonomy ) {
            if($taxonomy->public){
                $options[$taxonomy->name] = $taxonomy->label;
            }

        }

        $this->add_control(
            'taxonomy',
            [
                'label' => __( 'Choose a taxonomy', 'webien' ),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => $options,
                'classes' => 'taxonomy',
                'condition' => [
                    'content_type' => 'taxonomy',
                ],
            ]
        );

        $this->add_control(
            'show_current_breadcrumb',
            [
                'label'     => __( 'Visa aktuell sida i tabbar' , 'webien' ),
                'type'      => \Elementor\Controls_Manager::SWITCHER,
                'default'   => 'yes'
            ]
        );

        $this->add_control(
            'show_current',
            [
                'label'     => __( 'Visa aktuell sidas innehåll' , 'webien' ),
                'type'      => \Elementor\Controls_Manager::SWITCHER,
                'default'   => 'no'
            ]
        );

        $this->add_control(
            'show_children',
            [
                'label'     => __( 'Visa barn' , 'webien' ),
                'type'      => \Elementor\Controls_Manager::SWITCHER,
                'default'   => 'yes'
            ]
        );

        $this->add_control(
            'max_posts',
            [
                'label'     => __('Maximalt antal att visa', 'webien'),
                'description'     => __('0 visar alla.', 'webien'),
                'type'      => \Elementor\Controls_Manager::NUMBER,
                'default'   => 0,
                'min'       => 0,
                'max'       => 50,
                'condition' => [
                    'content_type!' => 'manual',
                ],
            ]
        );

        $this->add_control(
            'link_note',
            [
                'label' => '',
                'type' => \Elementor\Controls_Manager::RAW_HTML,
                'raw' => '<span style="display:block;background:#eceeef;padding:15px;font-size:12px;border-radius:8px;">' . __('För att få fram direktlänk till aktiv tab, håll ner "<b>t</b>" och klicka på tabben ute på sidan.', 'webien') . '</span>',
            ]
        );



        $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_outer_selectors = [
            '{{WRAPPER}} .tabs'
        ];

        $button_selectors = [
            '{{WRAPPER}} button.tab'
        ];

        $button_hover_selectors = [
            '{{WRAPPER}} button.tab:hover',
            '{{WRAPPER}} button.tab:focus'
        ];

        $button_active_selectors = [
            'body {{WRAPPER}} button.active',
        ];

        $button_selector = implode( ',', $button_selectors );
        $button_hover_selector = implode( ',', $button_hover_selectors );
        $button_active_selector = implode( ',', $button_active_selectors );
        $button_outer_selector = implode( ',', $button_outer_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->add_responsive_control(
            'button_outer_margin',
            [
                'label' => __( 'Button margin', 'elementor' ),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', 'em', '%' ],
                'selectors' => [
                    $button_selector => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $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->start_controls_tab(
            'tab_button_active',
            [
                'label' => __( 'Active', 'elementor' ),
            ]
        );

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

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

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

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

        $this->add_control(
            'button_active_border_radius',
            [
                'label' => __( 'Border Radius', 'elementor' ),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%' ],
                'selectors' => [
                    $button_active_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}};',
                ],
            ]
        );

        $this->end_controls_section();



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

        $this->add_control(
            'nowrap',
            [
                'label'     => __( 'Håll på en rad' , 'webien' ),
                'type'      => \Elementor\Controls_Manager::SWITCHER,
                'default'   => 'yes'
            ]
        );


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

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

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

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

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

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


        $this->end_controls_section();

    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();


        if($settings['content_type'] === 'current_page') {
            global $post;

            $post_ids = [];

            array_push($post_ids, $post->ID);

            $numberposts = $settings['max_posts'] === 0 ? -1 : $settings['max_posts'];

            if($settings['show_children'] === 'yes'){
                 $args = [
                     'post_type'     => $post->post_type,
                     'fields'        => 'ids',
                     'orderby'       => 'menu_order',
                     'order'         => 'asc',
                     'post_parent'   => $post->ID,
                     'numberposts'  => $numberposts
                 ];
                 $posts = get_posts($args);

                 foreach ($posts as $id) {
                    array_push($post_ids, $id);
                 }
            }
            $posts = $post_ids;
        }


        if($settings['content_type'] === 'taxonomy') {

            $taxonomy = $settings['taxonomy'];
            $terms = get_terms( $taxonomy );
            $term_ids = wp_list_pluck( $terms, 'term_id' );

            $numberposts = $settings['max_posts'] === 0 ? -1 : $settings['max_posts'];
            $include_children = $settings['show_children'] === 'yes' ?:false;

            $args = [
                'post_type' => 'any',
                'fields'    => 'ids',
                'orderby'   => 'menu_order',
                'numberposts' => $numberposts,
                'tax_query' => [
                    [
                        'taxonomy'  => $taxonomy,
                        'field'     => 'term_id',
                        'terms'     => $term_ids,
                        'include_children' => $include_children,
                        'operator' => 'IN',
                    ]
                ]
            ];

            $posts = get_posts($args);
        }


        if ($settings['content_type'] === 'manual') {
            $manual_ids = explode(',', $settings['manual_posts']);
            $arr = [];
            foreach ($manual_ids as $id) {
                $post_id = (int)trim($id);
                array_push($arr, $post_id);

                if($settings['show_children'] === 'yes'){
                    $args = [
                        'post_type'     => 'any',
                        'fields'        => 'ids',
                        'orderby'       => 'menu_order',
                        'post_parent'   => $post_id,
                    ];
                    $posts = get_posts($args);

                    foreach ($posts as $id) {
                        array_push($arr, $id);
                    }
                }
            }

            $posts = $arr;
        }


        $tabs = '';
        $tabs_content = "";
        $i=0;

        $inAdmin = is_admin() ||
            \Elementor\Plugin::$instance->preview->is_preview_mode() ||
            \Elementor\Plugin::$instance->editor->is_edit_mode() ||
            (isset($_SERVER['HTTP_REFERER']) && (strpos($_SERVER['HTTP_REFERER'], 'action=elementor') !== false)); // in templates the other ones won't work

        foreach($posts as $id){

            $i++;

            // Check if post is Elementor edited
            $isElementor = \Elementor\Plugin::$instance->documents->get( $id )->is_built_with_elementor();

            $elementorClass = '';
            $content = '';

            if ($isElementor) {

                // To avoid recursion i Elementor, collision of current IDs, etc
                // Generate a post content widget if we try to display the content of the current page
                if ( get_the_ID() === (int) $id ) {
                    $widget = \Elementor\Plugin::instance()->elements_manager->create_element_instance(
                        [
                            'elType' => 'widget',
                            'widgetType' => 'theme-post-content',
                        ],
                        []
                    );

                    ob_start();
                    $widget->print_element();
                    $content = ob_get_clean();
                    ob_flush();
                }
                else {
                    $content = \Elementor\Plugin::$instance->frontend->get_builder_content_for_display($id, true);
                    $content = apply_filters('elementor/frontend/the_content', $content);
                }

                $elementorClass = ' elementor-content';
            }
            else {
                $post = get_post($id);
                $content = $post->post_content;
                $content = apply_filters('the_content', $content);
                $content = str_replace(']]>', ']]&gt;', $content);

            }


            $active = $i===1 ? ' active': '';

            if( $i === 1 && $settings['show_current'] !== 'yes') {
                // Do nothing
            } else {

                // Since we are displaying content from another source,
                // we need to disable indexing for the duplicated content.
                if($i === 2){
                    $tabs_content .= '<!--googleoff: index-->';
                }

                $tabs_content .= '<div class="tab-content'.$active.$elementorClass.'" data-id="'.$id.'">'.$content.'</div>';

                // Switch google robots on again if last tab
                if($i === count($posts)){
                    $tabs_content .= '<!--googleon: index-->';
                }
            }

            if(count($posts) > 1){ // Only show if more then one
                if( $i === 1 && $settings['show_current_breadcrumb'] !== 'yes') {
                    continue;
                } else {

                    $url = explode('?', $_SERVER['REQUEST_URI'], 2);
                    $slug = get_post_field( 'post_name', $id );
                    $activeTabLink = get_home_url() . $url[0] . '?activeTab=' . $slug;


                    $url = $i !== 1 ? get_permalink($id):'';
                    $tabs .= '<button class="tab'.$active.'" data-id="'.$id.'" data-url="' . $url . '" data-slug="' . $slug . '" data-direct-url="' . $activeTabLink . '">'.get_the_title($id).'</button>';

                }
            }
        }


        wp_reset_postdata();

        ob_start();
        include('view.php');
        $html = ob_get_clean();

        echo $html;



    }



    protected function _content_template()
    {

    }



}
