<?php

////////////////////////////////////////////////
////// SHOW CONNECTIONS HUB WIZARD /////////////
////////////////////////////////////////////////

function gg_connect_wizard_show() {
	include_once(GG_DIR . '/classes/gg_connections_hub.php');
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }
	
	if(!isset($_POST['gallery_id'])) {
        wp_die('missing data');
    }
	$gid = absint($_POST['gallery_id']);
	
	if(!isset($_POST['gg_type'])) {
        wp_die('missing data');
    }
	$type = sanitize_text_field(wp_unslash($_POST['gg_type']));
	
	
	$conn_hub = new gg_connection_hub($gid, $type);
	echo gg_static::wp_kses_ext($conn_hub->wizard());
	
	wp_die();
}
add_action('wp_ajax_gg_connect_wizard_show', 'gg_connect_wizard_show');






////////////////////////////////////////////////
////// RELOAD TYPE CONNECTIONS DROPDOWN ////////
////////////////////////////////////////////////

function gg_connect_dd_reload() {
	include_once(GG_DIR . '/classes/gg_connections_hub.php');
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }

	if(!isset($_POST['gallery_id'])) {
        wp_die('missing data');
    }
	$gid = absint($_POST['gallery_id']);
	
	if(!isset($_POST['gg_type'])) {
        wp_die('missing data');
    }
	$type = sanitize_text_field(wp_unslash($_POST['gg_type']));

	$conn_hub = new gg_connection_hub($gid, $type);
	echo gg_static::wp_kses_ext($conn_hub->src_connections_dd());
	
	wp_die();
}
add_action('wp_ajax_gg_connect_dd_reload', 'gg_connect_dd_reload');






////////////////////////////////////////////////
////// SAVE TYPE CONNECTION - CONNECTION HUB ///
////////////////////////////////////////////////

function gg_save_type_connect() {
	include_once(GG_DIR . '/classes/gg_connections_hub.php');
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }
	
	if(!isset($_POST['gallery_id'])) {
        wp_die('missing data');
    }
	$gid = absint($_POST['gallery_id']);
	
	if(!isset($_POST['gg_type'])) {
        wp_die('missing data');
    }
	$type = sanitize_text_field(wp_unslash($_POST['gg_type']));
	
	$conn_hub = new gg_connection_hub($gid, $type);
	echo gg_static::wp_kses_ext($conn_hub->setup_connection());
	
	wp_die();
}
add_action('wp_ajax_gg_save_type_connect', 'gg_save_type_connect');






////////////////////////////////////////////////
////// DELETE TYPE CONNECTION //////////////////
////////////////////////////////////////////////

function gg_remove_connection() {
	include_once(GG_DIR . '/classes/gg_connections_hub.php');
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }

	if(!isset($_POST['conn_id']) || !filter_var($_POST['conn_id'], FILTER_VALIDATE_INT)) {
        wp_die('missing data');
    }
	$conn_id = absint($_POST['conn_id']);
	
	
	// TO CHECK
	/*** OPERATIONS TO PERFORM BEFORE DELETION ***/
	$term = get_term($conn_id, 'gg_connect_hub');
	if(is_object($term)) {
		$data = unserialize(base64_decode($term->description));
		
		// google drive - remove from tokens database
		if(isset($data['gdrive_user'])) {
			$stored = get_option('gg_gdrive_base_tokens_db', array());
			
			if(isset($stored[ $data['gdrive_user'] ])) {
				unset($stored[ $data['gdrive_user'] ]);
				update_option('gg_gdrive_base_tokens_db', $stored);	
			}
		}
		
		// OneDrive - remove from tokens database
		if(isset($data['onedrive_user'])) {
			$stored = get_option('gg_onedrive_base_tokens_db', array());
			
			if(isset($stored[ $data['onedrive_user'] ])) {
				unset($stored[ $data['onedrive_user'] ]);
				update_option('gg_onedrive_base_tokens_db', $stored);	
			}
		}
	}

	$response = wp_delete_term($conn_id, 'gg_connect_hub');
	echo (is_wp_error($response)) ? esc_html($response->get_error_message()) : 'success';
	
	wp_die();
}
add_action('wp_ajax_gg_remove_connection', 'gg_remove_connection');






