<?php

namespace GenixCore\Widgets;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use \Elementor\Group_Control_Background;
use \Elementor\Group_Control_Image_Size;
use \Elementor\Repeater;
use \Elementor\Utils;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * Xotric Core
 *
 * Elementor widget for hello world.
 *
 * @since 1.0.0
 */
class TG_Project_Filter extends Widget_Base
{

    /**
     * Retrieve the widget name.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget name.
     */
    public function get_name()
    {
        return 'project-filter';
    }

    /**
     * Retrieve the widget title.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget title.
     */
    public function get_title()
    {
        return __('Project Filter', 'genixcore');
    }

    /**
     * Retrieve the widget icon.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget icon.
     */
    public function get_icon()
    {
        return 'genix-icon';
    }

    /**
     * Retrieve the list of categories the widget belongs to.
     *
     * Used to determine where to display the widget in the editor.
     *
     * Note that currently Elementor supports only one category.
     * When multiple categories passed, Elementor uses the first one.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return array Widget categories.
     */
    public function get_categories()
    {
        return ['genixcore'];
    }

    /**
     * Retrieve the list of scripts the widget depended on.
     *
     * Used to set scripts dependencies required to run the widget.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return array Widget scripts dependencies.
     */
    public function get_script_depends()
    {
        return ['genixcore'];
    }

