<?php
/* ------------------------------------------------------------------------*
 * This file contains the main theme options functionality.
 * ------------------------------------------------------------------------*/

/**
 * ADD THE ACTIONS
 */
if ( isset($_GET['page']) && $_GET['page'] == DEEP_OPTIONS_PAGE ){
	//options actions
	add_action('init', 'deep_init_options_functionality');  
	add_action('init', 'deep_set_options'); 
}

if ( isset($_GET['page']) && $_GET['page'] == DEEP_STYLE_OPTIONS_PAGE ){
	
	/* NEW FONTS 2025 */
	global $boldway_google_fonts_json_file_content;
	/**/
	
	//options actions
	add_action('init', 'deep_init_style_options_functionality');  
	add_action('init', 'deep_set_style_options'); 
}

/**
 * Inits the options functionality. Loads the files that contain the options arrays
 * to populate the global options array.
 */
function deep_init_style_options_functionality(){
	
	/* NEW FONTS 2025 */
	
	global $deep_style_options, $wp_filesystem, $boldway_google_fonts_json_file_content; /* JADG - we need the filesystem to read the json with the fonts */
	
	if (!function_exists('WP_Filesystem')) require_once ( ABSPATH . '/wp-admin/includes/file.php' );
	WP_Filesystem();
	
	$boldway_google_fonts_json_file = DEEP_OPTIONS_PATH . "fonts.json";
	$boldway_google_fonts_json_file_content = array();
	
	if ($wp_filesystem->exists( $boldway_google_fonts_json_file ) ) {
		$boldway_google_fonts_json_file_content = json_decode( $wp_filesystem->get_contents( $boldway_google_fonts_json_file ) );
	}
	
	/* add theme specific fonts - useful for custom fonts that ship with the theme. */
	array_unshift($boldway_google_fonts_json_file_content, json_decode(json_encode(array(
		"type" => "Theme Defaults",
		"items" => array(
			array(
				"family" => "Josefin Sans",
				"variants" => array( "100", "300", "400" ) 
			),
			array(
				"family" => "Mulish",
				"variants" => array( "200", "300", "400", "500", "600", "700", "800" ) 
			),
			array(
				"family" => "Hind",
				"variants" => array( "300", "400", "500", "600" ) 
			)
		)
	))));
	
	$boldway_adobetypekit_fonts = get_option( 'boldway_custom_typekit_option', false );
	if ($boldway_adobetypekit_fonts){
		$aux_array = array();
		foreach ($boldway_adobetypekit_fonts as $font){
			array_push( $aux_array, array(
				'family' => $font['family'],
				'variants' => $font['weights']
			) );
		}
		array_unshift($boldway_google_fonts_json_file_content, json_decode(json_encode(array(
			"type" => "Adobe TypeKit",
			"items" => $aux_array
		))));
	}
	
	
	$boldway_custom_uploaded_fonts = get_option( 'deep_custom_font_list', false );
	if ($boldway_custom_uploaded_fonts){
		$custom_uploaded_fonts_array = json_decode(stripslashes($boldway_custom_uploaded_fonts), true);
		if ($custom_uploaded_fonts_array && !empty($custom_uploaded_fonts_array)){
			$aux_array = array();			
			foreach ($custom_uploaded_fonts_array as $font){
				array_push( $aux_array, array(
					'family' => $font['name'],
					'variants' => array($font['var'])
				) );
			}
			array_unshift($boldway_google_fonts_json_file_content, json_decode(json_encode(array(
				"type" => "Custom Fonts",
				"items" => $aux_array
			))));
		}
	}
	/**/
	
	$deep_style_options=array();

	//get all the categories
	$categories=get_categories('hide_empty=0');
	$deep_categories=array();
	for($i=0; $i<sizeof($categories); $i++){
		$deep_categories[]=array('id'=>$categories[$i]->cat_ID, 'name'=>$categories[$i]->cat_name);
	}

	//load the files that contain the options
	$deep_style_options_files=array('style-general', 'style-website-loading', 'style-header-top-bar', 'style-logotype', 'style-menu', 'style-sliding-panel', 'style-search', 'style-pagetitle', 'style-footer', 'style-typography' ,'style-mobile' , 'style-import-export');
	foreach($deep_style_options_files as $file){
		require_once(DEEP_OPTIONS_PATH.$file.'.php');
	}
}


/**
 * Sets the Options save functionality.
 */