////////////////////////////////////////////////
////// CPT TAXONOMY - CHANGE TAXONOMY //////////
////////////////////////////////////////////////

function gg_cpt_tax_change() {
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }
	
	if(!isset($_POST['cpt_tax'])) {
        wp_die('missing data');
    }
	$cpt_tax = sanitize_text_field(wp_unslash($_POST['cpt_tax']));
	
	echo gg_static::wp_kses_ext(gg_gall_static::get_taxonomy_terms($cpt_tax));
	wp_die();
}
add_action('wp_ajax_gg_cpt_tax_change', 'gg_cpt_tax_change');






//////////////////////////////////////////////////////////////////////////////////////////






////////////////////////////////////////////////
////// GALLERY SETTINGS LOAD ///////////////////
////////////////////////////////////////////////

function gg_load_gb_settings() {
	include_once(GG_DIR . '/classes/gg_builder_sources_hub.php');
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }

	if(!isset($_POST['gallery_id'])) {wp_die('gallery id missing');}
	$gid = absint($_POST['gallery_id']);
	
	if(!isset($_POST['gg_type'])) {wp_die('source type missing');}
	$type = sanitize_text_field(wp_unslash($_POST['gg_type']));
	
	if(!isset($_POST['gg_username'])) {wp_die('gg_username missing');}
	$username = sanitize_text_field(wp_unslash($_POST['gg_username']));
	
	if(!isset($_POST['gg_connect_id'])) {wp_die('connection ID missing');}
	$connect_id = sanitize_text_field(wp_unslash($_POST['gg_connect_id']));
	
	// specific options
	$hub = new gg_builder_hub($gid, $type);
    
	echo gg_static::wp_kses_ext($hub->spec_opt(array('username' => $username, 'connect_id' => $connect_id)));
	wp_die();
}
add_action('wp_ajax_gg_load_gb_settings', 'gg_load_gb_settings');





///////////////////////////////////////
////// MEDIA IMAGE PICKER /////////////
///////////////////////////////////////