    /**
     * Register the widget controls.
     *
     * Adds different input fields to allow the user to change and customize the widget settings.
     *
     * @since 1.0.0
     *
     * @access protected
     */
    protected function register_controls()
    {

        // Service group
        $this->start_controls_section(
            '__tg_project_query',
            [
                'label' => esc_html__('Project Query', 'genixcore'),
                'description' => esc_html__('Control all the style settings from Style tab', 'genixcore'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $post_type = 'project';
        $taxonomy = 'project-cat';

        $this->add_control(
            'posts_per_page',
            [
                'label' => esc_html__('Posts Per Page', 'genixcore'),
                'description' => esc_html__('Leave blank or enter -1 for all.', 'genixcore'),
                'type' => Controls_Manager::NUMBER,
                'default' => '6',
            ]
        );

        $this->add_control(
            'category',
            [
                'label' => esc_html__('Include Categories', 'genixcore'),
                'description' => esc_html__('Select a category to include or leave blank for all.', 'genixcore'),
                'type' => Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => genix_get_categories($taxonomy),
                'label_block' => true,
            ]
        );

        $this->add_control(
            'exclude_category',
            [
                'label' => esc_html__('Exclude Categories', 'genixcore'),
                'description' => esc_html__('Select a category to exclude', 'genixcore'),
                'type' => Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => genix_get_categories($taxonomy),
                'label_block' => true
            ]
        );

        $this->add_control(
            'post__not_in',
            [
                'label' => esc_html__('Exclude Item', 'genixcore'),
                'type' => Controls_Manager::SELECT2,
                'options' => genix_get_all_types_post($post_type),
                'multiple' => true,
                'label_block' => true
            ]
        );

        $this->add_control(
            'offset',
            [
                'label' => esc_html__('Offset', 'genixcore'),
                'type' => Controls_Manager::NUMBER,
                'default' => '0',
            ]
        );

        $this->add_control(
            'orderby',
            [
                'label' => esc_html__('Order By', 'genixcore'),
                'type' => Controls_Manager::SELECT,
                'options' => array(
                    'ID' => 'Post ID',
                    'author' => 'Post Author',
                    'title' => 'Title',
                    'date' => 'Date',
                    'modified' => 'Last Modified Date',
                    'parent' => 'Parent Id',
                    'rand' => 'Random',
                    'comment_count' => 'Comment Count',
                    'menu_order' => 'Menu Order',
                ),
                'default' => 'date',
            ]
        );

        $this->add_control(
            'order',
            [
                'label' => esc_html__('Order', 'genixcore'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'asc'     => esc_html__('Ascending', 'genixcore'),
                    'desc'     => esc_html__('Descending', 'genixcore')
                ],
                'default' => 'desc',

            ]
        );

        $this->add_control(
            'ignore_sticky_posts',
            [
                'label' => esc_html__('Ignore Sticky Posts', 'genixcore'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'genixcore'),
                'label_off' => esc_html__('No', 'genixcore'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();

        // TAB_STYLE
        $this->start_controls_section(
            'section_style',
            [
                'label' => esc_html__('Style', 'genixcore'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'genix_portfolio_filter',
            [
                'label' => esc_html__('Filter?', 'genixcore'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'genixcore'),
                'label_off' => esc_html__('No', 'genixcore'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            '__portfolio_columns_section',
            [
                'label' => esc_html__('Portfolio Columns', 'genixcore'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            '__portfolio__for_desktop',
            [
                'label' => esc_html__('Columns for Desktop', 'genixcore'),
                'description' => esc_html__('Screen width equal to or greater than 1200px', 'genixcore'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    12 => esc_html__('1 Columns', 'genixcore'),
                    6 => esc_html__('2 Columns', 'genixcore'),
                    4 => esc_html__('3 Columns', 'genixcore'),
                    3 => esc_html__('4 Columns', 'genixcore'),
                    2 => esc_html__('6 Columns', 'genixcore'),
                    1 => esc_html__('12 Columns', 'genixcore'),
                ],
                'separator' => 'before',
                'default' => '4',
                'style_transfer' => true,
            ]
        );

        $this->add_control(
            '__portfolio__for_laptop',
            [
                'label' => esc_html__('Columns for Laptop', 'genixcore'),
                'description' => esc_html__('Screen width equal to or greater than 992px', 'genixcore'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    12 => esc_html__('1 Columns', 'genixcore'),
                    6 => esc_html__('2 Columns', 'genixcore'),
                    4 => esc_html__('3 Columns', 'genixcore'),
                    3 => esc_html__('4 Columns', 'genixcore'),
                    2 => esc_html__('6 Columns', 'genixcore'),
                    1 => esc_html__('12 Columns', 'genixcore'),
                ],
                'separator' => 'before',
                'default' => '4',
                'style_transfer' => true,
            ]
        );

        $this->add_control(
            '__portfolio__for_tablet',
            [
                'label' => esc_html__('Columns for Tablet', 'genixcore'),
                'description' => esc_html__('Screen width equal to or greater than 768px', 'genixcore'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    12 => esc_html__('1 Columns', 'genixcore'),
                    6 => esc_html__('2 Columns', 'genixcore'),
                    4 => esc_html__('3 Columns', 'genixcore'),
                    3 => esc_html__('4 Columns', 'genixcore'),
                    2 => esc_html__('6 Columns', 'genixcore'),
                    1 => esc_html__('12 Columns', 'genixcore'),
                ],
                'separator' => 'before',
                'default' => '6',
                'style_transfer' => true,
            ]
        );

        $this->add_control(
            '__portfolio__for_mobile',
            [
                'label' => esc_html__('Columns for Mobile', 'genixcore'),
                'description' => esc_html__('Screen width less than 768px', 'genixcore'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    12 => esc_html__('1 Columns', 'genixcore'),
                    6 => esc_html__('2 Columns', 'genixcore'),
                    4 => esc_html__('3 Columns', 'genixcore'),
                    3 => esc_html__('4 Columns', 'genixcore'),
                    5 => esc_html__('5 Columns (For Carousel Item)', 'genixcore'),
                    2 => esc_html__('6 Columns', 'genixcore'),
                    1 => esc_html__('12 Columns', 'genixcore'),
                ],
                'separator' => 'before',
                'default' => '12',
                'style_transfer' => true,
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render the widget output on the frontend.
     *
     * Written in PHP and used to generate the final HTML.
     *
     * @since 1.0.0
     *
     * @access protected
     */
    protected function render()
    {

        $settings = $this->get_settings_for_display();

        if (get_query_var('paged')) {
            $paged = get_query_var('paged');
        } else if (get_query_var('page')) {
            $paged = get_query_var('page');
        } else {
            $paged = 1;
        }

        // include_categories
        $category_list = '';
        if (!empty($settings['category'])) {
            $category_list = implode(", ", $settings['category']);
        }
        $category_list_value = explode(" ", $category_list);

        // exclude_categories
        $exclude_categories = '';
        if (!empty($settings['exclude_category'])) {
            $exclude_categories = implode(", ", $settings['exclude_category']);
        }
        $exclude_category_list_value = explode(" ", $exclude_categories);

        $post__not_in = '';
        if (!empty($settings['post__not_in'])) {
            $post__not_in = $settings['post__not_in'];
            $args['post__not_in'] = $post__not_in;
        }
        $posts_per_page = (!empty($settings['posts_per_page'])) ? $settings['posts_per_page'] : '-1';
        $orderby = (!empty($settings['orderby'])) ? $settings['orderby'] : 'post_date';
        $order = (!empty($settings['order'])) ? $settings['order'] : 'desc';
        $offset_value = (!empty($settings['offset'])) ? $settings['offset'] : '0';
        $ignore_sticky_posts = (!empty($settings['ignore_sticky_posts']) && 'yes' == $settings['ignore_sticky_posts']) ? true : false;


        // number
        $off = (!empty($offset_value)) ? $offset_value : 0;
        $offset = $off + (($paged - 1) * $posts_per_page);
        $p_ids = array();

        // build up the array
        if (!empty($settings['post__not_in'])) {
            foreach ($settings['post__not_in'] as $p_idsn) {
                $p_ids[] = $p_idsn;
            }
        }

        $args = array(
            'post_type' => 'project',
            'post_status' => 'publish',
            'posts_per_page' => $posts_per_page,
            'orderby' => $orderby,
            'order' => $order,
            'offset' => $offset,
            'paged' => $paged,
            'post__not_in' => $p_ids,
            'ignore_sticky_posts' => $ignore_sticky_posts
        );

        // exclude_categories
        if (!empty($settings['exclude_category'])) {

            // Exclude the correct cats from tax_query
            $args['tax_query'] = array(
                array(
                    'taxonomy'    => 'project-cat',
                    'field'         => 'slug',
                    'terms'        => $exclude_category_list_value,
                    'operator'    => 'NOT IN'
                )
            );

            // Include the correct cats in tax_query
            if (!empty($settings['category'])) {
                $args['tax_query']['relation'] = 'AND';
                $args['tax_query'][] = array(
                    'taxonomy'    => 'project-cat',
                    'field'        => 'slug',
                    'terms'        => $category_list_value,
                    'operator'    => 'IN'
                );
            }
        } else {
            // Include the cats from $cat_slugs in tax_query
            if (!empty($settings['category'])) {
                $args['tax_query'][] = [
                    'taxonomy' => 'project-cat',
                    'field' => 'slug',
                    'terms' => $category_list_value,
                ];
            }
        }

        $filter_list = $settings['category'];

        // The Query
        $query = new \WP_Query($args);

        $i = 1;
?>

        <script>
            jQuery(document).ready(function($) {

                /*=============================================
                    =    		Isotope	Active  	      =
                =============================================*/
                $('.new-project-active').imagesLoaded(function() {
                    // init Isotope
                    var $grid = $('.new-project-active').isotope({
                        itemSelector: '.grid-item',
                        percentPosition: true,
                        masonry: {
                            columnWidth: '.grid-sizer',
                        }
                    });
                    // filter items on button click
                    $('.project-menu').on('click', 'button', function() {
                        var filterValue = $(this).attr('data-filter');
                        $grid.isotope({
                            filter: filterValue
                        });
                    });
                });
                //for menu active class
                $('.project-menu button').on('click', function(event) {
                    $(this).siblings('.active').removeClass('active');
                    $(this).addClass('active');
                    event.preventDefault();
                });

            });
        </script>

        <?php if (!empty($settings['genix_portfolio_filter'])) : ?>
            <div class="row new-project-filter">
                <div class="col-12 text-center">
                    <div class="project-menu d-flex flex-wrap align-items-center justify-content-center">
                        <?php if (!empty($filter_list)) : foreach ($filter_list as $list) : $term = get_term_by('name', $list, 'project-cat'); ?>
                                <?php if ($i === 1) : $i++; ?>
                                    <button class="active filter-tab-item" data-filter="*"><span><?php echo esc_html__('All', 'genixcore'); ?></span><span class="count">(<?php echo esc_html($settings['posts_per_page']); ?>)</span></button>
                                    <button class="filter-tab-item" data-filter=".<?php echo esc_attr($list); ?>"><span><?php echo esc_html($list); ?></span><span class="count">(<?php echo $term->count; ?>)</span></button>
                                <?php else : ?>
                                    <button class="filter-tab-item" data-filter=".<?php echo esc_attr($list); ?>"><span><?php echo esc_html($list); ?></span><span class="count">(<?php echo $term->count; ?>)</span></button>
                                <?php endif; ?>
                        <?php endforeach;
                        endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="row new-project-active">

            <?php while ($query->have_posts()) :
                $query->the_post();
                global $post;
                $terms = get_the_terms($post->ID, 'project-cat');
                $item_classes = '';
                $item_cat_names = '';
                $item_cats = get_the_terms($post->ID, 'project-cat');
                if (!empty($item_cats)) :
                    $count = count($item_cats) - 1;
                    foreach ($item_cats as $key => $item_cat) {
                        $item_classes .= $item_cat->slug . ' ';
                        $item_cat_names .= ($count > $key) ? $item_cat->name  . ', ' : $item_cat->name;
                    }
                endif;

                $categories = get_the_terms($post->ID, 'project-cat');
            ?>
                <div class="col-xl-<?php echo esc_attr($settings['__portfolio__for_desktop']); ?> col-lg-<?php echo esc_attr($settings['__portfolio__for_laptop']); ?> col-md-<?php echo esc_attr($settings['__portfolio__for_tablet']); ?> col-<?php echo esc_attr($settings['__portfolio__for_mobile']); ?> grid-item grid-sizer <?php echo $item_classes; ?>">
                    <div class="filter-post-item">
                        <div class="filter-post-thumb">
                            <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('full', ['class' => 'w-100']); ?></a>
                        </div>
                        <div class="filter-post-content">
                            <h2 class="title">
                                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            </h2>
                            <span><?php echo esc_html($categories[0]->name); ?></span>
                        </div>
                    </div>
                </div>
            <?php endwhile;
            wp_reset_query(); ?>
        </div>

<?php
    }
}

$widgets_manager->register(new TG_Project_Filter());
