<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://flothemes.com/
 * @since      1.0.0
 *
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Flo_Flex_Builder
 * @subpackage Flo_Flex_Builder/admin
 * @author     Flothemes <alexb@flothemes.com>
 */
class Flo_Flex_Builder_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * The option name where we will save a flag that tells us to enable/disable the local ACF json for this plugin.
	 * By default if the plugin is activated, the local json is set to this plugin and if we need to add new ACF fields in the theme, then we should disable local json for this plugin
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The local json option name.
	 */
	private $local_json_option_name;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->local_json_option_name = 'enable_'.$this->plugin_name.'_local_json';
 
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Flo_Flex_Builder_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Flo_Flex_Builder_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		$script_version = $this->version;
		
		if ( defined('FLO_ENVIROMENT') && FLO_ENVIROMENT == 'DEV') {
			$script_version = mt_rand(0, 99999);
		}

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/flo-flex-builder-admin.min.css', [], $script_version, 'all' );

	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Flo_Flex_Builder_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Flo_Flex_Builder_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		$script_version = $this->version;
		if ( defined('FLO_ENVIROMENT') && FLO_ENVIROMENT == 'DEV') {
			$script_version = mt_rand(0, 99999);
		}
		
		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/flo-flex-builder-admin.min.js', array( 'jquery' ), $script_version, false );

	}
	
	
	
	/**
		 * Check for the plugin updates
		 *
		 * @since    1.0.0
	 */
		function flo_include_updater() {

			if ( is_admin() && !version_compare(phpversion(), '5.3.0', '<') ) {

				$plugin_data = get_plugin_data( plugin_dir_path( __DIR__ ) . 'flo-flex-builder.php' );

				$plugin_version = $plugin_data['Version'];

				$flo_plugin_remote_path = 'http://flothemes.com/recommended_plugins/plugin-updates.php';

				$flo_plugin_slug = plugin_basename( plugin_dir_path( __DIR__ ) . 'flo-flex-builder.php' );

				$product_name = 'flo-flex-builder';

				$the_plugin = 'flo-flex-builder/flo-flex-builder.php';

				require_once ('class-flo-plugin-auto-update.php');

				new flo_plugin_auto_update ($plugin_version, $flo_plugin_remote_path, $flo_plugin_slug, $product_name, $the_plugin);

			}

		}
	
	/**
	 *
	 * Define the folder where the json files will be saved
	 *
	 */
	public function set_json_save_path( $path ) {
		if($this->local_json_enabled()) { // check if local json for this plugin is enabled
			// update path
			$path = plugin_dir_path( __FILE__ ) .'../'. 'plugin_json';	
		}
		
		return $path;
	}

	public function add_json_load_path( $paths ) {
		
		if($this->local_json_enabled()) { // check if local json for this plugin is enabled
			$paths[] = plugin_dir_path( __FILE__ ) .'../'. 'plugin_json';
		}

		return $paths;
	}


	/**
	 *
	 * Append the layout blocks provided by this plugin to the theme layout blocks
	 * This method is called by an ACF action 'acf/load_field/name=layout'
	 *
	 * @param object - $field -> the Layout field
	 *
	 */
	public function append_blocks($field) {

		// main layout from theme	
		$parentLayout = $field;

		if(isset($field['layouts'])) {
			$parentLayoutFields = $field['layouts'];	
		}else{
			$parentLayoutFields = [];
		}
		

		// child layout from plugin
		// make sure to use the correct field key 
		// for each plugin it must be unique
		$childLayout = acf_get_field('field_5bb35d7e0ce87'); 
		$childLayoutFields = $childLayout['layouts'];

		if(!is_array($childLayoutFields)) {
			$childLayoutFields = [];
			//echo sprintf('%s Warning: the %s plugin blocks can not be loaded for soame reason. Check Admin class - append_blocks() method.%s', '<span style="color: red;">', $this->plugin_name, '</span>'); 
		}

		// combine the two above back in the main layout
		$combinedLayout = array_merge($parentLayoutFields, $childLayoutFields);
		$field['layouts'] = $combinedLayout;

		return $field;
		
	}


	/**
	 *
	 * Enable or disable the local json being saved inside the current plugin files using a GET param
	 *
	 */
	public function enable_disable_local_acf_json() {
			
		// pass this GET param to disable the local json for the current plugin
		// the plugin folder name is used as a GET param in order to know exactly for which plugin to 
		// change the local json settings when there are several Flo Blocks plugins activated
		// i.e. &disable_local_json=flo-flex-builder
		if( isset($_GET['disable_local_json']) && $_GET['disable_local_json'] == $this->plugin_name) {
			update_option( $this->local_json_option_name, 0, $autoload = false );
		}

		// pass this GET param to enable the local json back
		if( isset($_GET['enable_local_json']) && $_GET['enable_local_json'] == $this->plugin_name) {
			delete_option( $this->local_json_option_name );
		}
		
	}

	/**
	 *
	 * Check wheather the local ACF json files are disabled for this plugin
	 * @return bool - true or false depending if 
	 */
	public function local_json_enabled() {

		if(get_option( $this->local_json_option_name, $default = 1 ) === "0") {
			// the option name is like 'enable_{plugin_name}_local_json'
			// if this option exists, and equals 0, then that means the loca json is disabled
			return false;
		}

		return true;
	}
}