function gg_img_picker() {
    include_once(GG_DIR . '/classes/gg_img_fetcher.php');
	$tt_path = GG_TT_URL; 
	
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }
	
	// get vars
	if(!isset($_POST['gallery_id'])) {
        wp_die('missing data');
    }
	$gid = absint($_POST['gallery_id']);
	
	if(!isset($_POST['gg_type'])) {
        wp_die('missing data');
    }
	$type = sanitize_text_field(wp_unslash($_POST['gg_type']));
	
	$page = (!isset($_POST['page'])) ? 1 : absint($_POST['page']);
	$per_page = (!isset($_POST['per_page'])) ? 26 : absint($_POST['per_page']);

	if(!filter_var($per_page, FILTER_VALIDATE_INT) || !$per_page) {
		$per_page = 26;
	}
	elseif($per_page < 1) {
        $per_page = 1;
    }
	elseif($per_page > 200) {
        $per_page = 200;
    }

	$search = (!isset($_POST['gg_search'])) ? '' : sanitize_text_field(wp_unslash($_POST['gg_search']));
	$extra = (!isset($_POST['gg_extra'])) ? array() : sanitize_text_field(wp_unslash($_POST['gg_extra']));
	
	// images fetcher 
	$fetcher = new gg_img_fetcher($gid, $type, $page, $per_page, $search, $extra);
	$img_data = $fetcher->get;
	
	
    // errors report
    if(!empty($fetcher->errors)) {
        wp_die('<p>'. implode('</p><p>', $fetcher->errors) .'</p>');    
    }
    
    
	// print code
	echo '<ul>';
	
	if(!$img_data['tot']) {
		wp_die('<p>'. esc_html__('No images found', 'gg_ml') .' .. </p>');
	}
	else {
		foreach($img_data['img'] as $true_img_id => $img) {
			if(in_array($type, array('wp', 'wp_cat', 'cpt_tax', 'rml'))) {
				$img_src = $img['id'];
			} 
			elseif($type == 'gg_album' || $type == 'ngg') {
				$img_src = $img['path'];
			}
			else {
				$img_src = $img['url'];
			}
            
			$img_full_src = gg_static::img_src_on_type($img_src, $type);
			$img_full_url = gg_static::img_url_on_type($img_src, $type);
            $data_id_attr = ($type == 'g_drive') ? md5(gg_gall_static::gdrive_img_url_trick($img_src)) : md5($img_full_url);
            
            $thumb_url = false;
			if(in_array($type, array('wp', 'wp_cat', 'cpt_tax', 'rml'))) { // use WP thumbs
				$thumb_data = wp_get_attachment_image_src($img['id'], 'thumbnail');
				
                if(is_array($thumb_data) && $thumb_data[1] == 150) {
                    $thumb_url = $thumb_data[0];
                }
			} 
			if(!$thumb_url) {
				$thumb_url = (!get_option('gg_use_admin_thumbs')) ? $img_full_url : gg_static::inline_thumb_src($img_full_src, $width = 90, $height = 90, $quality = 90);
			}
			
            
			// add link to post if WP taxonomy
			$link = (in_array($type, array('wp_cat', 'cpt_tax')) && isset($img['link']) && !empty($img['link']) && get_option('gg_wp_term_autolink')) ? $img['link'] : '';
            
            // add tags if key exists
            $tags = (isset($img['tags'])) ? $img['tags'] : '';
            
			echo '
			<li class="gg_sel_status gg_img_not_sel">
				<figure style="background-image: url(\''. esc_attr(gg_gall_static::gdrive_img_url_trick($thumb_url)) .'\');" class="gg_gb_ip_img"
                    data-id="'. esc_attr($data_id_attr) .'"
				    data-img_src="'. esc_attr(gg_gall_static::gdrive_img_url_trick($img_src)) .'" 
                    data-img_full_src="'. esc_attr(gg_gall_static::gdrive_img_url_trick($img_full_src)) .'" 
                    data-fullurl="'. esc_attr($img_full_url) .'"
				    title="'.esc_attr(wp_strip_all_tags($img['title'])) .'" 
                    alt="'. esc_attr(wp_strip_all_tags($img['descr'], '<br>')) .'" 
                    data-author="'. esc_attr($img['author']) .'" 
                    data-link="'. esc_attr($link) .'"
                    data-tags="'. esc_attr($tags) .'"
				></figure>
				
			  <div class="gg_zoom_img"></div>
			</li>';	
		}
	}
	
	echo '
	</ul>
    
	<table class="gg_gall_img_picker_nav">
		<tr>
			<td>';			
			if($page > 1)  {
				echo '<input type="button" class="gg_img_pick_back button-secondary" id="slp_'. absint($page - 1) .'" name="mgslp_p" value="&laquo; ' . esc_attr__('Previous images', 'gg_ml') . '" />';
			}
			
		echo '</td><td>';
		
			if($img_data['tot'] > 0 && $img_data['tot_pag'] > 1) {
				echo '<em>page '. absint($img_data['pag']) .' of '. absint($img_data['tot_pag']) .'</em> - <input type="text" size="2" name="mgslp_num" id="gg_img_pick_pp" value="'. absint($per_page) .'" autocomplete="off" /> <em>'. esc_html__('images per page', 'gg_ml') .'</em>';	
			}
			else {
                echo '<input type="text" size="2" name="mgslp_num" id="gg_img_pick_pp" value="'. absint($per_page) .'" autocomplete="off" /> <em>'. esc_html__('images per page', 'gg_ml') .'</em>';
            }
			
		echo '</td><td>';
			if($img_data['more'] != false)  {
				echo '<input type="button" class="gg_img_pick_next button-secondary" id="slp_'. absint($page + 1) .'" name="mgslp_n" value="'. esc_attr__('Next images', 'gg_ml') .' &raquo;" />';
			}
		echo '</td>
		</tr>
	</table>';
	
	if($img_data['tot'] > 0) {
		echo'
		<script type="text/javascript">
        (function($) { 
            "use strict";  
            
		    $("#gg_total_img_num").text("('. absint($img_data['tot']) .')");
        })(jQuery);        
		</script>';
	}
	wp_die();
}
add_action('wp_ajax_gg_img_picker', 'gg_img_picker');