function deep_set_style_options(){
	global $deep_style_options;
	
	$nonsavable_types=array('open', 'close','subtitle','title','documentation');

	//insert the default values if the fields are empty
	foreach ($deep_style_options as $value) {

		if(isset($value['id'])){
			if(get_option($value['id'])=='' && isset($value['std']) && !in_array($value['type'], $nonsavable_types)){
				update_option( $value['id'], $value['std']);
			}
		}
	}
	
	//save the field's values if the Save action is present
	if ( $_GET['page'] == DEEP_STYLE_OPTIONS_PAGE ) {
	
		if (isset($_REQUEST['action'])){
			if ( 'save' == $_REQUEST['action'] ) {
				
				//verify the nonce
				if ( empty($_POST) || !wp_verify_nonce($_POST['deep-theme-style-options'],'deep-theme-update-style-options') ){
					print 'Sorry, your nonce did not verify.';
					exit;
				} else {
					
					if (!get_option("deep_style_first_save")){
						update_option("deep_style_first_save",'true');
					}
					
					$uploaddir = wp_upload_dir();
					$filename = $uploaddir['basedir']."/style_options.xml";
					$doc = new DOMDocument('1.0');
					$doc->formatOutput = true;
					$root = $doc->createElement('root');

					foreach ($deep_style_options as $value) {
						
						if (isset($value['id'])){
							if( isset( $_REQUEST[ $value['id'] ] ) && !in_array($value['type'], $nonsavable_types)) {
								update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
								
								$opt = $doc->createElement('option');
								$val = $doc->createElement('value');
								$valText = $doc->createTextNode($_REQUEST[$value['id']]);
								$val->appendChild($valText);
								
								$id = $doc->createElement('id');
								$idText = $doc->createTextNode($value['id']);
								$id->appendChild($idText);

								$opt->appendChild($id);								
								$opt->appendChild($val);

								$root->appendChild($opt);
																				
							} else if(!in_array($value['type'], $nonsavable_types)){
								delete_option( $value['id'] );
							}	
						}
	
						/*
						Update the values for the custom options that contain unlimited suboptions - for example when having
						 * a slider with fields "title" and "imageurl", for all the entities the titles will be saved in one field,
						 * separated by a separator. In this case, if the field name is slider_title and it contains some data like
						 * title 1|*|title2|*|title3 (|*| is the separator), then all this data will be saved into a custom field
						 * with id slider_titles.
						 */
						if($value['type']=='custom'){
							foreach($value['fields'] as $field){
								update_option( $field['id'].'s', $_REQUEST[ $field['id'].'s' ] );

								$opt = $doc->createElement('option');
								$val = $doc->createElement('value');
								if (isset($_REQUEST[$value['id']]))
									$valText = $doc->createTextNode($_REQUEST[$value['id']]);
								$val->appendChild($valText);
								
								$id = $doc->createElement('id');
								$idText = $doc->createTextNode($value['id']);
								$id->appendChild($idText);

								$opt->appendChild($id);								
								$opt->appendChild($val);

								$root->appendChild($opt);
																
								
							}
						}
					}
					
					$doc->appendChild($root);
					$doc->save($filename);		
					header("Location: themes.php?page=".DEEP_STYLE_OPTIONS_PAGE."&saved=true");
					die;
				}
			}	
		}
	}

}



/**
 * Inits the options functionality. Loads the files that contain the options arrays
 * to populate the global options array.
 */
function deep_init_options_functionality(){
	global $deep_options;

	$deep_options=array();

	//get all the categories
	$categories=get_categories('hide_empty=0');
	$deep_categories=array();
	for($i=0; $i<sizeof($categories); $i++){
		$deep_categories[]=array('id'=>$categories[$i]->cat_ID, 'name'=>$categories[$i]->cat_name);
	}

	//load the files that contain the options
	$deep_options_files = array('general', 'header-menu', 'widgetsarea', 'sliders', 'translation', 'social', 'data');
	if (defined('DEEP_PLG_ACTIVE') === true) $deep_options_files = array('general', 'customfonts', 'header-menu', 'widgetsarea', 'sliders', 'newsletter', 'translation', 'social', 'customcss' , 'data');
	
	foreach($deep_options_files as $file){
		require_once(DEEP_OPTIONS_PATH.$file.'.php');
	}
}


/**
 * Sets the Options save functionality.
 */