if(!function_exists('flex_get_theme_list')) {
	function flex_get_theme_list() {
		return [
			'cannes' => [
				'html_font_size' => 1.25,
				'block_padding' => 6.25
			],
			'crowd2' => [
				'html_font_size' => 1.21,
				'block_padding' => 3.4375
			],
			'cube' => [
				'html_font_size' => 1.15,
				'block_padding' => 9.375
			],
			'evora' => [
				'html_font_size' => 1.25,
				'block_padding' => 6.25
			],
			'fiji2' => [
				'html_font_size' => 1.25,
				'block_padding' => 9.0625
			],
			'kyoto' => [
				'html_font_size' => 1.21,
				'block_padding' => 4.46875
			],
			'leon' => [
				'html_font_size' => 1.25,
				'block_padding' => 4.375
			],
			'lovely2' => [
				'html_font_size' => 1.25,
				'block_padding' => 9.0625
			],
			'milea' => [
				'html_font_size' => 1.25,
				'block_padding' => 3.75
			],
			'narcisse' => [
				'html_font_size' => 1.25,
				'block_padding' => 6.25
			],
			'osaka' => [
				'html_font_size' => 1.25,
				'block_padding' => 6.25
			],
			'porto2' => [
				'html_font_size' => 1.11111,
				'block_padding' => 6.375
			],
			'rosemary2' => [
				'html_font_size' => 1.25,
				'block_padding' => 3.75
			],
			'trento' => [
				'html_font_size' => 1.25,
				'block_padding' => 4.375
			]
		];
	}
}

// start: get theme data (BLOCK PADDINGS AND HTML FONT SIZE) and set it as a transient
	if(!function_exists('flex_get_theme_data')) {
		function flex_get_theme_data() {

			$theme_data_arr = null;
			$theme_data_arr = apply_filters('flex_theme_padding', $theme_data_arr);
			if ($theme_data_arr === null) {
				$theme_list = flex_get_theme_list();
				$current_theme_name = strtolower(wp_get_theme()->get('Name'));
				$child_to_parent = str_replace('child', '', $current_theme_name);
				$current_theme = str_replace(' ', '', $child_to_parent);
				
				if(isset($theme_list[$current_theme])) {
					$theme_data_arr = $theme_list[$current_theme];
				} else {
					$theme_data_arr = [
						'html_font_size' => 1.25,
						'block_padding' => 3.75
					];
				}		
			}		
			
			return $theme_data_arr;
		}
	}

	if(!function_exists('flex_set_theme_data')) {
		function flex_set_theme_data() {
			$dummy_block_padding = flex_get_theme_data();
			if(!get_transient('flex_theme_data_transient')) {
				$theme_data = flex_get_theme_data();
				// store as 24 hours transient
				set_transient( 'flex_theme_data_transient', json_encode($theme_data), 60*60*24 );
			}
		}
	}

	if(!function_exists('flex_reset_theme_data')) {
		function flex_reset_theme_data() {
			delete_transient('flex_theme_data_transient');
			flex_set_theme_data();
		}
	}

	add_action('admin_init', 'flex_set_theme_data');
	add_action('after_switch_theme', 'flex_reset_theme_data');