////////////////////////////////////////////////
////// GALLERY AUTO POPULATION /////////////////
////////////////////////////////////////////////

function gg_make_autopop() {
	include_once(GG_DIR . '/classes/gg_img_fetcher.php');
	$tt_path = GG_TT_URL; 
	
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }
	
	if(!isset($_POST['gallery_id'])) {wp_die('missing data');}
	$gid = absint($_POST['gallery_id']);
	
	if(!isset($_POST['gg_type'])) {wp_die('missing data');}
	$type = sanitize_text_field(wp_unslash($_POST['gg_type']));
	
	if(!isset($_POST['gg_max_img']) || !absint($_POST['gg_max_img']) ) {wp_die('missing data');}
	$o_max_img = absint($_POST['gg_max_img']);
	$max_img = $o_max_img;
	
	if(!isset($_POST['gg_random_img'])) {wp_die('missing data');}
	$random = sanitize_text_field(wp_unslash($_POST['gg_random_img']));

	$erase_past = (!isset($_POST['gg_erase_past'])) ? false : sanitize_text_field(wp_unslash($_POST['gg_erase_past']));
	$extra 		= (!isset($_POST['gg_extra'])) ? array() : sanitize_text_field(wp_unslash($_POST['gg_extra']));
	
	
	// unified function - use update autopop cache
	$attr = array(
		'type'		=> $type,
		'max_images'=> $max_img,
		'random'	=> $random,
		'extra'		=> $extra,
		'erase_past'=> $erase_past
	);
	$to_save = gg_gall_static::autopop_update_cache($gid, $attr);
	
	// display
	if(!count($to_save)) {
        wp_die('<em>' . esc_html__('No images found', 'gg_ml') .' .. </em>');
    }
	echo '<ul id="gg_fb_builder" class="gg_autopop_gallery">';
	
	// display
	foreach($to_save as $img) {
		$img_full_src = gg_static::img_src_on_type($img['img_src'], $type);
        
		$thumb_url = (!get_option('gg_use_admin_thumbs')) ? 
            gg_static::img_url_on_type($img['url'], $type) : 
            gg_static::inline_thumb_src($img_full_src, $width = 400, $height = 220, 85, 'c', 3);	
		
		echo '
        <li>
			<div class="gg_builder_img_wrap">
				<figure style="background-image: url(\''. esc_attr(gg_gall_static::gdrive_img_url_trick($thumb_url)) .'\');" class="gg_builder_img" data-fullurl="'. esc_attr($img_full_src) .'" title="'. esc_attr__("click to enlarge", 'gg_ml') .'"></figure>
			</div>	
			<div>
				<table>
				  <tr>
					<td class="gg_img_data_icon"><span class="dashicons dashicons-admin-users" title="'. esc_attr__('photo author', 'gg_ml') .'"></span></td>
					<td>'. esc_html($img['author']) .'</td>
				  </tr>
				  <tr>
					<td class="gg_img_data_icon"><span class="dashicons dashicons-editor-textcolor" title="'. esc_attr__('photo title', 'gg_ml') .'"></span></td>
					<td>'. wp_kses_post($img['title']) .'</td>
				  </tr>
				  <tr>
					<td class="gg_img_data_icon"><span class="dashicons dashicons-editor-alignleft" title="'. esc_attr__('photo description', 'gg_ml') .'"></span></td>
					<td>'. wp_kses_post($img['descr']) .'</td>
				  </tr>';
        
                  if(in_array($type, array('gg_album', 'ngg')) && isset($img['tags'])) {
					echo '
					<tr>
					  <td class="gg_img_data_icon">
                        <span class="dashicons dashicons-tag" title="'. esc_attr__('photo tags - comma split', 'gg_ml') .'"></span>
                      </td>
					  <td>'. esc_html($img['tags']) .'</td>
					</tr>';
				  }
				  
				  if(($type == 'wp_cat' || $type == 'cpt_tax') && isset($img['link']) && !empty($img['link'])) {
					echo '
					<tr>
					  <td class="gg_img_data_icon"><span class="dashicons dashicons-admin-links" title="photo link"></span></td>
					  <td><a href="'. esc_attr($img['link']) .'" target="_blank">'. esc_html($img['link']) .'</a></td>
					</tr>';
				  }

				echo '
				</table>
			</div>
		</li>';		
	}
	
	echo '</ul>';
	wp_die();
}
add_action('wp_ajax_gg_make_autopop', 'gg_make_autopop');






