<?php

/////////////////////////////////////////////////////
// [g-collection]
function gg_collection_shortcode( $atts, $content = null ) {
	include_once(GG_DIR . '/classes/gg_overlay_manager.php');
	
	extract( shortcode_atts( array(
		'cid' 		=> '',
		'random' 	=> 0,
		
        'filter' 	=> 0,
        'def_filter'=> 0,
        'hide_all_filter'=>0,
        
		'pag_sys'	=> '',
		'per_page'	=> 0,
        
	), $atts ) );

	if($cid == '') {
        return '';
    }
	
	// init
	$collection = '';
	
	$thumb_q = (int)get_option('gg_thumb_q', 90);
	$timestamp = current_time('timestamp');
	$unique_id = uniqid();
	
	$basewidth = get_option('gg_masonry_basewidth', 960);
	$thumb_w = (int)get_option('gg_coll_thumb_max_w', 300);
	
	// find out thumb sizes - calculate height if is percentage based
	$thumb_h_val = (int)get_option('gg_coll_thumb_h', 140);
	$thumb_h_type = get_option('gg_coll_thumb_h_type', 'px');
    
	$thumb_h = ($thumb_h_type == 'px') ? $thumb_h_val : ($thumb_w * ($thumb_h_val / 100));
	
	// collection elements
	$coll_data = get_term($cid, 'gg_collections');
    if(!$coll_data || is_wp_error($coll_data)) {
        return '';    
    }
    
	$coll_composition = unserialize($coll_data->description);
	
	$coll_galleries = $coll_composition['galleries'];
	$coll_cats = $coll_composition['categories'];
	
	
	// fetch galleries elements
	$galleries = array();
	if(is_array($coll_galleries)) {
		foreach($coll_galleries as $gdata) {
			$orig_gid = absint($gdata['id']);
            $gid = absint(gg_gall_static::wpml_get_translated_id($orig_gid));
			
			if(isset($gdata['cust_img']) && !empty($gdata['cust_img'])) {
				$img_data = array(
					'src' => gg_static::img_src_on_type($gdata['cust_img'], 'wp'),
					'align' => 'c'
				);	
			}
			else {
				$img_data = gg_coll_static::get_gall_first_img($gid, 'full');
			}
			
			if($img_data) {
				if($gdata['wmark'] && filter_var(get_option('gg_watermark_img'), FILTER_VALIDATE_URL)) {
					$new_paths = gg_static::watermark_image($img_data['src']);	
					$img_data['src'] = $new_paths['path'];
				}
				
				$galleries[] = array(
					'id'		=> $gid, 
					'thumb'		=> gg_static::thumb_src($img_data['src'], ($thumb_w + 2), $thumb_h, $thumb_q, $img_data['align']),
					'full_url'	=> $img_data['src'],
					'title'		=> get_the_title($gid), 
					
					'rand'		=> (int)$gdata['rand'],
					'filters'	=> (isset($gdata['filters'])) ? (int)$gdata['filters'] : 0,
					'search'	=> (isset($gdata['search'])) ? (int)$gdata['search'] : 0,
					'wmark'		=> (int)$gdata['wmark'],
					
					'link_subj' => (isset($gdata['link_subj'])) ? $gdata['link_subj'] : 'none',
					'link_val'	=> (isset($gdata['link_val'])) ? gg_coll_static::get_wpml_translated_string($cid, $orig_gid, 'custom link', $gdata['link_val']) : '',
					'descr'		=> (isset($gdata['descr'])) ? gg_coll_static::get_wpml_translated_string($cid, $orig_gid, 'description', $gdata['descr']) : ''
				);
			}
		}
	}
	
	// check for existing galleries
	if(count($galleries) == 0) {
		return '';
	}	
		
	// randomize images 
	if((int)$random == 1) {
		shuffle($galleries);
	}
	
	// image overlay code 
	$ol_man = new gg_overlay_manager('', false, 'coll');
	

	// pagination vars
	$paginate = false;
	if($pag_sys && (int)$per_page && count($galleries) > (int)$per_page) {
		
		$page = 1;
		$paginate = true;
		$tot_pages = ceil(count($galleries) / (int)$per_page);	
	}


	// build
	$collection .= '
	<div id="'.$unique_id.'" class="gg_gallery_wrap gg_collection_wrap cid_'.$cid.'" data-cid="'.$cid.'">';
      
	  // table structure start
	  $collection .= '
	  <div class="gg_coll_table">
        <div class="gg_coll_table_cell gg_coll_table_first_cell">';
	  
	  
		  // filter
		  if($filter) {
			  // deeplinked value?
			  $dl_selected = (isset($GLOBALS['gg_deeplinks'][ 'cid_'.$cid ]) && isset($GLOBALS['gg_deeplinks'][ 'cid_'.$cid ]['gcc'])) ? $GLOBALS['gg_deeplinks'][ 'cid_'.$cid ]['gcc'] : '';
              
              // selected by shortcode parameter?
              if(!$dl_selected && (int)$def_filter) {
                 $dl_selected = (int)$def_filter;
              }
              
			  $filter_code = gg_coll_static::coll_filter_code($coll_cats, 'html', $dl_selected, (int)$hide_all_filter);
			  
			  if($filter_code) {
				  $filter_type = (get_option('gg_use_old_filters')) ? 'gg_textual_filters' : 'gg_btn_filters';
				  $collection .= '<div id="ggf_'.$cid.'" class="gg_filter '.$filter_type.'">'.$filter_code.'</div>';
			  
				  // mobile dropdown 
				  if(get_option('mg_dd_mobile_filter')) {
					  $filter_code = gg_coll_static::coll_filter_code($coll_cats, 'dropdown', $dl_selected, (int)$hide_all_filter);
					  
					  if($filter_code) {
						  $collection .= '<div id="ggmf_'.$cid.'" class="gg_mobile_filter">'. $filter_code .'<i></i></div>';
					  }
				  }
			  }
		  }
		  
	  
		  // collection container 
		  $collection .= 
		  '<div id="ggco_'.$cid.'" class="gg_coll_outer_container '.$ol_man->txt_vis_class.' '.$ol_man->ol_wrap_class.'">
             <div class="gg_container gg_coll_container">'.gg_static::preloader();
		 
                  $ol_type = get_option('gg_overlay_type');

                  $included_galleries = array();

                  $gall_counter = 1;
                  $pag_counter = 1;

                  foreach($galleries as $gi => $gal) {
                      $included_galleries[] = $gal['id'];

                      $gall_cats = gg_coll_static::gallery_cats($gal['id'], $return = 'class_list');
                      $gall_cats_list = (is_array($gall_cats)) ? '' : $gall_cats;

                      // image link codes
                      if(isset($gal['link_subj']) && trim($gal['link_subj']) != 'none') {
                          if($gal['link_subj'] == 'page') {$thumb_link = get_permalink($gal['link_val']);}
                          else {$thumb_link = $gal['link_val'];}

                          $link_tag = 'data-gg-link="'.$thumb_link.'"';
                          $add_class = "gg_linked_img";
                      } else {
                          $link_tag = '';
                          $add_class = '';
                      }


                     // replace %IMG-NUM% placeholder
                     $gal['descr'] = str_replace('%IMG-NUM%', (int)get_post_meta($gal['id'], 'gg_img_count', true), $gal['descr']);
                     $gal['descr'] = str_replace(array('&apos;', '&quot;', '&lt;', '&gt;', '&amp;'), array('\'', '"', '<', '>', '&'), $gal['descr']); // allow HTML execution

                      // title overlay position switch
                      if(get_option('gg_coll_title_under')) {
                        $descr = (!empty($gal['descr'])) ? '<div class="gg_img_descr_under">'. $gal['descr'] .'</div>' : '';
                        $outer_ol = '<div class="gg_main_overlay_under"><div class="gg_img_title_under">'. $gal['title'] .'</div>'. $descr .'</div>';  

                        $inner_ol = $ol_man->get_img_ol('', '', '', $gal['thumb']);
                      } else {
                          $inner_ol = $ol_man->get_img_ol($gal['title'], $gal['descr'], '', $gal['thumb']);
                          $outer_ol = ''; 
                      }

                      // SEO noscript part for full-res image
                      $noscript = '<noscript><img src="'.$gal['full_url'].'" alt="'. esc_attr($gal['title']) .'" /></noscript>';

                      // pag vis class
                      $pag_vis = ($pag_counter === 1) ? '' : 'gg_coll_pag_hidden';

                      // data array to recall gallery through ajax
                      $gall_data = base64_encode( json_encode(array(
                        'id' 		=> $gal['id'],
                        'rand' 		=> $gal['rand'],
                        'filters' 	=> $gal['filters'],
                        'search' 	=> $gal['search'],
                        'wmark'		=> $gal['wmark']
                      )));

                      $collection .= '
                      <div class="gg_coll_img_wrap '.$pag_vis.' '.$gall_cats_list.'">
                          <div class="gg_img gg_coll_img '.$add_class.'" data-coll-gid="'.$gal['id'].'" data-gall-data="'.$gall_data.'" style="padding-bottom: '.$thumb_h_val.$thumb_h_type.'" '.$link_tag.'>
                              <div class="gg_main_img_wrap" tabindex="0">
                                  <div class="gg_img_wrap_inner">
                                      <img src="" data-gg-lazy-src="'.$gal['thumb'].'" alt="'. esc_attr($gal['title']) .'" class="gg_photo gg_main_thumb" />
                                      '.$noscript.'
                                  </div>
                              </div>
                              <div class="gg_overlays">'.$inner_ol.'</div>
                          </div>
                          '.$outer_ol.'
                      </div>';

                      if($paginate) {
                          $gall_counter++; 
                          if($gall_counter > (int)$per_page) {
                            $gall_counter = 1;
                            $pag_counter ++;	  
                          }
                      }
                  }

              // container closing
              $collection .= 
              '</div>';
			  
			  
			  /////////////////////////
			  // pagination
    
			  if($paginate && (strpos($pag_sys, 'inf_scroll') === false || (strpos($pag_sys, 'inf_scroll') !== false && $page < count($galleries))) ) {	 	
				  $pag_wrap_vis = (isset($dl_selected) && !empty($dl_selected)) ? 'style="display: none;"' : '';
				 
				  $collection .= '
				  <div class="gg_paginate gg_coll_pag_wrap gg_pag_'. esc_attr(get_option('gg_pag_style', 'light')) .'" data-pag="'. absint($page) .'" data-per-pag="'. absint($per_page) .'" data-totpag="'. absint($tot_pages).'" '. $pag_wrap_vis .'>';
				  
				  // use global pagination system?
				  if($pag_sys == 'auto') { 
					  $pag_sys = get_option('gg_pag_system', 'standard');
				  }
				  
				  // classic pagination
				  if($pag_sys == 'standard') {
					  $pag_layout = get_option('gg_pag_layout', 'standard'); 
					  $pl_class = '';
					  
					  if($pag_layout == 'only_num') {$pl_class .= 'gg_pag_onlynum';}
					  if($pag_layout == 'only_arr_mb' || $pag_layout == 'only_arr') {
						  $pl_class .= 'gg_only_arr';
						  $pl_class .= ($pag_layout == 'only_arr_mb') ? ' gg_monoblock' : ' gg_detach_arr';
					  }
					  
					  // mid nav - layout code
					  if($pag_layout == 'standard') {
						  $mid_code = '<div class="gg_nav_mid"><div>'. esc_html__('page', 'gg_ml') .' <span>'. (int)$page .'</span> '. esc_html__('of', 'gg_ml') .' '.$tot_pages.'</div></div>';	
					  }
					  elseif($pag_layout == 'only_num') {
						  $mid_code = '<div class="gg_nav_mid"><div><span>'. (int)$page .'</span> <font>/</font> '.$tot_pages.'</div></div>';	
					  }
					  else {
						  $mid_code = '<div class="gg_nav_mid gg_displaynone"><div><span>'. (int)$page .'</span> <font>-</font> '.$tot_pages.'</div></div>';
					  }
					  
					  $prev_disabled  = ($page == 1) ? 'gg_pag_disabled' : '';
					  $next_disabled  = ($page >= $tot_pages) ? 'gg_pag_disabled' : '';
					  
					  $collection .= '
					  <div class="gg_standard_pag '.$pl_class.'">
						  <div class="gg_nav_left gg_prev_page '. $prev_disabled .'"><i></i></div>
						  '.$mid_code.'
						  <div class="gg_nav_right gg_next_page '. $next_disabled .'"><i></i></div>
					  </div>';		
				  }
				  
				  // infinite scroll
				  else if(strpos($pag_sys, 'inf_scroll') !== false) {
					  $auto_is_class = ($pag_sys == 'inf_scroll') ? '' : 'gg_auto_inf_scroll';
					  
					  $collection .= '
					  <div class="gg_infinite_scroll '. $auto_is_class .'">
						  <div class="gg_nav_left"></div>
						  <div class="gg_nav_mid"><span>'. esc_html__('show more', 'gg_ml') .'</span></div>
						  <div class="gg_nav_right"></div>
					  </div>';
				  }
				  
				  // numbered buttons
				  else if($pag_sys == 'num_btns') {
					  $collection .= '<div class="gg_num_btns_wrap">';
						  for($a=1; $a<=$tot_pages; $a++) {
							  $disabled = ($a == $page) ? 'gg_pag_disabled' : '';
							  $collection .= '<div class="gg_pagenum '.$disabled.'" title="'. esc_attr__('go to page', 'gg_ml') .' '.$a.'" data-pag="'.$a.'">'.$a.'</div>';
						  }
					  $collection .= '</div>';
				  }
				  
				  // dots
				  else {
					  $collection .= '<div class="gg_dots_pag_wrap">';
						  for($a=1; $a<=$tot_pages; $a++) {
							  $disabled = ($a == $page) ? 'gg_pag_disabled' : '';
							  $collection .= '<div class="gg_pag_dot '.$disabled.'" title="'. esc_attr__('go to page', 'gg_ml') .' '.$a.'" data-pag="'.$a.'"></div>';
						  }
					  $collection .= '</div>';
				  }
				  
				  $collection .= '</div>';
			  }	
		  
		  
		  // outer-container closing
		  $collection .=
		  '</div>';
		  
	// end collection cell and start gallery one
	$collection .= 
        '</div>
        <div class="gg_coll_table_cell gg_coll_gallery_container">';  
		
                // "back to" elements
                $back_to_str = get_option('gg_coll_back_to');
                if(empty($back_to_str)) {
                    $back_to_str = '<i class="fas fa-caret-left"></i> '. esc_html__('Back to collection', 'gg_ml');
                }
    
                $btn_style = (get_option('gg_use_old_filters')) ? '' : 'gg_coll_back_to_new_style';

            // gallery container
            $collection .= '
            <div class="gg_back_to_coll_wrap">
                <span id="gg_cgb_'.$unique_id.'" class="gg_back_to_coll '.$btn_style.'">'. $back_to_str .'</span>';
                
                if(get_option('gg_coll_show_gall_title')) {
                    $collection .= '<h4 class="gg_coll_gall_title"></h4>';
                }
    
            $collection .= '
            </div>';
	
	// close table and the main wrapper
	$collection .= '
        </div>
      </div>
    </div>'; // collection wrap closing
	
	
	
	// js - init collection ajax suppport
	$collection .= '
	<script type="text/javascript"> 
    (function() { 
        "use strict";  
    
        const intval = setInterval(() => {
            if(typeof(jQuery) == "undefined" || typeof(gg_galleries_init) == "undefined") {
                return true;
            }
            else {
                clearTimeout(intval);
            
                const $ = jQuery;
                gg_galleries_init("'.$unique_id.'");';

                // deeplinked chosen gallery?
                if(isset($GLOBALS['gg_deeplinks'][ 'cid_'.$cid ]) && isset($GLOBALS['gg_deeplinks'][ 'cid_'.$cid ]['gcg'])) {
                    $dl_gall = (int)$GLOBALS['gg_deeplinks'][ 'cid_'.$cid ]['gcg'];

                    if(in_array($dl_gall, $included_galleries)) {

                        $collection .= '
                        const gcg_intval = setInterval(() => {
                            if(!$(`#'. $unique_id .'`).find(`.gg_coll_img[data-coll-gid="'. $dl_gall .'"]`).parents(".gg_coll_img_wrap").hasClass("gg_shown")) {
                                return true;
                            }
                            else {
                                clearTimeout(gcg_intval);
                                $(`#'. $unique_id .'`).find(`.gg_coll_img[data-coll-gid="'. $dl_gall .'"]`).trigger("click");
                            }
                        }, 50);';
                    }
                }

                $collection .= '
            }
        }, 50);
    })(); 
	</script>';
	
		
	return str_replace(array("\r", "\n", "\t", "\v"), '', $collection);
}
add_shortcode('g-collection', 'gg_collection_shortcode');