function deep_set_options(){
	
	wp_enqueue_script( 'boldway-ace-rich-editor', get_template_directory_uri().'/lib/classes/ace/min/ace.js', array('jquery'), $in_footer = false );
	
	global $deep_options;
	
	$nonsavable_types=array('open', 'close','subtitle','title','documentation');

	//insert the default values if the fields are empty
	foreach ($deep_options as $value) {
		if(isset($value['id'])){
			if(get_option($value['id'])=='' && isset($value['std']) && !in_array($value['type'], $nonsavable_types)){
				update_option( $value['id'], $value['std']);
			}
		}
	}
	
	//save the field's values if the Save action is present
	if ( $_GET['page'] == DEEP_OPTIONS_PAGE ) {
	
		if (isset($_REQUEST['action'])){
			if ( 'save' == $_REQUEST['action'] ) {
				//verify the nonce
				if ( empty($_POST) || !wp_verify_nonce($_POST['deep-theme-options'],'deep-theme-update-options') ){
					print 'Sorry, your nonce did not verify.';
					exit;
				} else {
					
					if (!get_option("deep_first_save")){
						update_option("deep_first_save",'true');
					}
					
					$uploaddir = wp_upload_dir();
					$filename = $uploaddir['basedir']."/options.xml";
					$doc = new DOMDocument('1.0');
					$doc->formatOutput = true;
					$root = $doc->createElement('root');

					foreach ($deep_options as $value) {
						
						if (isset($value['id'])){
							if( isset( $_REQUEST[ $value['id'] ] ) && !in_array($value['type'], $nonsavable_types)) {
								
								if ($value['id'] === "deep_portfolio_permalink"){
									$oldval = get_option("deep_portfolio_permalink");
									$newval = $_REQUEST[$value['id']];
									
									if ($oldval !== $newval){
										global $wpdb;
										$args = array(
											'posts_per_page' => -1,
											'post_type' => "$oldval"
										);
										$theposts = get_posts( $args );
										foreach ($theposts as $p){
											$oldGuid = $p->guid;
											$aux1 = explode("?post_type=",$oldGuid);
											$newGuid = home_url('/')."?post_type=".$newval."&amp;p=".$p->ID;
											$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET guid = %s WHERE ID = %d", $newGuid, $p->ID) );
											$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_type = %s WHERE ID = %d", $newval, $p->ID) );
										}
									} 
									
								}
								
								
								if ($value['id'] == 'ultimate_selected_google_fonts'){
									if (isset($_REQUEST[$value['id']])) update_option( $value['id'], unserialize(stripslashes(($_REQUEST[$value['id']]))));
								} else {
									if ( $value['id'] == 'page_on_front' && class_exists('Polylang') ){}
									else update_option( $value['id'], $_REQUEST[ $value['id'] ]  );	
								}
								
								$opt = $doc->createElement('option');
								$val = $doc->createElement('value');
								if ($value['id'] == 'ultimate_selected_google_fonts'){
									$fontsvalue = stripslashes($_REQUEST[$value['id']]);
									$valText = $doc->createTextNode($fontsvalue);
								} else $valText = $doc->createTextNode($_REQUEST[$value['id']]);
								$val->appendChild($valText);
								
								$id = $doc->createElement('id');
								$idText = $doc->createTextNode($value['id']);
								$id->appendChild($idText);

								$opt->appendChild($id);								
								$opt->appendChild($val);

								$root->appendChild($opt);
																				
							} else if(!in_array($value['type'], $nonsavable_types)){
								delete_option( $value['id'] );
							}	
						}
	
						/*
						Update the values for the custom options that contain unlimited suboptions - for example when having
						 * a slider with fields "title" and "imageurl", for all the entities the titles will be saved in one field,
						 * separated by a separator. In this case, if the field name is slider_title and it contains some data like
						 * title 1|*|title2|*|title3 (|*| is the separator), then all this data will be saved into a custom field
						 * with id slider_titles.
						 */
						if($value['type']=='custom'){
							foreach($value['fields'] as $field){
								update_option( $field['id'].'s', $_REQUEST[ $field['id'].'s' ] );
									
								$opt = $doc->createElement('option');
								$val = $doc->createElement('value');
								if (isset($_REQUEST[$field['id'].'s']))
									$valText = $doc->createTextNode($_REQUEST[$field['id'].'s']);
								$val->appendChild($valText);

								$id = $doc->createElement('id');
								$idText = $doc->createTextNode($field['id'].'s');
								$id->appendChild($idText);

								$opt->appendChild($id);								
								$opt->appendChild($val);

								$root->appendChild($opt);
							}
						}
					}
					$doc->appendChild($root);
					$doc->save($filename);		
					header("Location: themes.php?page=".DEEP_OPTIONS_PAGE."&saved=true");
					die;
				}
			}	
		}
	}

}

