<?php

namespace PowerElements\Helpers;

class Partials{

    function __construct(){}

    private static $post_args = [
        // content ticker
        'power_ticker_type',
        'power_ticker_custom_contents',
        
        // post grid
        'power_post_grid_columns',
        
        // common 
        'meta_position',
        'power_show_meta',
        'image_size',
        'power_show_image',
        'power_show_title',
        'power_show_excerpt',
        'power_excerpt_length',
        'power_show_read_more',
        'power_read_more_text',
        'show_load_more',
        'show_load_more_text',
        
        // query_args
        'post_type',
        'post__in',
        'posts_per_page',
        'post_style',
        'tax_query',
        'post__not_in',
        'power_post_authors',
        'eaeposts_authors',
        'offset',
        'orderby',
        'order',
    ];
    
    
    static function get_rating_html( $number ) {
        $wpbucket_ratting = $number;
        $ratting_html     = '';
        $integer          = (int) $wpbucket_ratting;
        $decimal          = $wpbucket_ratting - $integer;
        $remain           = 5 - (int) $wpbucket_ratting;
        $count            = 0;
        for ( $i = 1; $i <= $integer; $i ++ ) {
            $ratting_html .= '<li><i class="fa fa-star"></i></li>';
            $count        += 1;
        }
        if ( $decimal > 0 ) {
            $ratting_html .= '<li><i class="fa fa-star-half"></i></li>';
            $count        += 1;
        }
        
        if ( $remain > 0 ) {
            $integer = 5 - $count;
            if ( $integer > 0 ) {
                for ( $i = 1; $i <= $integer; $i ++ ) {
                    $ratting_html .= '<li><i class="fa fa-star-o"></i></li>';
                }
            }
        }
        
        
        $rating_html = '<ul class="power_testimonial_reviewer_rating">' . balanceTags( $ratting_html ) . '</ul>';
        
        return $rating_html;
        
    }
    
    /**
     * Get all types of post.
     * @return array
     */
    public static function get_all_types_post(){
        $posts_args = [
            'post_type' => 'any',
            'post_style' => 'all_types',
            'post_status' => 'publish',
            'posts_per_page' => '-1',
        ];
        $posts = self::load_more_ajax($posts_args);
        
        $post_list = [];
        
        foreach ($posts as $post) {
            $post_list[$post->ID] = $post->post_title;
        }
        
        return $post_list;
    }
    
    /**
     * This function is responsible for get the post data.
     * It will return HTML markup with AJAX call and with normal call.
     *
     * @return string of an html markup with AJAX call.
     * @return array of content and found posts count without AJAX call.
     */
    public static function load_more_ajax(){

        $args = func_get_args();
        $post_args = $args[0];
        $posts = new \WP_Query($post_args);
        
        /**
         * For returning all types of post as an array
         * @return array;
         */
        if (isset($post_args['post_style']) && $post_args['post_style'] == 'all_types') {
            return $posts->posts;
        }
        
        $return = [];
        $return['count'] = $posts->found_posts;
        ob_start();
        
        while ($posts->have_posts()): $posts->the_post();
            require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/content/content.php' );
        endwhile;
        
        $return['content'] = ob_get_clean();
        
        wp_reset_postdata();
        wp_reset_query();
        
        if (isset($_POST['action']) && $_POST['action'] == 'load_more') {
            wp_send_json($return['content']);
        } else {
            return $return;
        }
    }


    public static function load_blog_posts($args, $widget_id){

        $args = func_get_args();
        $post_args = $args[0];
        $posts = new \WP_Query($post_args);
        
        /**
         * For returning all types of post as an array
         * @return array;
         */
        if (isset($post_args['post_style']) && $post_args['post_style'] == 'all_types') {
            return $posts->posts;
        }
        
        $return = [];
        $return['count'] = $posts->found_posts;
        ob_start();
        
        while ($posts->have_posts()): $posts->the_post();
            require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/'.$widget_id.'/content.php' );
        endwhile;
        
        $return['content'] = ob_get_clean();
        
        wp_reset_postdata();
        wp_reset_query();
        
        if (isset($_POST['action']) && $_POST['action'] == 'load_more') {
            wp_send_json($return['content']);
        } else {
            return $return;
        }
    }
    