////////////////////////////////////////////////
////// MANUAL GALLERY - SAVE IMAGES ////////////
////////////////////////////////////////////////

function gg_manual_gb_save() {
	if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'gg_gall_builder')) {
        wp_die('cheating?');
    }
	include_once(GG_DIR.'/classes/simple_form_validator.php');

	// decode the gdata JSON string containing gallery data
	if(!isset($_POST['gdata'])) {
		wp_die('gallery data missing');	
	}
	
	$gdata = json_decode(wp_unslash($_POST['gdata']), true);
    $gdata = map_deep($gdata, 'sanitize_text_field');
    
	$keys = array('gg_item_img_src', 'gg_item_thumb', 'gg_item_author', 'gg_item_title', 'gg_item_descr', 'gg_item_tags', 'gg_link_opt', 'gg_item_link');
	
	foreach($keys as $key) {
		if(!isset($gdata[$key]) || !is_array($gdata[$key])) {
			wp_die('gallery data missing ('. $key .')');	
		}
		
		$_POST[$key] = $gdata[$key];
	}
	

	$validator = new simple_fv(GG_ML);
	
	$indexes = array();
	$indexes[] = array('index'=>'gid', 'label'=>'Gallery ID', 'required'=>true, 'type'=>'int');
	
	$indexes[] = array('index'=>'gg_item_img_src', 'label'=>'Images Image source');
	$indexes[] = array('index'=>'gg_item_thumb', 'label'=>'Images Thumb Center');
	$indexes[] = array('index'=>'gg_item_author', 'label'=>'Images Author');
	$indexes[] = array('index'=>'gg_item_title', 'label'=>'Images Title');
	$indexes[] = array('index'=>'gg_item_descr', 'label'=>'Images Description');
	$indexes[] = array('index'=>'gg_item_tags', 'label'=>'Images Tags');
	$indexes[] = array('index'=>'gg_link_opt', 'label'=>'Images Link option');
	$indexes[] = array('index'=>'gg_item_link', 'label'=>'Images Link source');
		
	$validator->formHandle($indexes);

	$fdata = $validator->form_val;
	$error = $validator->getErrors();
	if($error) {
		wp_die($error);	
	}
		
		
	// clean data
	foreach($fdata as $key=>$val) {
		if(!is_array($val)) {
			$fdata[$key] = stripslashes($val);
		}
		else {
			$fdata[$key] = array();
			foreach($val as $arr_val) {
                $fdata[$key][] = stripslashes($arr_val);
            }
		}
	}

	// gallery data array builder
	if(!is_array($fdata['gg_item_img_src']) || empty($fdata['gg_item_img_src'])) {
		$gallery = false;
	}
	else {
		$gallery = array();

		for($a=0; $a < count($fdata['gg_item_img_src']); $a++) {
			if(!isset($fdata['gg_item_link'][$a]) || !$fdata['gg_item_link'][$a]) {
				$fdata['gg_link_opt'][$a] = 'none';
			}

			$gallery[] = array(
				'img_src'	=> $fdata['gg_item_img_src'][$a],
				'thumb' 	=> $fdata['gg_item_thumb'][$a],
				'author'	=> trim($fdata['gg_item_author'][$a]),
				'title'		=> trim($fdata['gg_item_title'][$a]),
				'descr'		=> preg_replace('~[\r\n]+~', '<br/>', trim($fdata['gg_item_descr'][$a])),
				'tags'		=> trim($fdata['gg_item_tags'][$a]),
				'link_opt'	=> $fdata['gg_link_opt'][$a],
				'link'		=> $fdata['gg_item_link'][$a]
			);
		}
	}
	
	
	// save
	gg_gall_static::save_data($fdata['gid'], $gallery);
	wp_die('success');
}
add_action('wp_ajax_gg_manual_gb_save', 'gg_manual_gb_save');