// end: get theme data (BLOCK PADDINGS AND HTML FONT SIZE) and set it as a transient


/* START: GET STYLEKIT COLORS IF PRESENT */
	if(!function_exists('flex_get_stylekit_colors')) {
		function flex_get_stylekit_colors() {
			if(function_exists('flo_get_current_style_kit')) {
				$current_stylekit = flo_get_current_style_kit();
				if(file_exists(get_template_directory()."/theme-files/flo_stylekits_config/".$current_stylekit."/colors_settings.php")) {
					include(get_template_directory()."/theme-files/flo_stylekits_config/".$current_stylekit."/colors_settings.php");
					if(isset($color_settings) && is_array($color_settings)){
						$flex_stylekit_color_list = [];
						$flex_stylekit_color_labels = [];
						foreach ($color_settings as $color_name => $color_value) {
							// $saved_color = flo_get_option($color_name);
							$color_obj = get_field_object($color_name, 'options');
							$color_label = $color_obj['label'];
							$flex_stylekit_color_labels[$color_name] = $color_label;
							if($color_obj['value']) {
								$flex_stylekit_color_list[$color_name] = $color_obj['value'];
							} else {
								$flex_stylekit_color_list[$color_name] = $color_obj['default_value'];
							}
						}
						
						$blocks = flex_load_block_paths();
						if($blocks && is_array($blocks) && sizeof($blocks)) {
							$style_parent_theme_author = wp_get_theme( get_template() )->get( "Name" );
							wp_localize_script('flo-flex-builder', 'flex_theme_name', strtolower($style_parent_theme_author));	
							wp_localize_script('flo-flex-builder', 'flex_predefined_blocks', $blocks);	
						}
						
						wp_localize_script('flo-flex-builder', 'flex_stylekit_color_list', $flex_stylekit_color_list);
						wp_localize_script('flo-flex-builder', 'flex_stylekit_color_labels', $flex_stylekit_color_labels);
						
					}
				}
			}
		}
	}
	add_action('admin_enqueue_scripts', 'flex_get_stylekit_colors', 11);
/* END: GET STYLEKIT COLORS IF PRESENT */