    public static function load_blogposts(){

        $args = func_get_args();
        $post_args = $args[0];
        $posts = new \WP_Query($post_args);
        
        /**
         * For returning all types of post as an array
         * @return array;
         */
        if (isset($post_args['post_style']) && $post_args['post_style'] == 'all_types') {
            return $posts->posts;
        }
        
        $return = [];
        $return['count'] = $posts->found_posts;
        ob_start();
        
        while ($posts->have_posts()): $posts->the_post();
            require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/blog/content.php' );
        endwhile;
        
        $return['content'] = ob_get_clean();
        
        wp_reset_postdata();
        wp_reset_query();
        
        if (isset($_POST['action']) && $_POST['action'] == 'load_more') {
            wp_send_json($return['content']);
        } else {
            return $return;
        }
    }

    
		/**
		 * Get All POst Types
		 * @return array
		 */
		public static function get_post_types(){
			$power_cpts = get_post_types(['public' => true, 'show_in_nav_menus' => true], 'object');
			$power_exclude_cpts = ['elementor_library', 'attachment'];
			
			foreach ($power_exclude_cpts as $exclude_cpt) {
				unset($power_cpts[$exclude_cpt]);
			}
			$post_types = array_merge($power_cpts);
			foreach ($post_types as $type) {
				$types[$type->name] = $type->label;
			}
			
			return $types;
		}
		
		/**
		 * Post Settings Parameter
		 * @param  array $settings
		 * @return array
		 */
		public static function get_post_settings($settings){
			foreach ($settings as $key => $value) {
				if (in_array($key, self::$post_args)) {
					$post_args[$key] = $value;
				}
			}
			$post_args['post_status'] = 'publish';
			
			return $post_args;
		}
		
		public static function get_query_args($control_id, $settings, $widget_id){
			$defaults = [
				$control_id . '_post_type' => 'post',
				$control_id . '_posts_ids' => [],
				'orderby' => 'date',
				'order' => 'desc',
				'posts_per_page' => 3,
				'offset' => 0,
			];
			
			$settings = wp_parse_args($settings, $defaults);
			
			$post_type = $settings[$control_id . '_post_type'];
			
			$query_args = [
				'orderby' => $settings['peeao_'.$widget_id.'_orderby'],
				'order' => $settings['peeao_'.$widget_id.'_order'],
				'ignore_sticky_posts' => 1,
				'post_status' => 'publish', // Hide drafts/private posts for admins
			];
			
			if ('by_id' === $post_type) {
				$query_args['post_type'] = 'any';
				$query_args['post__in'] = $settings[$control_id . '_posts_ids'];
				
				if (empty($query_args['post__in'])) {
					// If no selection - return an empty query
					$query_args['post__in'] = [0];
				}
			} else {
				$query_args['post_type'] = $post_type;
				$query_args['posts_per_page'] = $settings['peeao_'.$widget_id.'_posts_per_page'];
				$query_args['tax_query'] = [];
				
				$query_args['offset'] = $settings['peeao_'.$widget_id.'_offset'];
				
				$taxonomies = get_object_taxonomies($post_type, 'objects');
				foreach ($taxonomies as $object) {
					$setting_key = $control_id . '_' . $object->name . '_ids';
					
					if (!empty($settings[$setting_key])) {
						$query_args['tax_query'][] = [
							'taxonomy' => $object->name,
							'field' => 'term_id',
							'terms' => $settings[$setting_key],
						];
					}
				}
			}
			
			if (!empty($settings[$control_id . '_authors'])) {
				$query_args['author__in'] = $settings[$control_id . '_authors'];
			}
			
			$post__not_in = [];
			if (!empty($settings['peeao_'.$widget_id.'_post__not_in'])) {
				$post__not_in = array_merge($post__not_in, $settings['post__not_in']);
				$query_args['post__not_in'] = $post__not_in;
			}
			
			if (isset($query_args['tax_query']) && count($query_args['tax_query']) > 1) {
				$query_args['tax_query']['relation'] = 'OR';
			}
			
			return $query_args;
		}
		
