<?php

/////////////////////////////////////////////////////
// [g-gallery]
function gg_gallery_shortcode( $atts, $content = null ) {
	include_once(GG_DIR . '/classes/gg_overlay_manager.php');
	
	extract( shortcode_atts( array(
		'gid' 			=> '',
		'random' 		=> 0,
		'watermark' 	=> 0,
		'filters'		=> 0,
		'search'		=> 0,
		'pagination' 	=> '',
		'wp_gall_hash' 	=> '', // hidden parameter for WP galleries - images list hash
		
		// parameters reserved to ajax gallery management
		'filter' 	 => '',
		'search_str' => '',
		'page'		 => 0,
	), $atts ) );

	if($gid == '') {return '';}
    get_post_meta($gid); // use only one query
	
	// check deeplinked values
	$dl_vals = array(
		'ggt' => '',
		'ggs' => '',
		'ggp' => 0,
	);	
	if(!isset($_POST['gg_pag_vars']) && isset($GLOBALS['gg_deeplinks'][ 'gid_'.$gid ])) {
		foreach($dl_vals as $dl_key => $def) {
			
			if(isset($GLOBALS['gg_deeplinks'][ 'gid_'.$gid ][ $dl_key ])) {
				$dl_vals[$dl_key] = $GLOBALS['gg_deeplinks'][ 'gid_'.$gid ][ $dl_key ];	
				
				if($dl_key == 'ggt') {
					$dl_vals[$dl_key] = urldecode($dl_vals[$dl_key]);	
				}
			}
		}
	}

	// maybe override vals with deeplink
	if(!$search_str && !empty($dl_vals['ggs'])) {
		$search_str	= $dl_vals['ggs'];
	}
	if(!$page && (int)$dl_vals['ggp'] > 1) {
		$page = (int)$dl_vals['ggp'];	
	}



	// init
	$gallery 	= '';
	$ajax_mode	= (isset($_POST['gg_pag_vars']) && ($filter === '' || !empty($search_str) || !empty($page))) ? true : false;
	$type 		= (!empty($wp_gall_hash)) ? 'wp_gall' : get_post_meta($gid, 'gg_type', true);
	
	$thumb_q 	= get_option('gg_thumb_q', 90);
	$timestamp 	= current_time('timestamp');
	$unique_id 	= uniqid();
	
	$raw_layout = get_post_meta($gid, 'gg_layout', true);
	$layout 	= gg_gall_static::check_default_val($gid, 'gg_layout');
	
	// layout options
	if($layout == 'standard') {
		$thumb_w = (int)gg_gall_static::check_default_val($gid, 'gg_thumb_w', 150, $raw_layout);
		$thumb_h = (int)gg_gall_static::check_default_val($gid, 'gg_thumb_h', 150, $raw_layout);
	}
	elseif($layout == 'columnized') {
		$thumb_w = (int)gg_gall_static::check_default_val($gid, 'gg_colnzd_thumb_max_w', 260, $raw_layout);

		$thumb_h_val  = (int)gg_gall_static::check_default_val($gid, 'gg_colnzd_thumb_h', 120, $raw_layout);
		$thumb_h_type = gg_gall_static::check_default_val($gid, 'gg_colnzd_thumb_h_type', 'px', $raw_layout);
		$thumb_h = ($thumb_h_type == 'px') ? $thumb_h_val : ($thumb_w * ($thumb_h_val / 100));
	}
	elseif($layout == 'masonry') { 
		$cols = (int)gg_gall_static::check_default_val($gid, 'gg_masonry_cols', 4, $raw_layout); 
		$default_w = (int)get_option('gg_masonry_basewidth', 960);
		
		$min_w = get_option('gg_masonry_min_width', 150);
		$col_w = floor( $default_w / $cols );
		if($col_w < $min_w) {$col_w = $min_w;}
	}
	else { 
		$row_h = gg_gall_static::check_default_val($gid, 'gg_photostring_h', 180, $raw_layout); 
	}
	
	
	
	// is ajax call?
	if($ajax_mode) {
		if(!isset($_POST['gg_pag_vars']) || !is_array($_POST['gg_pag_vars'])) {
			die('missing gallery infos');
		}
		
        $pag_vars       = map_deep($_POST['gg_pag_vars'], 'sanitize_text_field');
		$pagination		= $pag_vars['pagination_sys'];
		$watermark 		= $pag_vars['watermark'];
		$wp_gall_hash	= $pag_vars['wp_gall_hash'];	
		$per_page 		= (!(int)$pag_vars['per_page']) ? 15 : (int)$pag_vars['per_page']; 
		$randomized_order = (!empty($pag_vars['random_trail'])) ? json_decode($pag_vars['random_trail']) : false;
		
		if($randomized_order) {
			$random = 1;	
		}
	}
	
	else {
		$raw_paginate 		= get_post_meta($gid, 'gg_paginate', true);
		$per_page 			= (int)gg_gall_static::check_default_val($gid, 'gg_per_page', 15, $raw_paginate);
		$randomized_order 	= false;	
	}
	
	// paginate?
	$paginate 			= gg_gall_static::check_default_val($gid, 'gg_paginate');
	
	
	//// prepare images
	// get them
	$images = gg_gall_static::frontend_img_prepare($gid, $type, $wp_gall_hash);

	if(!is_array($images) || !count($images)) {
		return '';
	}
    $full_gall_img_count = count($images);


	// create randomized order if needed	
	if(!$ajax_mode) {
		$randomized_order = ((int)$random) ? gg_static::random_img_indexes(count($images)) : false;
	}

	// randomized order? replace indexes
	if($randomized_order) {
		$resorted_images = array();
		
		foreach($randomized_order as $old_id) {
			if(isset($images[$old_id])) {
				$resorted_images[] = $images[$old_id];
			}
		} 
		$images = $resorted_images;
	}

	// filters enabled? prepare them
	if(!$ajax_mode && !empty($filters)) {
		$tags = gg_gall_static::get_gallery_tags($images);	
		
		// deeplinked tag? point it to matched images
		if($dl_vals['ggt'] !== '' && is_array($tags) && isset($tags[ $dl_vals['ggt'] ])) {
			$dl_vals['ggt_bkp'] = $dl_vals['ggt']; // keeep the deeplinked tag name for gg_gall_static::gallery_tags_code()
			$dl_vals['ggt'] = implode(',', $tags[ $dl_vals['ggt'] ]);
            
			$filter = $dl_vals['ggt'];
		}
		else {
			$dl_vals['ggt_bkp'] = '';
			$dl_vals['ggt'] = ''; // reset if deeplinked tag not exist	
		}
	}
	
	
	// pre-gallery block (tags / search)
	if(!$ajax_mode && (!empty($tags) || !empty($search))) {
		
		// pre block classes
		$outer_classes = array();
		if(!empty($tags)) 	{$outer_classes[] = 'gg_gall_has_filter';}
		if(!empty($search)) {$outer_classes[] = 'gg_gall_has_search';}
		
		$gallery .= '
		<div class="gg_pre_gallery '. implode(' ', $outer_classes) .'" data-gid="'. $unique_id .'">';
	
			// gallery tags
			if(!empty($filters)) {
				$gallery .= gg_gall_static::gallery_tags_code($unique_id, $gid, $tags, $dl_vals['ggt_bkp']);
			}
			
			
			// search?
			if(!empty($search)) {
				$has_txt_class = ($dl_vals['ggs']) ? 'ggs_has_txt' : '';

				$gallery .= '
				<form class="gg_gall_search_form '. $has_txt_class .'">
					<input type="text" name="gg_gall_search" value="'. esc_attr($dl_vals['ggs']) .'" placeholder="'. esc_html__('search', 'gg_ml') .' .." autocomplete="off" />
					<i class="fa fa-search gg_gall_search_icon"></i>
					<i class="gg_clear_search">&times;</i>
				</form>';
			}
		
		$gallery .= '
		</div>';
	}
	


	// calculate images range
	if($page <= 1) {$page = 1;}
	$start = ($page - 1) * $per_page;  
	$selection = (!$paginate) ? 'all' : array( (($page -1) * $per_page), ($page * $per_page) );  


	// search/tags deeplink only if there's pagination
	if($paginate && count($images) > $per_page) {
		$paginated_gallery = true; // flag for deeplink application with local filters	
		
		// is filtering? (ajax or deeplink)
		if($filter !== '') {
			$filter_img_ids = explode(',', $filter);
			
			$filtered_imgs = array();
			foreach($filter_img_ids as $fii) {
				
				if($randomized_order) {
					$filtered_imgs[$fii] = $images[ (int)$fii ];
				} else {
					$filtered_imgs[] = $images[ (int)$fii ];	
				}
			}
            
			$images = $filtered_imgs;
		}
		
	
		// is searching? (ajax or deeplink)
		if($search_str) {
			$src_arr = explode(' ', strtolower($search_str));
			$filtered_imgs = array();
			
			foreach($images as $img_id => $img) {
				$img['tags'] = (!isset($img['tags'])) ? '' : strtolower(str_replace(',', '', $img['tags']));
                
                $src_attr = strtolower($img['author'] .' '. $img['title'] .' '. $img['descr'] .' '. $img['tags']);
				
				foreach($src_arr as $word) {
					if(strlen($word) < 2) {continue;}
					
					if(strpos($src_attr, $word) !== false) {
						
						if($randomized_order) {
							$filtered_imgs[ $img_id ] = $img; 
						} else {
							$filtered_imgs[] = $img; 
						}
	
						break;
					}
				}
			}
			
			if(!$dl_vals['ggs'] || count($filtered_imgs)) {
				$images = $filtered_imgs;	
			} else {
				$paginated_gallery = false; // fake value, but has to triger manually the filter	
			}
		}
	}
	else {
		$paginated_gallery = false; // flag for deeplink application with local filters	
	}
	

	// split images for pagination
	$gall_img_count = count($images);
	//$randomized_order = false; // v7 gallery already passes randomized order
	
	$images = gg_gall_static::frontend_img_split($gid, $images, $selection, false /*$randomized_order*/, $watermark);	// PASS ALSO WATERMARK FLAG!!!!
	if(!is_array($images) || !count($images)) {
        $images = array();
    }	

	// pagination limit
	if($paginate && $gall_img_count > $per_page) {
		$tot_pages = ceil($gall_img_count / $per_page );	
	} 
	
		
	// additional parameters
	switch($layout) {
		case 'columnized' :
			$add_param = 'data-col-maxw="'. esc_attr($thumb_w) .'"';
			break;
		
		case 'masonry' :
			$add_param = 'data-col-num="'. esc_attr($cols) .'"';
			
			if(get_post_meta($gid, 'gg_layout', true) == 'masonry' && (int)get_post_meta($gid, 'gg_masonry_min_width', true)) {
				$add_param .= ' data-minw="'. (int)get_post_meta($gid, 'gg_masonry_min_width', true) .'"';	
			}
			break;
			
		case 'string' :
			$add_param = 'data-row-h="'. esc_attr($row_h) .'"';
			
			if(get_post_meta($gid, 'gg_layout', true) == 'string' && (int)get_post_meta($gid, 'gg_photostring_min_width', true)) {
				$add_param .= ' data-minw="'. (int)get_post_meta($gid, 'gg_photostring_min_width', true) .'"';	
			}
			break;	
		
		default :
			$add_param = '';
			break;
	}
	
	
	// image overlay code 
	$ol_man = new gg_overlay_manager('', false, 'gall');
	
    
	// build
	$gallery .= '
	<div id="'. esc_attr($unique_id) .'" class="gg_gallery_wrap gg_true_gallery gg_'. esc_attr($layout) .'_gallery gid_'.$gid.' '. esc_attr($ol_man->ol_wrap_class) .' '. esc_attr($ol_man->txt_vis_class) .'" '.$add_param.' data-gid="'. esc_attr($gid) .'" data-nores-txt="'. esc_attr__('No images found', 'gg_ml') .'">
      '.gg_static::preloader().'
	  <div class="gg_container">';	
	   
	  
	  // ajax mode? reset code 
	  if($ajax_mode) {
		$gallery = '';  
	  }
	
	  
	  // images code
	  foreach($images as $img_index => $img) {
		  if(!isset($img['url'])) {
            continue;      
          }
          
		// image link codes
		if(isset($img['link']) && trim($img['link']) != '') {
			$thumb_link = ($img['link_opt'] == 'page') ? get_permalink($img['link']) : $img['link'];
			
			$open_tag = '<div data-gg-link="'. esc_attr($thumb_link) .'"';
			$add_class = "gg_linked_img";
			$close_tag = '</div>';
		} else {
			$open_tag = '<div';
			$add_class = "";
			$close_tag = '</div>';
		}
		
		
		// dunno why, but wp gall managed src must be managed
		if($wp_gall_hash) {
            $img['url'] = gg_static::img_id_to_url($img['url']);  
		}
		
		
		// SEO noscript part for full-res image
		$noscript = '<noscript><img src="'. esc_attr($img['url']) .'" alt="'. esc_attr($img['title']) .'" /></noscript>';
		
		// common attributes + classes
		$img['tags'] = (!isset($img['tags'])) ? '' : strtolower(str_replace(',', '', $img['tags']));
          
        $atts = 'class="gg_img '. $add_class .'" data-gg-url="'. esc_attr($img['url']) .'" data-gg-title="'. esc_attr($img['title']) .'" data-gg-author="'. esc_attr($img['author']) .'" data-gg-descr="'. esc_attr($img['descr']) .'" data-gg-tags="'. esc_attr($img['tags']) .'" data-img-id="'. (int)$img_index .'" data-gid="'. esc_attr($gid) .'"';
		
		
		
		/////////////////////////
		// standard layout
		if($layout == 'standard') {	 
			
			$thumb = gg_static::thumb_src($img['path'], $thumb_w, $thumb_h, $thumb_q, $img['thumb']);
			$gallery .= '
			'. $open_tag .' '. $atts .'>
			  <div class="gg_img_inner">';
				
				$gallery .= '
				<div class="gg_main_img_wrap">
					<img src="" data-gg-lazy-src="'. esc_attr($thumb) .'" alt="'. esc_attr($img['title']) .'" class="gg_photo gg_main_thumb" />
					'.$noscript.'
				</div>';	
				
				$gallery .= '
				<div class="gg_overlays">'. $ol_man->get_img_ol($img['title'], $img['descr'], $img['author'], $img['url']) .'</div>';	
				
			$gallery .= '</div>' . $close_tag;
		}
		
		
		/////////////////////////
		// columnized layout
		else if($layout == 'columnized') {
			
			$thumb = gg_static::thumb_src($img['path'], $thumb_w, $thumb_h, $thumb_q, $img['thumb']);	
			$gallery .= '
			'. $open_tag .' '. $atts .'>
			  <div class="gg_img_inner" style="padding-bottom: '.$thumb_h_val.$thumb_h_type.'">
				<div class="gg_main_img_wrap">
					<div class="gg_img_wrap_inner">
						<img src="" data-gg-lazy-src="'. esc_attr($thumb) .'" alt="'. esc_attr($img['title']) .'" class="gg_photo gg_main_thumb" />
						'.$noscript.'	
					</div>
				</div>
				<div class="gg_overlays">'. $ol_man->get_img_ol($img['title'], $img['descr'], $img['author'], $img['url']) .'</div>	
			</div>'.$close_tag;  
		}
		
		
		/////////////////////////
		// masonry layout
		else if($layout == 'masonry') {
			
			$thumb = gg_static::thumb_src($img['path'], ($col_w + 40), false, $thumb_q, $img['thumb']);	
			$gallery .= '
			'. $open_tag .' '. $atts .'>
			  <div class="gg_img_inner">
				<div class="gg_main_img_wrap">
					<div class="gg_img_wrap_inner">
						<img src="" data-gg-lazy-src="'. esc_attr($thumb) .'" alt="'. esc_attr($img['title']) .'" class="gg_photo gg_main_thumb" />
						'.$noscript.'	
					</div>
				</div>
				<div class="gg_overlays">'. $ol_man->get_img_ol($img['title'], $img['descr'], $img['author'], $img['url']) .'</div>	
			</div>'.$close_tag;  
		}
		
		  
		/////////////////////////
		// photostring layout
		else {

			$thumb = gg_static::thumb_src($img['path'], false, $row_h, $thumb_q, $img['thumb']);
			$gallery .= '
			'. $open_tag .' '. $atts .'>
			  <div class="gg_img_inner" style="height: '.$row_h.'px;">
			  	<div class="gg_main_img_wrap">
					<div class="gg_img_wrap_inner">
						<img src="" data-gg-lazy-src="'. esc_attr($thumb) .'" alt="'. esc_attr($img['title']) .'" class="gg_photo gg_main_thumb" />	
						'.$noscript.'
					</div>
				</div>
				<div class="gg_overlays">'. $ol_man->get_img_ol($img['title'], $img['descr'], $img['author'], $img['url']) .'</div>	
			</div>'.$close_tag;  
		}	
	}
	  
	// container height trick for photostring
	if($layout == 'string') {$gallery .= '<div class="gg_string_clear_both" style="clear: both;"></div>';}


	// container closing
	if(!$ajax_mode) {
		$gallery .= '</div>'; 
	}
	
	

	/////////////////////////
	// pagination
	$pag_system = $pagination;
	if(!$page) {
        $page = 1;
    }
	
	if($paginate && $gall_img_count > $per_page && (strpos($pag_system, 'inf_scroll') === false || (strpos($pag_system, 'inf_scroll') !== false && $page < $tot_pages)) ) {	 	
		$gallery .= '<div class="gg_paginate gg_pag_'. get_option('gg_pag_style', 'light') .'" gg-random="'. $random .'" data-gg-totpages="'. $tot_pages .'">';
		
		// use global pagination system?
		if(empty($pag_system)) { 
			$pag_system = get_option('gg_pag_system', 'standard');
		}
		
		// classic pagination
		if($pag_system == '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' : '';
			
			$gallery .= '
			<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_system, 'inf_scroll') !== false) {
			$auto_is_class = ($pag_system == 'inf_scroll') ? '' : 'gg_auto_inf_scroll';
			
			$gallery .= '
			<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_system == 'num_btns') {
			$gallery .= '<div class="gg_num_btns_wrap">';
				for($a=1; $a<=$tot_pages; $a++) {
					$disabled = ($a == $page) ? 'gg_pag_disabled' : '';
					$gallery .= '<div class="gg_pagenum '.$disabled.'" title="'. esc_attr__('go to page', 'gg_ml') .' '.$a.'" data-pag="'.$a.'">'.$a.'</div>';
				}
			$gallery .= '</div>';
		}
		
		// dots
		else {
			$gallery .= '<div class="gg_dots_pag_wrap">';
				for($a=1; $a<=$tot_pages; $a++) {
					$disabled = ($a == $page) ? 'gg_pag_disabled' : '';
					$gallery .= '<div class="gg_pag_dot '.$disabled.'" title="'. esc_attr__('go to page', 'gg_ml') .' '.$a.'" data-pag="'.$a.'"></div>';
				}
			$gallery .= '</div>';
		}
		
		$gallery .= '</div>';
	}
	
	
	// ajax mode? skip last code part
	if($ajax_mode) {
		return $gallery;	
	}
	
	
	$gallery .= '<div style="clear: both;"></div>
	</div>'; // gallery wrap closing
	

	// pagination JS vars (WP-gall imgages - watermark flag - random order trail)
	if($paginate && $full_gall_img_count > $per_page) {	
		$random = (!empty($random)) ? json_encode($randomized_order) : 'false';
		
		$gallery .= '
		<script type="text/javascript"> 
		(function() { 
            "use strict";  
            
            if(typeof(gg_pag_vars) == "undefined") {
                window.gg_pag_vars = {};
            }
            gg_pag_vars["'.$unique_id.'"] = {
                per_page		: '. $per_page .',
                pagination_sys	: "'. $pag_system .'",		
                watermark 		: '. (int)$watermark .',
                random_trail 	: "'. $random .'",
                wp_gall_hash	: "'. $wp_gall_hash .'"
            };
        })();
		</script>';
	}
	
	
	
	// js - init gallery
	$gallery .= '
	<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 values
                foreach($dl_vals as $dl_key => $dl_val) {
                    if(!empty($dl_val)) {
                        switch($dl_key) {
                            case 'ggt' : $gallery .= 'gg_gall_curr_filter["'. $unique_id .'"] =  ['. $dl_vals['ggt'] .'];'; 
                                break;	 

                            case 'ggs' : $gallery .= 'gg_gall_curr_search["'. $unique_id .'"] = "'. addslashes($dl_val) .'";'; 
                                break;	

                            case 'ggp' : $gallery .= 'gg_gallery_pag["'. $unique_id .'"] = '. (int)$dl_val .';'; 
                                break;		
                        }
                    }
                }

                // deeplinks for local filters
                if(!$paginated_gallery && $dl_vals['ggt'] !== '') {
                    $gallery .= '$(`.gg_pre_gallery[data-gid="'. $unique_id .'"] .gg_tag[data-images="'. $dl_vals['ggt'] .'"]`).trigger("gg-click");';		
                }
                if(!$paginated_gallery && $dl_vals['ggs']) {
                    $gallery .= '$(`.gg_pre_gallery[data-gid="'. $unique_id .'"] .gg_gall_search_form input`).trigger("keyup");';		
                }

            $gallery .= '
            }
        }, 50);
    })();
	</script>';


	return str_replace(array("\r", "\n", "\t", "\v"), '', $gallery);
}
add_shortcode('g-gallery', 'gg_gallery_shortcode');