/* START: SCREENSHOT RELATED FUNCTIONS */
	add_action('wp_ajax_flex_upload_screen', 'flex_upload_screen');
	add_action('wp_ajax_nopriv_flex_upload_screen', 'flex_upload_screen'); // Allow front-end submission 

	function flex_upload_screen() {
		$img = $_POST['main_image'];
		$filename = $_POST['screen_name'];
		$uploaded_img = flex_save_base64_image($img, $filename);
		echo $uploaded_img;
		exit();
	}

	if(!function_exists('flex_save_base64_image')) {
		function flex_save_base64_image($base64_image_string, $output_file_name_without_extension) {
			global $wp_filesystem;
			
			// get uploads dir
			$upload_dir = wp_upload_dir();
			$upload_basedir = $upload_dir['basedir'];
			$upload_baseurl = $upload_dir['baseurl'];
			
			$screens_dir = $upload_basedir . '/flex_screens/';
			
			// if folder that will hold the screens does not exist yet, create it
			if(!$wp_filesystem->is_dir($screens_dir)) {
				$wp_filesystem->mkdir($screens_dir);
			}
			
			// folder exists, push image to it
			$file = false;
			if($wp_filesystem->is_dir($screens_dir)) {
				
				$splited = explode(',', substr($base64_image_string, 5), 2);
				$data64 = $splited[1];
				
				$mime = $splited[0];
				$mime_split_without_base64 = explode(';', $mime, 2);
				$mime_split = explode('/', $mime_split_without_base64[0], 2);
				$ext = $mime_split[1];
				
				$filePath = $screens_dir . $output_file_name_without_extension . ".png";
				$fileCallback = $wp_filesystem->put_contents(
					$filePath,
					base64_decode($data64),
					FS_CHMOD_FILE // predefined mode settings for WP files
				);
				
				$publicFilePath = str_replace($upload_basedir, $upload_baseurl, $filePath);
				if($fileCallback) $file = $publicFilePath;
			}
			
			return $file;
			
		}	
	}
	add_action('wp_ajax_flex_delete_screen', 'flex_delete_screen');
	add_action('wp_ajax_nopriv_flex_delete_screen', 'flex_delete_screen'); // Allow front-end submission 

	function flex_delete_screen() {
		global $wp_filesystem;
		
		$img = $_POST['main_image'];
		
		$upload_dir = wp_upload_dir();
		$upload_basedir = $upload_dir['basedir'];
		$upload_baseurl = $upload_dir['baseurl'];
		
		$img_basedir = str_replace($upload_baseurl, $upload_basedir, $img);
		
		if(file_exists($img_basedir)) {
			$wp_filesystem->delete($img_basedir, true);
			echo 'success';
		}
		
		exit();
	}
/* END: SCREENSHOT RELATED FUNCTIONS */

