<?php

/**
 * Common Blocks Configs Handler
 * 
 * Setup the correct term whether it's a category, tag, or custom taxonomy.
 * 
 * @see Bunyad_ShortCodes::__call()
 */

class Bunyad_Block_Motive {
	
	public $_atts = array();
	public $_sc_handle;
	public $_data = array();
	
	/**
	 * Bootstrap with necessary data
	 * 
	 * @param array   $atts  array of shortcode attributes from Bunyad_Shortcodes::__call()
	 * @param string  $tag   shortcode tag
	 * @param object  $sc_handle   Bunyad_Shortcodes reference
	 */
	public function __construct($atts, $tag, $sc_handle = null) 
	{	
		$this->_atts = $atts;
		$this->_tag  = $tag; 
		$this->_sc_handle = $sc_handle;
	}
	
	/**
	 * Process the data to setup the block query 
	 */
	public function process()
	{
		extract($this->_atts, EXTR_SKIP);
		
		// have query args?
		$query_args = array();
		if (isset($this->_data['query_args']) && is_array($this->_data['query_args'])) {
			$query_args = $this->_data['query_args'];
		}
	
		$query_args = array_merge($query_args, array(
			'posts_per_page' => (!empty($posts) ? intval($posts) : 4), 
			'order' => ($sort_order == 'asc' ? 'asc' : 'desc'), 
			'offset' =>  ($offset ? $offset : '')
		));
		
		// add page if available
		$page = (is_front_page() ? get_query_var('page') : get_query_var('paged'));
		if (!empty($pagination) && !empty($page)) {
			$query_args['paged'] = $page;
		}
	
		
		// sorting criteria
		switch ($sort_by) {
			case 'modified':
				$query_args['orderby'] = 'modified';
				break;
				
			case 'random':
				$query_args['orderby'] = 'random';
				break;
	
			case 'comments':
				$query_args['orderby'] = 'comment_count';
				break;
				
			case 'alphabetical':
				$query_args['orderby'] = 'title';
				break;
				
			case 'rating':
				$query_args = array_merge($query_args, array('meta_key' => '_bunyad_review_overall', 'orderby' => 'meta_value_num'));
				break; 	
		}
	
		
		// use term ids
		$term_ids = array_filter(explode(',', $terms));
		$term = '';
		
		// template helper variables
		$term_id   = '';
		$term_wrap = array('block-wrap');
		
			
		/**
		 * Limit by custom taxonomy?
		 */
		if (!empty($taxonomy)) {
	
			$_taxonomy = $taxonomy; // preserve
			
			// get the tag
			$term = get_term_by('id', (!empty($cat) ? $cat : current($term_ids)), $_taxonomy);
			
			$query_args['tax_query'] = array(array(
				'taxonomy' => $_taxonomy,
				'field' => 'id',
				'terms' => (array) $term_ids
			));
			
			if (empty($title)) {
				$title = $term->slug; 
			}
			
			$link = get_term_link($term, $_taxonomy);
			
		}
		else {
		
			/*
			 * Got main category/term? Use it for filter, link, and title
			 */
			if (!empty($cat)) {
				
				// get latest from the specified category
				$term = $category = is_numeric($cat) ? get_category($cat) : get_category_by_slug($cat);
				
				if (!empty($category)) {
					array_push($term_ids, $category->term_id);
						
					if (empty($title)) {
						$title = $category->cat_name;
					}
				
					$link = get_category_link($category);
				}
			}
			
			/*
			 * Filtering by a tag?
			 */
			if (!empty($tags)) {
		
				// add query filter supporting multiple tags separated with comma
				$query_args['tag'] = $tags;
				
				// get the first tag
				$tax_tag = current(explode(',', $tags));
				$term = get_term_by('slug', $tax_tag, 'post_tag');
				
				if (empty($title)) {
					$title = $term->slug; 
				}
				
				if (empty($link)) {
					$link = get_term_link($term, 'post_tag');
				}
			}
			
			/*
			 * Multiple categories/terms filter
			 */
			if (count($term_ids)) {
				$query_args['cat'] = join(',', $term_ids);
			}
		}
		
		/**
		 * Post Formats?
		 */
		if (!empty($post_format)) {
			
			if (!isset($query_args['tax_query'])) {
				$query_args['tax_query'] = array();
			}
			
			$query_args['tax_query'][] = array(
				'taxonomy' => 'post_format',
				'field' => 'slug',
				'terms' => array('post-format-' . $post_format),
			);
		}
		
		/**
		 * Custom Post Types?
		 */
		if (!empty($post_type)) {
			$query_args['post_type'] = array_map('trim', explode(',', $post_type));
		}
		
		
		/**
		 * Execute the query
		 */
		
		// add a filter - $tag comes from Bunyad_Shortcodes:__call() magic handler
		$query_args = apply_filters('bunyad_block_query_args', $query_args, $this->_tag, $this->_atts);
		$query = new WP_Query($query_args);
	
		
		// set our category, tag, or custom taxonomy id  in $term_id
		if (is_object($term) && !empty($term->term_id)) {
			$term_id = $term->term_id;
			$term_wrap[] = esc_attr('term-wrap-' . $term->term_id);
		}
	
		// set title link if possible
		if (!empty($link)) {
			$title_link = '<a href="' . esc_url($link) .'">' . esc_html($title) . '</a>';
		}
		else {
			$title_link = $title;
		}
		
		// disable title if empty
		if (empty($title_link)) {
			$title_type = 'none';
		}
		
		
		/**
		 * Custom CSS for main color
		 */
		if (!empty($main_color)) {
			
			// add to shortcode counters - for suffix
			$this->_sc_handle->counter++;
				
			$term_wrap[] = $selector = esc_attr($this->_sc_handle->css_suffix('block-css'));
			
			echo "
			<style>
				
			.{$selector} .read-more a, .{$selector} .image-overlay { background: {$main_color}; }
			.{$selector} .section-head .title { background: {$main_color}; }
			.{$selector} .section-head { border-color: {$main_color}; }
				
			</style>
			";
		}
		
		// setup accessible variables
		$this->_data = array_merge($this->_data, array(
			'title_link' => $title_link,
			'link'       => $link,
			'query_args' => $query_args,
			'query'      => $query,
			'term_wrap'  => join(' ', $term_wrap),
			'term_id'    => $term_id,
		
			// set current column width weight (width/100) - used to determine image sizing 
			'col_relative_width' =>  Bunyad::get('motive')->block_relative_width()
		));
				
		return $this;
	}
	