/**
 * Calls the options manager to print the Options page.
 */
function deep_theme_admin() {
	global $deep_options,$deep_options_manager;

	$deep_options_manager=new DeepOptionsManager("Deep", DEEP_IMAGES_URL, DEEP_UTILS_URL, DEEP_UPLOADS_URL, DEEP_VERSION);
	$deep_options_manager->set_options($deep_options);

	if ( isset($_REQUEST['saved'] )) {
		$deep_options_manager->print_saved_message();
	}
	if ( isset($_REQUEST['reset'] )) {
		$deep_options_manager->print_reset_message();
	}

	$deep_options_manager->print_heading("");
	$deep_options_manager->print_options();
	$deep_options_manager->print_footer();
}


/**
 * Calls the style options manager to print the Style Options page.
 */
function deep_theme_style_options_admin() {
	global $deep_style_options, $deep_style_options_manager;

	$deep_style_options_manager=new DeepStyleOptionsManager("Deep", DEEP_IMAGES_URL, DEEP_UTILS_URL, DEEP_UPLOADS_URL, DEEP_VERSION);
	$deep_style_options_manager->set_options($deep_style_options);

	if ( isset($_REQUEST['saved'] )) {
		$deep_style_options_manager->print_saved_message();
	}
	if ( isset($_REQUEST['reset'] )) {
		$deep_style_options_manager->print_reset_message();
	}

	$deep_style_options_manager->print_heading("");
	$deep_style_options_manager->print_options();
	$deep_style_options_manager->print_footer();
}



/**
 * Calls the style options manager to print the Demos page.
 */
function deep_theme_demos_admin() {
	global $deep_demos_manager;

	$deep_demos_manager=new DeepDemosManager("Deep", DEEP_IMAGES_URL, DEEP_UTILS_URL, DEEP_UPLOADS_URL, DEEP_VERSION);

	$deep_demos_manager->print_heading("");
	$deep_demos_manager->print_options();
	$deep_demos_manager->print_footer();
}




/**
 * Adds all the options that an array contains to the current global options array.
 * @param $option_arr the array that contains the options values
 */
function deep_add_options($option_arr){
	global $deep_options;

	foreach($option_arr as $option){
		$deep_options[]=$option;
	}
}

function deep_add_style_options($option_arr){
	global $deep_style_options;

	foreach($option_arr as $option){
		$deep_style_options[]=$option;
	}
}

/**
 * Gets an option
 * @param $option the option's second part of the ID (after the theme's shortname part)
 */
function deep_get_opt($option){
	return stripslashes(get_option("deep".$option));
}


function deep_get_custom_sidebars(){
	$res=array();
	$sides=get_option('deep_sidebar_name_names');
	if($sides){
		$res=explode(DEEP_SEPARATOR, $sides);
		array_pop($res);
	}
	return $res;
}


/**
 * Gets an array containing options settings and if there is an option for adding
 * multiple entities of one type, generates addional array elements for these entities.
 * For example: If there have been created 2 additional sliders, it will append
 * to option elements to this array for each slider.
 * @param $opt_array the array to be modified
 * @return an array containing the custom entity options
 */
function deep_add_custom_options($opt_array){
	$new_deep_options=array();

	foreach($opt_array as $option){
		if($option['type']=='multiple_custom'){
			//insert the new custom options here
				
			$saved_values=get_option($option['refers']);
			$saved_array=explode(DEEP_SEPARATOR, $saved_values);
			if(sizeof($saved_array)>1){
				array_pop($saved_array);
				foreach($saved_array as $custom_name){
					$id=deep_convert_to_class($custom_name);
					$custom_option=array(
					"id"=>$id,
					"name"=>$option["name"].$custom_name,
					"button_text"=>$option["button_text"],
					"type"=>"custom",
					"preview"=>$id.$option["preview"]
					);
						
					//generate new fields with different unique IDs
					$fields=$option['fields'];
					for($i=0; $i<sizeof($fields);$i++){
						$fields[$i]['id']=$id.$fields[$i]['id'];
					}
						
					$custom_option['fields']=$fields;
						
					array_push($new_deep_options, $custom_option);
				}
			}
				
		} else{
			//this is just a normal option, just append it into the new array
			array_push($new_deep_options, $option);
		}
	}

	return $new_deep_options;
}