/* START: TYPOGRAPHY RELATED FUNCTIONS */
	if(!function_exists('flex_get_flothemes_fonts')) {
		function flex_get_flothemes_fonts() {
			$flothemesFontList = get_field('flex_font_list', 'options');
			if(is_array($flothemesFontList) && sizeof($flothemesFontList)) {
				$fontNames = [];
				$fontFaces = "";
				foreach ($flothemesFontList as $font) {
					if((isset($font['font_name']) && strlen($font['font_name'])) && (isset($font['font_url']) && strlen($font['font_url']))) {
						$fontNames[$font['font_name']] = $font['font_name'];
						$fontFaces .= ' @font-face {font-family: "'.$font['font_name'].'"; src: url('.$font['font_url'].')}';
					}
				}
				
				$flothemes_font_map = [
					'fontNames' => $fontNames,
					'fontFaces' => $fontFaces
				];
				
				return $flothemes_font_map;
			}
			
			return false;
		}
	}

	if(!function_exists('flex_set_font_transient')) {
		function flex_set_font_transient() {
			$font_faces = '';
			$font_names = [];
			$google_font_face = [];
			$theme_typography_option_name = 'flo-typography';
			$theme_typography_option_name = apply_filters('flo_theme_typography_option_name', $theme_typography_option_name);
			$flo_typography = get_field($theme_typography_option_name, 'options');
			
			if(isset($flo_typography['font_styles'])) {
				if (is_string($flo_typography['font_styles'])) {
					$font_styles_data = json_decode($flo_typography['font_styles']);
				} else {
					$font_styles_data = (array) $flo_typography['font_styles'];
				}
				
				if(is_object($font_styles_data)) {

					$theme_defaults = [];
					$user_specified = [];
					$font_styles = [];
					
					if(isset($font_styles_data->theme_defaults)) {
						$theme_defaults = $font_styles_data->theme_defaults;
					}
					if(isset($font_styles_data->user_specified)) {
						$user_specified = $font_styles_data->user_specified;
					}

					// merge the 2 objects to have only 1 iteration for both
					$typography_styles = (object) array_merge((array) $theme_defaults, (array) $user_specified);
					// iterate and construct font data

					foreach ($typography_styles as $fontName => $value) {
						$font_face = get_font_face($value);
						$font_style_css = get_font_styles($value);
						
						$font_styles[$fontName] = [
							'name' => $value->font_style_name,
							'style' => $font_style_css['default'],
							'mobile_style' => $font_style_css['mobile']
						];
						
						if(isset($value->font_family) && !in_array($value->font_family, $font_names)) {
							
							if(isset($font_face['custom_font_face'])) {
								$font_faces .= $font_face['custom_font_face'];	
								$font_names[$value->font_family] = $value->font_family;
							} else if(isset($font_face['google_font_face']) && !in_array($font_face['google_font_face'], $google_font_face)) {
								$google_font_face[] = $font_face['google_font_face'];
								$font_names[$font_face['google_font_face']] = $font_face['google_font_face'];
							}
						}
					}
				}
			}
			
			if(sizeof($google_font_face)) {
				
				$site_url = get_site_url();
				$isHttps = strpos($site_url, 'https') !== false;
				$g_url = [];
				if(!$isHttps) {
					foreach ($google_font_face as $i => $googleFont) {
						$family_name = trim(str_replace(' ', '+', $googleFont));
						$query_args = ['family' => $family_name];
						$g_url[] = add_query_arg( $query_args, "//fonts.googleapis.com/css" );
					}
				} else {
					$family_name = implode('|', $google_font_face);
					$family_name = trim(str_replace(' ', '+', $family_name));
					$query_args = [ 'family' => $family_name ];
					$g_url[] = add_query_arg( $query_args, "//fonts.googleapis.com/css" );
				}
				
			}
			
			// custom_fonts
			if(isset($flo_typography['custom_fonts']) && strlen($flo_typography['custom_fonts'])) {
				$custom_fonts_data = json_decode($flo_typography['custom_fonts']);
				$custom_fonts_generated = acf_field_flo_typography::process_custom_fonts_list($custom_fonts_data);
				if(gettype($custom_fonts_generated) === 'array' && sizeof($custom_fonts_generated)) {
					foreach ($custom_fonts_generated as $font_data) {
						$custom_font_name = $font_data['font_family'];
						$font_names[$custom_font_name] = $custom_font_name;
						$custom_font_face = acf_field_flo_quick_typography::get_custom_font_face($font_data);
						$font_faces .= $custom_font_face;
					}
				}
			}
			
			$font_map = [
				'fontNames' => $font_names,
				'fontFaces' => $font_faces
			];
			
			if(isset($font_styles)) {
				$font_map['fontStyles'] = $font_styles;
			}
			if(isset($g_url)) {
				$font_map['themeGFontsURL'] = $g_url;
			}
			$flothemes_font_map = json_encode($font_map);
			
			// store as 24 hours transient
			set_transient( 'flex_font_data_transient', $flothemes_font_map, 60*60*24 );
			return $flothemes_font_map;
		}
	}

	if(!function_exists('flex_get_fonts')) {
		function flex_get_fonts() {
			$isFlothemes = Flo_Flex_Builder::isFlothemes();
			if($isFlothemes) {
				$flothemes_font_map = flex_get_flothemes_fonts();
			} else {
				delete_transient('flex_font_data_transient');
				if(!get_transient('flex_font_data_transient')) {
					$flothemes_font_map = flex_set_font_transient();
				} else {
					$flothemes_font_map = get_transient('flex_font_data_transient');
				}
			}
			
			wp_localize_script('flo-flex-builder', 'flothemes_font_map', $flothemes_font_map);
		}
	}
	add_action('admin_enqueue_scripts', 'flex_get_fonts', 11);
	
	add_action('acf/save_post', 'delete_flex_font_data', 20);
	function delete_flex_font_data() {
		if(get_transient('flex_font_data_transient')) {
			delete_transient('flex_font_data_transient');
		}
	}
/* END: TYPOGRAPHY RELATED FUNCTIONS */

require_once( __DIR__ . '/save-blocks.php' );
require_once( __DIR__ . '/load-blocks.php' );