	public function output_title()
	{
		extract($this->_atts, EXTR_SKIP);
		
		// no title?
		if (!$this->title_link) {
			return;
		}
		
		
		if (empty($title_type) OR $title_type == 'default'):
		
		?>
		
		<h4 class="section-head cf cat-border-<?php echo esc_attr($this->term_id); ?>">
			<span class="title"><?php echo $this->title_link; // generated in $title_link above - esc_*() functions pre-applied ?></span>
			
			<?php if ($view_all): ?>
				<a href="<?php echo esc_url($this->link); ?>" class="more"><?php _e('View all', 'bunyad'); ?> <i class="fa fa-caret-right"></i></a>
			<?php endif; ?>
			
					
			<?php if (!empty($sub_title)): ?>
				<span class="sub-title"><?php echo esc_html($sub_title); ?></span>
			<?php endif; ?>
		</h4>

		
		
		<?php
		elseif ($title_type == 'small'):
		?>
		
		<h4 class="section-head-small cf cat-border-<?php echo esc_attr($this->term_id); ?>">
			<span class="title"><?php echo $this->title_link; // generated in $title_link above - esc_*() functions pre-applied ?></span>
			
			<?php if ($view_all): ?>
				<a href="<?php echo esc_url($this->link); ?>" class="more"><?php _e('View all', 'bunyad'); ?> <i class="fa fa-caret-right"></i></a>
			<?php endif; ?>
		</h4>
		
		<?php 
		endif;
	}

	
	public function __get($key) 
	{
		return $this->get($key);
	}
	
	public function get($key)
	{
		if (!isset($this->_data[$key])) {
			return;
		}
		
		return $this->_data[$key];
	}
}