function deep_fonts_array_builder(){
	$defaultfonts = array();
	$res = array(array("id" => "", "name"=> "---- Standard Fonts ----", "class" => "select_font_type"), array("id" => "Arial", "name" => "Arial", "class" => "select_font_name"), array("id" => "Arial Black", "name" => "Arial Black", "class" => "select_font_name"), array("id" => "Helvetica", "name" => "Helvetica", "class" => "select_font_name"), array("id" => "Helvetica Neue", "name" => "Helvetica Neue", "class" => "select_font_name"), array("id" => "Courier New", "name" => "Courier New", "class" => "select_font_name"), array("id" => "Georgia", "name" => "Georgia", "class" => "select_font_name"), array("id" => "Impact", "name" => "Impact", "class" => "select_font_name"), array("id" => "Lucida Sans Unicode", "name" => "Lucida Sans", "class" => "select_font_name"), array("id" => "Times New Roman", "name" => "Times New Roman", "class" => "select_font_name"), array("id" => "Trebuchet MS", "name" => "Trebuchet MS", "class" => "select_font_name"), array("id" => "Verdana", "name" => "Verdana", "class" => "select_font_name"), array("id" => "Hind|Normal", "name" => "Hind Normal", "class" => "select_font_name"), array("id" => "Hind|300", "name" => "Hind 300", "class" => "select_font_name"), array("id" => "Hind|500", "name" => "Hind 500", "class" => "select_font_name"), array("id" => "Hind|600", "name" => "Hind 600", "class" => "select_font_name"), array("id" => "Hind|700", "name" => "Hind 700", "class" => "select_font_name"), array("id" => "Mulish|Normal", "name" => "Mulish Normal", "class" => "select_font_name"), array("id" => "Mulish|300", "name" => "Mulish 300"), array("id" => "Mulish|500", "name" => "Mulish 500"), array("id" => "Mulish|700", "name" => "Mulish 700", array("id" => "Mulish|800", "name" => "Mulish 800"), array("id" => "Josefin|300", "name" => "Josefin 300"), array("id" => "Josefin|normal", "name" => "Josefin normal"), "class" => "select_font_name"));

	array_push($res, $defaultfonts);
	$selected_fonts = get_option('ultimate_selected_google_fonts');
	if(!empty($selected_fonts)) {
		array_push($res, array("id" => "", "name"=> "---- Custom Fonts ----", "class" => "select_font_type"));
		foreach($selected_fonts as $key => $sfont){
			if(!empty($sfont['variants'])){
				$variant = false;
				array_push($res, array("id" => $sfont['font_name']."|normal", "name" => $sfont['font_name']." Normal", "class" => "select_font_name"));
				foreach($sfont['variants'] as $svkey => $svariants){
					if ($svariants['variant_selected'] == 'true'){
						$variant = true;
						array_push($res,array("id" => $sfont['font_name']."|".$svariants['variant_value'], "name" => $sfont['font_name']." {$svariants['variant_value']}", "class" => "select_font_name"));
					}
				}
				if (!$variant){
					array_push($res, array("id" => $sfont['font_name'], "name" => $sfont['font_name'], "class" => "select_font_name"));
				}
			} else array_push($res, array("id" => $sfont['font_name'], "name" => $sfont['font_name'], "class" => "select_font_name"));
		}
	}
	return $res;
}

function deep_portfolio_types(){
	//load the porftfolio categeories
	$portf_categories=array(array('id'=>'all', 'name'=>'All Portfolios'));
	if (function_exists('deep_get_taxonomies')){
		$portf_taxonomies=deep_get_taxonomies('portfolio_type');
		if (isset($portf_taxonomies)){
			foreach($portf_taxonomies as $taxonomy){
				$portf_categories[]=array("name"=>$taxonomy->name, "id"=>$taxonomy->slug);
			}			
		}
	}
	return $portf_categories;
}

function deep_get_proj(){
	
	$deep_proj2=array(array('id'=>'default', 'name'=>'Default'));
	if (function_exists('deep_get_projects')){
		$deep_proj1 = deep_get_projects();
		foreach($deep_proj1 as $dp){
			$deep_proj2[]=array("name"=>$dp['p_title'], "id"=>$dp['p_id']);
		}
	}

	return $deep_proj2;
}

?>