		/**
		 * Template for categories lists.
		 *
		 * @param $post_id
		 * @param $no_icon for fontawesome control
		 * @param $taxonomy for custom taxonomy
		 */
		public static function get_categories_lists($post_id, $taxonomy = null){
			if ($taxonomy == null) {
				$getCats = get_the_category($post_id);
			} else {
				$getCats = get_the_terms($post_id, $taxonomy);
			}
			$html ='';
			if (is_array($getCats)) {
				foreach ($getCats as $key => $cat) {
					if (count($getCats)==1 || $key==count($getCats)-1){
						$coma ='';
					}else{
						$coma ='';
					}

					if ($taxonomy==null) { 
						$html .= '<a href="' . get_category_link($cat->term_id) . '">' . " " . $cat->name . ' </a>'.$coma;
					}else{
						$html .= '<a href="' . get_term_link($cat->term_id,$taxonomy) . '">' . " " . $cat->name . ' </a>'.$coma;
					}
				}
			}
			return $html;
		}
		
		public static function load_filter($args, $widget_id){
			
			$args = func_get_args();
			$post_args = $args[0];
			if(is_array($post_args['tax_query']) && !empty($post_args['tax_query']))
				$term_ids = $post_args['tax_query'][0]['terms'];
			else
				$term_ids = null;
			
			$posts = new \WP_Query($post_args);
			
			/**
			 * For returning all types of post as an array
			 * @return array;
			 */
			if (isset($post_args['peeao_'.$widget_id.'_post_style']) && $post_args['peeao_'.$widget_id.'_post_style'] == 'all_types') {
				return $posts->posts;
			} 
			
			$return = [];
			$return['count'] = $posts->found_posts; 

			
			ob_start();
			
			if ($post_args['peeao_'.$widget_id.'_show_filter']=='yes') {
				require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/'.$widget_id.'/wrapper.php' );
				require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/'.$widget_id.'/filter.php' );
				require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/'.$widget_id.'/wrapper-end.php' );
			}
			
			require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/'.$widget_id.'/content-wrapper.php' );
			while ($posts->have_posts()): $posts->the_post();
			
				if ($posts->current_post % 2 == 0):
					$arr = ['left info' , 'right'];
				else:
					$arr = ['right info' , 'left'];
				endif;
				require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/'.$widget_id.'/content.php' );
			endwhile;
			require( POWER_ELEMENTS_DIR_PATH . '/widgets/parts/'.$widget_id.'/content-wrapper-end.php' );
			
			$return['content'] = ob_get_clean();
			
			wp_reset_postdata();
			wp_reset_query();
			
			return $return;
        }
        public static function get_all_nested_templates(){
			
			$args = [ 
				'post_type' => 'peeao_nested',
				'post_status' => 'publish',
			];
			$query = new \WP_Query( $args );
			
			$templates = [];
			if ( $query->have_posts() ) :
				while ( $query->have_posts() ) : $query->the_post();
					$templates[get_the_ID()] = get_the_title();
				endwhile;
			endif;
			wp_reset_postdata();

			return $templates;
		}
		public static function get_all_forms(){
			
			$args = [ 
				'post_type' => 'peeao_form',
				'post_status' => 'publish',
			];
			$query = new \WP_Query( $args );
			
			$templates = [];
			if ( $query->have_posts() ) :
				while ( $query->have_posts() ) : $query->the_post();
					$templates[get_the_ID()] = get_the_title();
				endwhile;
			endif;
			wp_reset_postdata();

			return $templates;
		}
}