<?php
/*
* Plugin-Name: Product Designer App
* Plugin-URI: https://productdesignerapp.com
* Author: productdesignerapp
* Helper Function
*/

if (!defined('ABSPATH'))
{
    exit;
}

global $wp_filesystem;
if(!$wp_filesystem)
{
	require_once ABSPATH . 'wp-admin/includes/file.php';
	WP_Filesystem();
} 

/******************** System ********************/
/******************** Database ********************/
/*
* Insert
*/
if(!function_exists('pdapp_insert_db'))
{
	function pdapp_insert_db($tableName = "", $insert = [], $format = null)
	{
		global $wpdb;
		$wpdb->insert($tableName, $insert, $format);
		$id = $wpdb->insert_id;
		return $id;
	}
}

/*
* Update
*/
if(!function_exists('pdapp_update_db'))
{
	function pdapp_update_db($tableName = "", $update = [], $whereArr = [], $format = null, $whereFormat = null)
	{
		global $wpdb;
		return $wpdb->update($tableName, $update, $whereArr, $format, $whereFormat);
	}
}

/*
* Delete
*/
if(!function_exists('pdapp_delete_db'))
{
	function pdapp_delete_db($tableName = "", $whereArr = [], $whereFormat = null)
	{
		global $wpdb;
		return $wpdb->delete($tableName, $whereArr, $whereFormat);
	}
}

/******************** Input/Output ********************/
/*
* Response
*/
if(!function_exists('pdapp_response'))
{
	function pdapp_response($error = 0, $msg = 'Success', $data = [])
	{
		$res = [
			'error'=>$error,
			'msg'=>$msg,
			'data'=>$data
		];

		header('Content-Type: application/json');
		echo wp_json_encode($res, JSON_PRETTY_PRINT);
		exit;
	}
}

/*
* Get
*/
if(!function_exists('pdapp_get'))
{
	function pdapp_get($param="", $default=false)
	{
		if(isset($_GET[$param]))
		{
			return sanitize_text_field(wp_unslash($_GET[$param]));
		}
		
		return $default;
	}
}

/*
* Post
*/
if(!function_exists('pdapp_post'))
{
	function pdapp_post($key='', $type="text", $default=false)
	{
		if($key != '' && isset($_POST[$key]))
		{
			$langs = $type == 'lang' ? pdapp_get_lang_available() : [];
			$default = pdapp_clean_data($type, $_POST[$key], $langs, $default);
		}
		
		return $default;
	}
}

/*
* Clean datas
*/
if(!function_exists('pdapp_clean_data'))
{
	function pdapp_clean_data($type='text', $value="", $langs=[], $default=false)
	{
		switch ($type)
		{
			case "key":
				return sanitize_key(wp_unslash($value));
				break;
			case "text":
				return sanitize_text_field(wp_unslash($value));
				break;
			case "email":
				return sanitize_email(wp_unslash($value));
				break;
			case "lang":
				$title = [];
				if(is_array($value))
				{
					foreach($langs as $lk=>$lang)
					{
						$title[$lk] = isset($value[$lk]) ? sanitize_text_field(wp_unslash($value[$lk])) : "Untitle";
					}
				}else
				{
					$post = sanitize_text_field(wp_unslash($value));
					$posts = json_decode($post, true);
					if(is_array($posts))
					{
						foreach($posts as $lk=>$lang)
						{
							$title[$lk] = isset($posts[$lk]) ? $posts[$lk] : "Untitle";
						}
					}
				}

				return $title;
				break;
			default:
				return sanitize_textarea_field(wp_unslash($value));
		}
		
		return $default;
	}
}

if(!function_exists('pdapp_post_arrs'))
{
	function pdapp_post_arrs($key='', $fields=[], $default=[])
	{
		if($key != '' && isset($_POST[$key]))
		{
			$i=0;
			$res = [];
			$langs = [];
			while(isset($_POST[$key][$i]))
			{
				$check = false;
				foreach($fields as $k=>$type)
				{
					if(!isset($_POST[$key][$i][$k]))
					{
						$check = true;
						break;
					}

					if($type == 'lang' && count($langs) == 0)
					{
						$langs = pdapp_get_lang_available();
					}
					$res[$i][$k] = pdapp_clean_data($type, $_POST[$key][$i][$k], $langs);
				}
				
				if($check)
				{
					$res = [];
					break;
				}
				
				$i++;
			}

			return $res;
		}
		
		return $default;
	}
}

if(!function_exists('pdapp_post_textarea'))
{
	function pdapp_post_textarea($key='', $default=false)
	{
		if($key != '' && isset($_POST[$key]))
		{
			return sanitize_textarea_field(wp_unslash($_POST[$key]));
		}
		
		return $default;
	}
}

/*
* Verify field data
*/
if(!function_exists('pdapp_verify_field'))
{
	function pdapp_verify_field($fields=[], $allows = [])
	{
		$res    = [];
		foreach ($fields as $key => $value)
		{
			if (in_array($key, $allows))
			{
				if (is_array($value) || is_object($value))
				{
					$res[$key] = pdapp_json_encode($value);
				}else
				{
					$res[$key] = $value;
				}
			}
		}

		return $res;
	}
}

if(!function_exists('pdapp_json_encode'))
{
	function pdapp_json_encode($arrs = [])
	{
		$str = wp_json_encode($arrs);

		return str_replace('"false"', 'false', str_replace('"true"', 'true', $str));
	}
}

/********************* Sercurity *******************/
/*
* Check token
*/
if(!function_exists('pdapp_check_token'))
{
	function pdapp_check_token($admin = false)
	{
		$pdappNonce = pdapp_get('pdapp-nonce');
		if($pdappNonce != '')
		{
			if($admin)
			{
				return wp_verify_nonce($pdappNonce, PDAPP_ADMIN_NONCE);
			}else
			{
				if(!wp_verify_nonce($pdappNonce, PDAPP_FRONT_NONCE))
				{
					return false;
				}

				$pdappToken = pdapp_get('pdapp-token');
				if($pdappToken != '')
				{
					$tokens = explode('-', $pdappToken);
					if(count($tokens) == 2)
					{
						$file = $tokens[0];
						$token = $tokens[1];
						
						$result = pdapp_get_cache('tokens', $file);
						if($result && isset($result[$token]))
						{
							return true;
						}
					}
				}
			}
		}
		
		return false;
	}
}

/*
* Create token
*/
if(!function_exists('pdapp_create_token'))
{
	function pdapp_create_token()
	{
		$token = uniqid(wp_rand(0, 10000));
		$file = gmdate("YmdH");
		$result = pdapp_get_cache('tokens', $file);
		if(!$result)
		{
			$result = [$token => 1];
		}else
		{
			$result[$token] = 1;
		}
		
		$expired = (int) PDAPP_TOKEN_DATE * 86400;
		pdapp_set_cache('tokens', $file, $result, $expired);
		
		return $file .'-'. $token;
	}
}

/*
* Refresh token
*/
if(!function_exists('pdapp_refresh_token'))
{
	function pdapp_refresh_token()
	{
		return wp_create_nonce(PDAPP_ADMIN_NONCE);
	}
}

/******************** Dashboard ********************/
/*
* Requirements
*/
if(!function_exists('pdapp_get_system_value'))
{
	function pdapp_get_system_value($key="", $convert = false)
	{
		$value = ini_get($key);

		if ($value)
		{
			if($convert)
			{
				$byt = (int) $value;
				if($byt == -1)
				{
					return $value;
				}
				$unit = strtoupper(substr($value, -1));

				switch ($unit)
				{
					case 'K':
						$byt *= 1024;
						break;
					case 'M':
						$byt *= 1024 * 1024;
						break;
					case 'G':
						$byt *= 1024 * 1024 * 1024;
						break;
				}

				return $byt;
			}

			return $value;
		}

		return false;
	}
}

/*
* get Woo Version
*/
if(!function_exists('pdapp_get_woo_version'))
{
	function pdapp_get_woo_version()
	{
		$wooCommerceVersion = get_option('woocommerce_version');

		if($wooCommerceVersion)
		{
			return $wooCommerceVersion;
		}

		return false;
	}
}

/*
* get Totals
*/
if(!function_exists('pdapp_get_total_info'))
{
	function pdapp_get_total_info()
	{
		$totals = pdapp_get_cache('dashboards', 'totals');
		if($totals && isset($totals['time']) && $totals['time'] < strtotime("-900 seconds"))
		{
			$totals = '';
		}
		
		if($totals == '')
		{
			global $wpdb;
			$totals = [
				'time'=>strtotime("now"),
				'orders'=>0,
				'arts'=>0,
				'templates'=>0,
				'products'=>0
			];
			
			$res = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) AS total_rows FROM %i WHERE type='o'", PDAPP_DB_ORDERS), ARRAY_A);
			if(isset($res['total_rows']))
			{
				$totals['orders'] = $res['total_rows'];
			}

			$res = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) AS total_rows FROM %i", PDAPP_DB_ARTWORKS), ARRAY_A);
			if(isset($res['total_rows']))
			{
				$totals['arts'] = $res['total_rows'];
			}

			$res = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) AS total_rows FROM %i", PDAPP_DB_TEMPLATES), ARRAY_A);
			if(isset($res['total_rows']))
			{
				$totals['templates'] = $res['total_rows'];
			}

			$res = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) AS total_rows FROM %i", PDAPP_DB_PRODUCTS), ARRAY_A);
			if(isset($res['total_rows']))
			{
				$totals['products'] = $res['total_rows'];
			}

			pdapp_set_cache('dashboards', 'totals', $totals);
		}

		if(isset($totals['time']))
		{
			unset($totals['time']);
		}

		return $totals;
	}
}

/*
* get Writables
*/
if(!function_exists('pdapp_check_writable'))
{
	function pdapp_check_writable($path="")
	{
		$file = $path .'/testWrite.txt';
		pdapp_write_file($file, '');
		return file_exists($file);
	}
}

/*
* get Requirements
*/
if(!function_exists('pdapp_get_requirements'))
{
	function pdapp_get_requirements()
	{
		global $wp_version;
		$woo_version = pdapp_get_woo_version();
		
		$checkPHP = version_compare(PHP_VERSION, PDAPP_PHP_VERSION, '<') ? false : true;
		$checkWP = version_compare($wp_version, PDAPP_WP_VERSION, '<') ? false : true;
		$checkWOO = !$woo_version && version_compare($woo_version, PDAPP_WOO_VERSION, '<') ? false : true;

		pdapp_set_cache('test', 'file', 'written');
		$testCache = pdapp_get_cache('test', 'file');
		$checkCache = $testCache == 'written' ? true : false;
		pdapp_delete_cache('test', 'file');

		$checkWrite = pdapp_check_writable(PDAPP_UPLOAD_DIR .'test');
		pdapp_delete_dir(PDAPP_UPLOAD_DIR .'test');

		$maxUploads = pdapp_get_system_value('max_file_uploads');
		if(!$maxUploads)
		{
			$maxUploads = 0;
		}
		$checkMaxUpload = $maxUploads >= 100 ? true : false;

		$maxPosts = pdapp_get_system_value('post_max_size', true);
		if(!$maxPosts)
		{
			$maxPosts = 0;
		}
		if($maxPosts >= 0)
		{
			$maxPosts = $maxPosts / (1024 * 1024);
		}
		$checkMaxPost = $maxPosts < 0 || $maxPosts >= 50 ? true : false;

		$maxSizes = pdapp_get_system_value('upload_max_filesize', true);
		if(!$maxSizes)
		{
			$maxSizes = 0;
		}
		if($maxSizes >= 0)
		{
			$maxSizes = $maxSizes / (1024 * 1024);
		}
		$checkMaxSize = $maxSizes < 0 || $maxSizes >= 50 ? true : false;

		$maxMemory = pdapp_get_system_value('memory_limit', true);
		if(!$maxMemory)
		{
			$maxMemory = 0;
		}
		if($maxMemory >= 0)
		{
			$maxMemory = $maxMemory / (1024 * 1024);
		}
		$checkMemory = $maxMemory < 0 || $maxMemory >= 1024 ? true : false;

		$maxInputs = pdapp_get_system_value('max_input_vars');
		if(!$maxInputs)
		{
			$maxInputs = 0;
		}
		$checkMaxInput = $maxInputs >= 10000 ? true : false;

		$purchased = pdapp_get_user_key();

		$res = [
			[
				"icon"=>$checkPHP ? 'check' : 'block',
				"status"=>$checkPHP ? 'success' : 'danger',
				"key"=>'php_version',
				"require"=>PDAPP_PHP_VERSION. '+',
				"current"=>PHP_VERSION
			],
			[
				"icon"=>$checkWP ? 'check' : 'block',
				"status"=>$checkWP ? 'success' : 'danger',
				"key"=>'wp_version',
				"require"=>PDAPP_WP_VERSION. '+',
				"current"=>$wp_version
			],
			[
				"icon"=>$checkWOO ? 'check' : 'block',
				"status"=>$checkWOO ? 'success' : 'danger',
				"key"=>'woo_version',
				"require"=>PDAPP_WOO_VERSION. '+',
				"current"=>$woo_version
			],
			[
				"icon"=>$checkWrite ? 'check' : 'block',
				"status"=>$checkWrite ? 'success' : 'danger',
				"key"=>'upload_folder',
				"require"=>pdapp_lang('dashboard.writable', 'admin'),
				"current"=>$checkWrite ? pdapp_lang('dashboard.writable', 'admin') : pdapp_lang('dashboard.not_writable', 'admin')
			],
			[
				"icon"=>$checkCache ? 'check' : 'warning',
				"status"=>$checkCache ? 'success' : 'warning',
				"key"=>'cache_folder',
				"require"=>pdapp_lang('dashboard.writable', 'admin'),
				"current"=>$checkCache ? pdapp_lang('dashboard.writable', 'admin') : pdapp_lang('dashboard.not_writable', 'admin')
			],
			[
				"icon"=>$checkMaxUpload ? 'check' : 'warning',
				"status"=>$checkMaxUpload ? 'success' : 'warning',
				"key"=>'max_file_uploads',
				"require"=>'100+',
				"current"=>$maxUploads
			],
			[
				"icon"=>$checkMaxPost ? 'check' : 'warning',
				"status"=>$checkMaxPost ? 'success' : 'warning',
				"key"=>'post_max_size',
				"require"=>'50M+',
				"current"=>$maxPosts < 0 ? pdapp_lang('dashboard.unlimit', 'admin') : $maxPosts. 'M'
			],
			[
				"icon"=>$checkMaxSize ? 'check' : 'warning',
				"status"=>$checkMaxSize ? 'success' : 'warning',
				"key"=>'upload_max_filesize',
				"require"=>'50M+',
				"current"=>$maxSizes < 0 ? pdapp_lang('dashboard.unlimit', 'admin') : $maxSizes. 'M'
			],
			[
				"icon"=>$checkMemory ? 'check' : 'warning',
				"status"=>$checkMemory ? 'success' : 'warning',
				"key"=>'memory_limit',
				"require"=>'1024M+',
				"current"=>$maxMemory < 0 ? pdapp_lang('dashboard.unlimit', 'admin') : $maxMemory. 'M'
			],
			[
				"icon"=>$checkMaxInput ? 'check' : 'warning',
				"status"=>$checkMaxInput ? 'success' : 'warning',
				"key"=>'max_input_vars',
				"require"=>'10000+',
				"current"=>$checkMaxInput
			],
			[
				"icon"=>$purchased != '' ? 'check' : 'warning',
				"status"=>$purchased != '' ? 'success' : 'warning',
				"key"=>'purchased',
				"require"=>pdapp_lang('dashboard.verify', 'admin'),
				"current"=>$purchased != '' ? pdapp_lang('dashboard.verified', 'admin') : pdapp_lang('dashboard.not_verify', 'admin'),
			]
			
		];

		return $res;
	}
}
/*
* get Charts
*/
if(!function_exists('pdapp_get_chart_orders'))
{
	function pdapp_get_chart_orders($type="")
	{
		global $wpdb;
		$datas = [];
		$vals = pdapp_get_cache('dashboards', 'chart_'. $type);
		if($vals && isset($vals['time']) && $vals['time'] < strtotime("-1 hours"))
		{
			$vals = '';
		}
		
		if($vals == '')
		{
			$orderTable = PDAPP_DB_ORDERS;
			if($type == 'month')
			{
				$month = gmdate('m');
				$result = $wpdb->get_results($wpdb->prepare("SELECT DAY(created) AS day, COUNT(*) AS total FROM %i WHERE `type` = 'o' AND MONTH(created) = %d GROUP BY DAY(created);", [$orderTable, $month]), ARRAY_A);
			}else
			{
				$year = gmdate('Y');
				$result = $wpdb->get_results($wpdb->prepare("SELECT MONTH(created) AS month, COUNT(*) AS total FROM %i WHERE `type` = 'o' AND YEAR(created) = %d GROUP BY MONTH(created);", [$orderTable, $year]), ARRAY_A);
			}
			$vals = [
				'time'=>strtotime("now"),
				'result'=>$result
			];

			pdapp_set_cache('dashboards', 'chart_'. $type, $vals);
		}
		$result = isset($vals['result']) ? $vals['result'] : [];
		
		$labels = [];
		if($type == 'month')
		{
			for($i=0; $i<31; $i++)
			{
				$labels[] = $i+1;
				$added = false;
				foreach($result as $res)
				{
					if($res['day'] == $i+1)
					{
						$datas[] = $res['total'];
						$added = true;
						break;
					}
				}

				if(!$added)
				{
					$datas[] = 0;
				}
			}
		}else
		{
			for($i=0; $i<12; $i++)
			{
				$labels[] = pdapp_lang('dashboard.month_'. ($i+1), 'admin');
				$added = false;
				foreach($result as $res)
				{
					if($res['month'] == $i+1)
					{
						$datas[] = $res['total'];
						$added = true;
						break;
					}
				}

				if(!$added)
				{
					$datas[] = 0;
				}
			}
		}

		return [
			"labels"=>$labels,
			"datasets"=>[[
				"label"=>pdapp_lang('dashboard.orders', 'admin'),
				"data"=>$datas,
				"backgroundColor"=>["rgba(102, 88, 221, 0.8)"],
				"borderColor"=>["rgba(102, 88, 221, 1)"],
				"borderWidth"=>1
			]]
		];
	}
}

/******************** Menus ********************/
/*
* get Menus
*/
if(!function_exists('pdapp_get_menus'))
{
	function pdapp_get_menus()
	{
		global $wpdb;
		$menus = pdapp_get_cache('settings', 'list_menus');
		if(!$menus)
		{
			$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='mn'", PDAPP_DB_SETTINGS), ARRAY_A);
			if(isset($res['values']))
			{
				$menus = json_decode($res['values'], true);
				pdapp_set_cache('settings', 'list_menus', $menus);
			}
		}

		if(!isset($menus['text']))
		{
			$menus = [];
		}
		
		foreach($menus as $key=>$menu)
		{
			$menus[$key]['title'] = pdapp_lang($menu['title'], 'front');
		}

		return $menus;
	}
}

/******************** Prints ********************/
/*
* get Print types
*/
if(!function_exists('pdapp_print_types'))
{
	function pdapp_print_types()
	{
		$prints = [];
		$path = PDAPP_PLUGIN_DIR .'datas/prints.json';
		$print = pdapp_read_file($path);
		if($print)
		{
			$prints = json_decode($print, true);
			foreach($prints as $key=>$print)
			{
				$prints[$key]['title'] = pdapp_lang('print.'. $print['title'], 'admin');
				foreach($prints[$key]['value'] as $k=>$v)
				{
					$prints[$key]['value'][$k]['title'] = pdapp_lang('print.'. $v['title'], 'admin');
					$prints[$key]['value'][$k]['desc'] = pdapp_lang('print.'. $v['desc'], 'admin');
				}
			}
		}

		return $prints;
	}
}

/*
* get List Print
*/
if(!function_exists('pdapp_get_prints'))
{
	function pdapp_get_prints()
	{
		$prints = pdapp_get_cache('prints', 'lists');
		if(!$prints)
		{
			$prints = [];
			global $wpdb;
			$res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i", PDAPP_DB_PRINTS), ARRAY_A);
			
			foreach($res as $val)
			{
				$prints[] = ["id"=>$val['id'], "pid"=>$val['pid'], "title"=>$val["title"], "thumb"=>$val['thumb'], "created"=>$val['created']];
			}
			pdapp_set_cache('prints', 'lists', $prints);
		}

		return $prints;
	}
}

/******************** Cache ********************/
/*
* Caching
*/
if(!function_exists('pdapp_cache'))
{
	function pdapp_cache($folder = '')
	{
		$path = PDAPP_PLUGIN_DIR .'cache';
		$newPath = $path;
		if(!is_dir($newPath))
		{
			if (!wp_mkdir_p($newPath))
			{
				return array('error'=> pdapp_lang('error_wriable_permission', 'system').' '. $newPath);
			}
		}

		if($folder != '')
		{
			$newPath = $newPath .'/'. $folder;
		}

		if(!is_dir($newPath))
		{
			if (!wp_mkdir_p($newPath))
			{
				return array('error'=> pdapp_lang('error_wriable_permission', 'system').' '. $newPath);
			}
		}
		
		require_once(PDAPP_PLUGIN_DIR .'includes/libraries/phpfastcache.php');
		PDAPP_PhpFastCache::pdapp_setup("storage", "files");
		PDAPP_PhpFastCache::pdapp_setup("path", $path);
		PDAPP_PhpFastCache::pdapp_setup("securityKey", $folder);
		$cache = pdapp_php_fast_cache();

		return $cache;
	}
}

/*
* Set cache
*/
if(!function_exists('pdapp_set_cache'))
{
	/*1 month = 2592000*/
	function pdapp_set_cache($folder = '', $file = '', $data=[], $time = 2592000)
	{
		$cache = pdapp_cache($folder);
		return $cache->pdapp_set($file, $data, $time);
	}
}

/*
* Get cache
*/
if(!function_exists('pdapp_get_cache'))
{
	function pdapp_get_cache($folder = '', $file = '')
	{
		$cache = pdapp_cache($folder);
		$result = $cache->pdapp_get($file);

		if($result != null && $result != '')
		{
			return $result;
		}else
		{
			return '';
		}
	}
}

/*
* Del cache
*/
if(!function_exists('pdapp_delete_cache'))
{
	function pdapp_delete_cache($folder = '', $file = '')
	{
		$cache = pdapp_cache($folder);
		return $cache->pdapp_delete($file);
	}
}

/*
* Update cache after remove folder
*/
if(!function_exists('pdapp_update_root_folders'))
{
	function pdapp_update_root_folders($pid=0, $folder="")
	{
		$db = PDAPP_DB_TEMPLATES;
		if($folder == 'arts')
		{
			$db = PDAPP_DB_ARTWORKS;
		}
		
		pdapp_update_db($db, ["pid"=>0], ["pid"=>$pid], ["%d"], ["%d"]);
		pdapp_delete_cache($folder, $folder. '-0');
		pdapp_delete_cache($folder, 'folders-0');
	}
}

/******************** Files ********************/
/*
* Upload
*/
if(!function_exists('pdapp_upload'))
{
	function pdapp_upload($key="", $path="", $allows = ['png', 'jpg', 'jpeg'], $filename = '', $mimes=null)
	{
		$res = array(
			'error'=>0,
			'message'=>'',
			'ext'=>''
		);
		if($key == "" || !isset($_FILES[$key]) || empty($_FILES[$key]["name"]))
		{
			$res['error'] = 1;
			$res['message'] = "Upload error!";
		}

		global $wp_filesystem;
		if(!is_dir($path))
		{
			if (!wp_mkdir_p($path)) 
			{
				$res['error'] = 1;
				$res['message'] = pdapp_lang('error_wriable_permission', 'system'). ' '. $path;
			}
		}
		
		$fileType = wp_check_filetype(sanitize_text_field(wp_unslash($_FILES[$key]['name'])), $mimes);
		if (!isset($fileType['ext']) || $fileType['ext'] == '')
		{
			$res['error'] = 1;
			$res['message'] = "Upload error!";
			return $res;
		}
		$ext = strtolower($fileType['ext']);
		if (in_array($ext, $allows))
		{
			if($mimes != null)
			{
				$fileUpload = wp_handle_upload($_FILES[$key], ['test_form' => false, 'test_type' => false, 'mimes' => $mimes]);
			}else
			{
				$fileUpload = wp_handle_upload($_FILES[$key], ['test_form' => false]);
			}
			
			if(isset($fileUpload['file']))
			{
				if($filename == '')
				{
					$filename = uniqid();
				}

				$filePath = $path .'/'. $filename.'.'.$ext;
				$wp_filesystem->move($fileUpload['file'], $filePath);

				$res['path'] = $filePath;
				$res['name'] = $filename;
				$res['filename'] = $filename.'.'.$ext;
				$res['ext'] = $ext;
			}else
			{
				$res['error'] = 1;
				$res['message'] = isset($fileUpload['error']) ? $fileUpload['error'] : "Upload error!";
			}
		}else
		{
			$res['error'] = 1;
			$res['message'] = pdapp_lang('upload_type_error', 'system'). ' '. $ext;
		}
		
		return $res;
	}
}

if(!function_exists('pdapp_upload_jsons'))
{
	function pdapp_upload_jsons($key="", $required_fields=[], $options=[])
	{
		$res = false;
		if($key != "" && isset($_FILES[$key]) && !empty($_FILES[$key]["name"]))
		{
			$fileUpload = wp_handle_upload($_FILES[$key], ['test_form' => false, 'test_type' => false, 'mimes' => ['json'=>'application/json']]);
			if(isset($fileUpload['file']))
			{
				$json = file_get_contents($fileUpload['file']);
				if($json)
				{
					$data = json_decode($json, true);

					$post = [];
					$langs = [];
					$check = false;
					foreach($required_fields as $key=>$type)
					{
						if(!isset($data[$key]))
						{
							$check = true;
							break;
						}
						
						if($type == 'lang' && count($langs) == 0)
						{
							$langs = pdapp_get_lang_available();
						}
						$post[$key] = pdapp_clean_data($type, $data[$key], $langs);
					}

					foreach($options as $k=>$v)
					{
						if(isset($data[$k]))
						{
							if($v == 'lang' && count($langs) == 0)
							{
								$langs = pdapp_get_lang_available();
							}
							$post[$k] = pdapp_clean_data($v, $data[$k], $langs);
						}else
						{
							$post[$k] = '';
						}
					}

					if($check)
					{
						$res = [];
					}

					$res = count($post) ? $post : false;
				}

				global $wp_filesystem;
				if(file_exists($fileUpload['file']))
				{
					$wp_filesystem->delete($fileUpload['file']);
				}
			}
		}
		
		return $res;
	}
}

/*
* Write file
*/
if(!function_exists('pdapp_write_file'))
{
	function pdapp_write_file($file="", $data="")
	{
		global $wp_filesystem;
		$paths = explode('/', $file);

		$repl = end($paths);
		$path = str_replace('//', '/', str_replace('/'.$repl, '', $file));
		
		if(!is_dir($path))
		{
			if (!wp_mkdir_p($path))
			{
				return false;
			}
		}
		
		return $wp_filesystem->put_contents($file, $data);
	}
}

/*
* Read file
*/
if(!function_exists('pdapp_read_file'))
{
	function pdapp_read_file($filepath="")
	{
		global $wp_filesystem;
		if(!file_exists($filepath))
		{
			return false;
		}

		return $wp_filesystem->get_contents($filepath);
	}
}

/*
* Delete file
*/
if(!function_exists('pdapp_delete_file'))
{
	function pdapp_delete_file($filePath="")
	{
		global $wp_filesystem;
		if(file_exists($filePath))
		{
			return $wp_filesystem->delete($filePath);
		}

		return false;
	}
}

/*
* Copy files
*/
if(!function_exists('pdapp_copy_files'))
{
	function pdapp_copy_files($from="", $to="")
	{
		if(is_dir($from))
		{
			if(!is_dir($to))
			{
				if (!wp_mkdir_p($to))
				{
					return false;
				}
			}

			$files = pdapp_files_folder($from, false);
			foreach($files as $file)
			{
				$path1 = $from .'/'. $file;
				$path2 = $to .'/'. $file;
				pdapp_copy_files($path1, $path2);
			}
		}elseif(file_exists($from) && !file_exists($to))
		{
			copy($from, $to);
		}

		return true;
	}
}

/*
* Move files
*/
if(!function_exists('pdapp_move_files'))
{
	function pdapp_move_files($from="", $to="")
	{
		global $wp_filesystem;
		if(!is_dir($to))
		{
			if (!wp_mkdir_p($to))
			{
				return false;
			}
		}
		
		$files = pdapp_files_folder($from, false);
		foreach($files as $file)
		{
			$path1 = $from .'/'. $file;
			$path2 = $to .'/'. $file;
			if (is_dir($path1))
			{
				pdapp_move_files($path1, $path2);
			}else
			{
				$wp_filesystem->move($path1, $path2);
			}
		}

		pdapp_delete_dir($from);
		return true;
	}
}

/*
* Write image base64
*/
if(!function_exists('pdapp_write_image'))
{
	function pdapp_write_image($folder="", $img="", $name='')
	{
		if($img == '') return '';

		if(strpos($img, ';base64,') === false)
		{
			return $img;
		}
		$imgs = explode(';base64,', $img);
		if(isset($imgs[1]))
		{
			if($name == '')
			{
				$name = 'img-'. uniqid() .'.png';
			}
			$file = $name;
			$data = base64_decode($imgs[1]);
			$path = $folder. '/' .$file;
			if(pdapp_write_file(PDAPP_UPLOAD_DIR . $path, $data))
			{
				return $file;
			}
		}

		return '';
	}
}

/*
* Write pda template
*/
if(!function_exists('pdapp_write_pda'))
{
	function pdapp_write_pda($folder="", $img="", $name='')
	{
		if($img == '') return '';

		if($name == '')
		{
			$name = 'img-'. uniqid() .'.svg';
		}
		$path = $folder. '/' .$name;

		if(strpos($img, 'image/svg+xml;base64,') === false)
		{
			if(pdapp_write_file(PDAPP_UPLOAD_DIR . $path, $img))
			{
				return $name;
			}
		}else
		{
			$imgs = explode('data:image/svg+xml;base64,', $img);
			if(isset($imgs[1]))
			{
				
				$data = base64_decode($imgs[1]);
				if(pdapp_write_file(PDAPP_UPLOAD_DIR . $path, $data))
				{
					return $name;
				}
			}
		}

		return '';
	}
}

/*
* Delete dir
*/
if(!function_exists('pdapp_delete_dir'))
{
	function pdapp_delete_dir($dirPath="")
	{
		global $wp_filesystem;
		
		if(is_dir($dirPath))
		{
			return $wp_filesystem->delete($dirPath, true);
		}
		
		return false;
	}
}

/*
* List folders
*/
if(!function_exists('pdapp_list_folders'))
{
	function pdapp_list_folders($dir="")
	{
		$dirs = [];

		if (is_dir($dir))
		{
			$dirs = array_filter(glob($dir .'/*'), 'is_dir');
		}

		return $dirs;
	}
}

/*
* List files
*/
if(!function_exists('pdapp_files_folder'))
{
	function pdapp_files_folder($dir="", $file_only = true)
	{
		$files = [];

		if (is_dir($dir))
		{
			if(!is_readable($dir))
			{
				chmod($dir, 0755);
			}
			$items = scandir($dir);
			foreach($items as $item)
			{
				if ($item != "." && $item != ".." && $item != ".DS_Store")
				{
					if($file_only && strpos($item, '.') === false)
					{
						continue;
					}
					$files[] = $item;
				}
			}
		}

		return $files;
	}
}

/******************** Unzip ********************/
/*
* Unzip file
*/
if(!function_exists('pdapp_unzip'))
{
	function pdapp_unzip($zip_file="", $extract_path="")
	{
		if(!function_exists('unzip_file'))
		{
			require_once(ABSPATH . 'wp-admin/includes/file.php');
		}

		$result = unzip_file($zip_file, $extract_path);

		if (is_wp_error($result))
		{
			/*$result->get_error_message();*/
			return false;
		}else
		{
			return true;
		}
	}
}

/*
* Remote - get URL
*/
if(!function_exists('pdapp_open_url'))
{
	function pdapp_open_url($url="", $type = 'application/json')
	{
		$data = false;
		$response = wp_remote_get($url, ['headers' => ['Accept' => 'application/json']]);

		if(is_array($response) && !is_wp_error($response))
		{
			$data = $response['body'];
		}

		return $data;
	}
}

/******************* Fonts *********************/
/*
* List font
*/
if(!function_exists('pdapp_get_list_fonts'))
{
	function pdapp_get_list_fonts()
	{
		$listFonts = pdapp_get_cache('fonts', 'list_fonts');
		if(!$listFonts)
		{
			global $wpdb;
			$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='lf'", PDAPP_DB_SETTINGS), ARRAY_A);
			if(isset($res['values']))
			{
				$listFonts = json_decode($res['values'], true);
				pdapp_set_cache('fonts', 'list_fonts', $listFonts);
			}
		}

		if(!$listFonts)
		{
			$listFonts = [];
		}

		return $listFonts;
	}
}

/*
* Font info
*/
if(!function_exists('pdapp_decode_font'))
{
	function pdapp_decode_font($dec="")
	{
		return str_repeat('0', 2-strlen(($hex=strtoupper(dechex(ord($dec)))))) . $hex;
	}
}

if(!function_exists('pdapp_read_font_name'))
{
	function pdapp_read_font_name($file="")
	{
		$res = ["title"=>'', "variant"=>''];
		$font = pdapp_read_file($file);
		if(!isset($font[4]) || !isset($font[5]))
		{
			return $res;
		}
		
		$pdappOffset = 0;
		$pdappOffsetStorage = 0;
		$pdappTables = hexdec(pdapp_decode_font($font[4]).pdapp_decode_font($font[5]));
		for ($i=0; $i<$pdappTables; $i++)
		{
			$tag = isset($font[12+$i*16]) && isset($font[12+$i*16+1]) && isset($font[12+$i*16+2]) && isset($font[12+$i*16+3]) ? $font[12+$i*16] . $font[12+$i*16+1] . $font[12+$i*16+2] . $font[12+$i*16+3] : '';
			if ($tag == 'name')
			{
				if(isset($font[12+$i*16+8]) && isset($font[12+$i*16+8+1]) && isset($font[12+$i*16+8+2]) && isset($font[12+$i*16+8+3]))
				{
					$pdappOffset = hexdec(pdapp_decode_font($font[12+$i*16+8]) . pdapp_decode_font($font[12+$i*16+8+1]) . pdapp_decode_font($font[12+$i*16+8+2]) . pdapp_decode_font($font[12+$i*16+8+3]));
					$pdappOffsetStorage = isset($font[$pdappOffset+4]) && isset($font[$pdappOffset+5]) ? hexdec(pdapp_decode_font($font[$pdappOffset+4]) . pdapp_decode_font($font[$pdappOffset+5])) : 0;
				}
			}
		}
		
		$storage_dec = $pdappOffsetStorage + $pdappOffset;
		
		for($j=1; $j<3; $j++)
		{
			if(isset($font[$pdappOffset+6+$j*12+8]) && isset($font[$pdappOffset+6+$j*12+9]) && isset($font[$pdappOffset+6+$j*12+10]) && isset($font[$pdappOffset+6+$j*12+11]))
			{
				$string_length_dec    = hexdec(pdapp_decode_font($font[$pdappOffset+6+$j*12+8]) . pdapp_decode_font($font[$pdappOffset+6+$j*12+9]));
				$string_offset_dec    = hexdec(pdapp_decode_font($font[$pdappOffset+6+$j*12+10]) . pdapp_decode_font($font[$pdappOffset+6+$j*12+11]));

				for($l=0; $l<$string_length_dec; $l++)
				{
					if(isset($font[$storage_dec+$string_offset_dec+$l]) && ord($font[$storage_dec+$string_offset_dec+$l]) == '0')
					{
						continue;
					}else if(isset($font[$storage_dec+$string_offset_dec+$l]))
					{
						if($j==1)
						{
							$res['title'] .= $font[$storage_dec+$string_offset_dec+$l];
						}else
						{
							$res['variant'] .= $font[$storage_dec+$string_offset_dec+$l];
						}
					}
				}
			}
		}
		
		return $res;
	}
}

/******************* Languages *********************/
/*
* Lang code
*/
if(!function_exists('pdapp_lang_code'))
{
	function pdapp_lang_code()
	{
		return get_locale();
	}
}

/*
* Languages Avaialble
*/
if(!function_exists('pdapp_get_lang_available'))
{
	function pdapp_get_lang_available()
	{
		$code = pdapp_lang_code();
		$language = [];
		
		$list = get_available_languages();
		if(!in_array($code, $list))
		{
			$list[] = $code;
		}
		
		$listLangs = pdapp_get_available_translations();
		if(!isset($listLangs['en_US']))
		{
			$listLangs['en_US'] = "English";
		}

		foreach($list as $langKey)
		{
			if(isset($listLangs[$langKey]))
			{
				$language[$langKey] = $listLangs[$langKey] .'-'. $langKey;
			}else
			{
				$language[$langKey] = $langKey;
			}
		}

		return $language;
	}
}

/*
* get languages Avaialble
*/
if(!function_exists('pdapp_get_available_translations'))
{
	function pdapp_get_available_translations()
	{
		$languages = pdapp_get_cache('settings', 'langs');
		if(!$languages)
        {
			$languages = [];
			$response = wp_remote_get('https://api.wordpress.org/translations/core/1.0/');

			if(is_array($response) && !is_wp_error($response))
			{
				$body = wp_remote_retrieve_body($response);
				$translations = json_decode($body, true);

				if(isset($translations['translations']))
				{
					foreach($translations['translations'] as $lang)
					{
						$languages[$lang['language']] = $lang['native_name'];
					}
					
					pdapp_set_cache('settings', 'langs', $languages);
				}
			}
		}

		return $languages;
	}
}

/*
* Languages by code
*/
if(!function_exists('pdapp_get_lang_by_code'))
{
	function pdapp_get_lang_by_code($code = 'en_US', $file = 'front')
	{
		$langs = [];
		$folder = PDAPP_PLUGIN_DIR .'languages';

		$pathLang = $folder .'/'.$file.'.json';
		$lang = pdapp_read_file($pathLang);
		if($lang)
		{
			$langs = json_decode($lang, true);
		}

		$folder = PDAPP_PLUGIN_DIR .'languages/'. $code;
		if(is_dir($folder) && file_exists($folder .'/'.$file.'.json'))
		{
			$updateLang = pdapp_read_file($folder .'/'.$file.'.json');
			if($updateLang)
			{
				$updateLangs = json_decode($updateLang, true);
				foreach($updateLangs as $k=>$v)
				{
					if(isset($langs[$k]) && is_array($v))
					{
						foreach($v as $kk=>$vv)
						{
							$langs[$k][$kk] = $vv;
						}
					}else
					{
						$langs[$k] = $v;
					}
				}
			}
		}

		return $langs;
	}
}

/*
* Languages
*/
if(!function_exists('pdapp_languages'))
{
	function pdapp_languages($file = 'front')
	{
		$code = pdapp_lang_code();

		return pdapp_get_lang_by_code($code, $file);
	}
}

/*
* Lang
*/
if(!function_exists('pdapp_lang'))
{
	function pdapp_lang($key = '', $file = 'front', $langs = [])
	{
		$lang = $key;
		if(count((array) $langs) == 0)
		{
			$langs = pdapp_languages($file);
		}

		$keys = explode('.', $key);
		foreach($keys as $val)
		{
			if($val == '')
			{
				continue;
			}
			if(isset($langs[$val]))
			{
				$lang = $langs[$val];
			}else if(isset($lang[$val]))
			{
				$lang = $lang[$val];
			}
		}

		return $lang;
	}
}

/******************* Functions *********************/
/*
* get List Font Size
*/
if(!function_exists('pdapp_get_font_size'))
{
	function pdapp_get_font_size()
	{
		$fontsize = [];
		for($j=0; $j<48; $j++)
		{
			$fontsize[] = $j*2 + 6;
		}

		return $fontsize;
	}
}

/*
* Product
* Upload product images
*/
if(!function_exists('pdapp_upload_views'))
{
	function pdapp_upload_views($views = [], $id=0)
	{
		foreach($views as $key=>$val)
		{
			foreach($val['backgrounds'] as $k=>$v)
			{
				if(isset($v['image']) && $v['image'] != '')
				{
					$views[$key]['backgrounds'][$k]['image'] = pdapp_write_image('products/product-'. $id, $v['image']);
				}
				if(isset($v['images']))
				{
					foreach($v['images'] as $i=>$j)
					{
						$views[$key]['backgrounds'][$k]['images'][$i] = pdapp_write_image('products/product-'. $id, $j);
					}
				}
			}

			foreach($val['layers'] as $k=>$v)
			{
				if(isset($v['mask']) && $v['mask'] != '')
				{
					$views[$key]['layers'][$k]['mask'] = pdapp_write_image('products/product-'. $id, $v['mask']);
				}
			}

			if(isset($val['mask']) && isset($val['mask']['image']) && $val['mask']['image'] != '')
			{
				$views[$key]['mask']['image'] = pdapp_write_image('products/product-'. $id, $val['mask']['image']);
			}
		}

		return $views;
	}
}

/*
* Design
* Upload design images
*/
if(!function_exists('pdapp_save_designs'))
{
	function pdapp_save_designs($designs = [], $id=0)
	{
		$res = [];

		foreach($designs as $key=>$design)
		{
			foreach($design as $k=>$val)
			{
				$val['svg'] = pdapp_replace_image_svg($val['svg']);
				pdapp_write_file(PDAPP_UPLOAD_DIR .'designs/d'. $id .'/'. $key.'-'.$k.'-'. md5(PDAPP_PREFIX . $id) .'.pda', $val['svg']);
				$res[] = $key.'-'.$k;
			}
		}

		return $res;
	}
}

/*
* checkPostFields
*/
if(!function_exists('pdapp_post_fields'))
{
	function pdapp_post_fields($fields = [])
	{
		$post = [];
		foreach($fields as $key=>$type)
		{
			$field = pdapp_post($key, $type);
			if($field === false)
			{
				$post = [];
				break;
			}

			$post[$key] = $field;
		}

		return count($post) ? $post : false;
	}
}

/*
* merge Values
*/
if(!function_exists('pdapp_merge_value'))
{
	function pdapp_merge_value($values="", $newValues = [])
	{
		foreach ($newValues as $key=>$val)
		{
			$values[$key] = $val;
		}

		return $values;
	}
}

/*
* get Art Folders
*/
if(!function_exists('pdapp_get_art_folders'))
{
	function pdapp_get_art_folders()
	{
		$folders = pdapp_get_cache('arts', 'folders');
		if(!$folders)
		{
			$folders = [];
			global $wpdb;
			$res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `type`='f'", PDAPP_DB_ARTWORKS), ARRAY_A);

			usort($res, function ($a, $b)
			{
				$arrA = json_decode($a['title'], true);
				$arrB = json_decode($b['title'], true);
				$newA = isset($arrA['en_US']) ? $arrA['en_US'] : current($arrA);
				$newB = isset($arrB['en_US']) ? $arrB['en_US'] : current($arrB);
				return strcmp($newA, $newB);
			});

			foreach($res as $val)
			{
				if(!isset($folders[$val['pid']]))
				{
					$folders[$val['pid']] = [];
				}
				if(isset($folders[$val['pid']]))
				{
					$folders[$val['pid']][] = ["id"=>$val["id"], "pid"=>$val["pid"], "title"=>json_decode($val["title"], true), "filetype"=>$val["filetype"], "thumb"=>$val["thumb"], "created"=>$val["created"]];
				}
			}
			pdapp_set_cache('arts', 'folders', $folders);
		}

		return $folders;
	}
}

/*
* get Temp Folders
*/
if(!function_exists('pdapp_get_template_folders'))
{
	function pdapp_get_template_folders()
	{
		$folders = pdapp_get_cache('templates', 'folders');
		if(!$folders)
		{
			$folders = [];
			global $wpdb;
			$res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `type`='f'", PDAPP_DB_TEMPLATES), ARRAY_A);

			usort($res, function ($a, $b)
			{
				$arrA = json_decode($a['title'], true);
				$arrB = json_decode($b['title'], true);
				$newA = isset($arrA['en_US']) ? $arrA['en_US'] : current($arrA);
				$newB = isset($arrB['en_US']) ? $arrB['en_US'] : current($arrB);
				return strcmp($newA, $newB);
			});

			foreach($res as $val)
			{
				if(!isset($folders[$val['pid']]))
				{
					$folders[$val['pid']] = [];
				}
				if(isset($folders[$val['pid']]))
				{
					$folders[$val['pid']][] = ["id"=>$val["id"], "pid"=>$val["pid"], "title"=>json_decode($val["title"], true), "thumb"=>$val["thumb"], "created"=>$val["created"]];
				}
			}
			pdapp_set_cache('templates', 'folders', $folders);
		}

		return $folders;
	}
}

/*
* get Template
*/
if(!function_exists('pdapp_get_template'))
{
	function pdapp_get_template($designs=[])
	{
		$res = [];
		foreach($designs as $v=>$view)
		{
			if(!isset($res[$v]))
			{
				$res[$v] = [];
			}
			foreach($view as $l=>$layer)
			{
				if(isset($layer['id']) && $layer['id'] != 0)
				{
					$tempID = $layer['id'];
					$file = PDAPP_UPLOAD_DIR .'templates/template-'. md5(PDAPP_PREFIX . $tempID) .'.pda';
					$res[$v][$l] = pdapp_read_file($file);
				}else
				{
					$res[$v][$l] = '';
				}
			}
		}

		return $res;
	}
}

/*
* get User Key
*/
if(!function_exists('pdapp_get_user_key'))
{
	function pdapp_get_user_key()
	{
		$key = pdapp_get_cache('settings', 'key');
		if(!$key)
		{
			global $wpdb;
			$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='k'", PDAPP_DB_SETTINGS), ARRAY_A);
			if(isset($res['values']))
			{
				$key = $res['values'];
				pdapp_set_cache('settings', 'key', $key);
			}
		}

		return $key;
	}
}

/*
* get Theme Active
*/
if(!function_exists('pdapp_get_theme'))
{
	function pdapp_get_theme()
	{
		$theme = pdapp_get_cache('settings', 'theme');
		if(!$theme)
		{
			global $wpdb;
			$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='t'", PDAPP_DB_SETTINGS), ARRAY_A);
			if(isset($res['values']))
			{
				$theme = $res['values'];
				pdapp_set_cache('settings', 'theme', $theme);
			}
		}
		
		return $theme;
	}
}

/*
* Settings
*/
if(!function_exists('pdapp_get_settings'))
{
	function pdapp_get_settings($general = false, $layout = false, $text = false, $font = false, $shape = false, $filter = false)
	{
		global $wpdb;
		$settings = ["general"=>[], "layout"=>[], "text"=>[], "font"=>[], "shape"=>[], "filter"=>[]];
		
		if($general)
		{
			$general = pdapp_get_cache('settings', 'setting_general');
			if(!$general)
			{
				$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='sg'", PDAPP_DB_SETTINGS), ARRAY_A);
				if(isset($res['values']))
				{
					$general = json_decode($res['values'], true);
					pdapp_set_cache('settings', 'setting_general', $general);
				}
			}
			if(isset($general['upload']) && isset($general['upload']['type']))
			{
				if(in_array('jpg', $general['upload']['type']) && !in_array('jpeg', $general['upload']['type']))
				{
					$general['upload']['type'][] = 'jpeg';
				}
				
				if(!isset($general['upload']['dpi']))
				{
					$general['upload']['dpi'] = false;
				}
			}
			$settings['general'] = $general;
		}
		
		if($layout)
		{
			$layout = pdapp_get_cache('settings', 'setting_layout');
			if(!$layout)
			{
				$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='sl'", PDAPP_DB_SETTINGS), ARRAY_A);
				if(isset($res['values']))
				{
					$layout = json_decode($res['values'], true);
					pdapp_set_cache('settings', 'setting_layout', $layout);
				}
			}
			$settings['layout'] = $layout;
		}
		
		if($text)
		{
			$text = pdapp_get_cache('settings', 'setting_text');
			if(!$text)
			{
				$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='st'", PDAPP_DB_SETTINGS), ARRAY_A);
				if(isset($res['values']))
				{
					$text = json_decode($res['values'], true);
					pdapp_set_cache('settings', 'setting_text', $text);
				}
			}
			$settings['text'] = $text;
		}

		if($font)
		{
			$font = pdapp_get_cache('settings', 'setting_font');
			if(!$font)
			{
				$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='tf'", PDAPP_DB_SETTINGS), ARRAY_A);
				if(isset($res['values']))
				{
					$font = json_decode($res['values'], true);
					pdapp_set_cache('settings', 'setting_font', $font);
				}
			}

			$settings['font'] = $font;
		}
		
		if($shape)
		{
			$shape = pdapp_get_cache('settings', 'setting_shape');
			if(!$shape)
			{
				$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='ss'", PDAPP_DB_SETTINGS), ARRAY_A);
				if(isset($res['values']))
				{
					$shape = json_decode($res['values'], true);
					pdapp_set_cache('settings', 'setting_shape', $shape);
				}
			}
			$settings['shape'] = $shape;
		}
		
		if($filter)
		{
			$filter = pdapp_get_cache('settings', 'setting_filter');
			if(!$filter)
			{
				$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='sf'", PDAPP_DB_SETTINGS), ARRAY_A);
				if(isset($res['values']))
				{
					$filter = json_decode($res['values'], true);
					pdapp_set_cache('settings', 'setting_filter', $filter);
				}
			}
			$settings['filter'] = $filter;
		}

		return $settings;
	}
}

if(!function_exists('pdapp_get_product'))
{
	function pdapp_get_product($id=0)
	{
		$product = pdapp_get_cache('products', 'product-'. $id);
		if(!$product)
		{
			global $wpdb;
			$product = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_PRODUCTS, $id]), ARRAY_A);
			if(!isset($product['id']))
			{
				return [];
			}
			
			$value = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_VALUES, $product['vid']]), ARRAY_A);

			if(!isset($value['values']))
			{
				return [];
			}
			$value['values'] = json_decode($value['values'], true);

			$product = pdapp_merge_value($product, $value['values']);
			pdapp_set_cache('products', 'product-'. $id, $product);
		}

		if(isset($product['views']))
		{
			foreach($product['views'] as $key=>$view)
			{
				if(isset($view['backgrounds']))
				{
					foreach($view['backgrounds'] as $k=>$background)
					{
						if(!isset($background['colorType']))
						{
							$product['views'][$key]['backgrounds'][$k]['colorType'] = 'color';
						}
						if(!isset($background['images']))
						{
							$product['views'][$key]['backgrounds'][$k]['images'] = [];
						}
					}
				}
			}
		}

		return $product;
	}
}

if(!function_exists('pdapp_woo_get_product'))
{
	function pdapp_woo_get_product($field=[], $key = '')
	{
		$postID = isset($field['pid']) ? $field['pid'] : 0;

		$design = pdapp_get_cache('woos', 'product-'. $postID);

		if(!$design)
		{
			global $wpdb;
			$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `pid`=%d", [PDAPP_DB_WOO_PRODUCTS, $field['pid']]), ARRAY_A);
			if(isset($row['id']))
			{
				$design = ["id"=>$row['id'], "pid"=>$row['pid'], "did"=>$row['did'], "vid"=>$row['vid'], "title"=>$row['title'], "thumb"=>$row['thumb'], "values"=>json_decode($row['values'], true)];
				pdapp_set_cache('woos', 'product-'. $postID, $design);
			}
		}

		if($key != '' && isset($design[$key]))
		{
			return $design[$key];
		}

		return $design;
	}
}

if(!function_exists('pdapp_woo_save_product'))
{
	function pdapp_woo_save_product($field=[], $data=[])
	{
		$postID = isset($field['pid']) ? $field['pid'] : 0;

		$updateData = ["pid"=>$data['pid'], "did"=>$data['did'], "vid"=>$data['vid'], "title"=>trim($data['title'], '"'), "thumb"=>$data['thumb'], "values"=>pdapp_json_encode($data['values'])];
		if($data['id'] != 0)
		{
			pdapp_update_db(PDAPP_DB_WOO_PRODUCTS, $updateData, ["id"=>$data['id']], ["%d", "%d", "%d", "%s", "%s", "%s"], ["%d"]);
		}else
		{
			$data['id'] = pdapp_insert_db(PDAPP_DB_WOO_PRODUCTS, $updateData, ["%d", "%d", "%d", "%s", "%s", "%s"]);
		}

		if($data['id'] != 0)
		{
			pdapp_set_cache('woos', 'product-'. $postID, $data);
			pdapp_delete_cache('woos', 'products-'. $data['did']);
			return $data['id'];
		}else
		{
			return false;
		}
	}
}

if(!function_exists('pdapp_get_page_studio'))
{
	function pdapp_get_page_studio()
	{
		$studio = pdapp_get_cache('woos', 'studio_page');
		if(!$studio)
		{
			global $wpdb;
			$studio = $wpdb->get_var($wpdb->prepare("SELECT ID FROM %i WHERE post_content LIKE %s AND post_status='publish'", [$wpdb->posts, '%[pdapp-studio-page%']));
			pdapp_set_cache('woos', 'studio_page', $studio, 60);
		}
		
		return $studio;
	}
}

/******************* Cart *********************/
/*
* add to quote
*/
if(!function_exists('pdapp_add_to_quote'))
{
	function pdapp_add_to_quote($item=[], $qID=0, $productID=0, $designID=0, $print=[], $team=[], $phone='', $email='', $note='', $files=[], $price=0, $itemQty=0, $folder="")
	{
		return false;
	}
}

/*
* add to cart
*/
if(!function_exists('pdapp_add_cart'))
{
	function pdapp_add_cart($item=[], $productID=0, $designID=0, $print=[], $team=[], $note='', $files=[], $price=0, $regular_price=0, $itemQty=0, $folder="")
	{
		global $woocommerce;
		$options = [];

		foreach($item['options'] as $option)
		{
			$opts = explode(': ', $option);
			if(isset($opts[1]))
			{
				$options[$opts[0]] = $opts[1];
			}
		}

		$sizeLang = count($item['sizes']) > 1 ? pdapp_lang('sizes', 'system') : pdapp_lang('quantity', 'system');
		$quanty = [];
		$qtyAttr = [];
		$sizes = [];
		if(count($team) == 0)
		{
			$itemQty = 0;
			foreach($item['sizes'] as $size)
			{
				$itemQty = $itemQty + (int) $size['value'];
				$quanty[] = count($item['sizes']) > 1 ? $size['title'] . '-' . (int) $size['value'] : (int) $size['value'];
				if((int) $size['value'] > 0)
				{
					$qtyAttr[$size['key']] = (int) $size['value'];
					$sizes[] = (int) $size['value'];
				}
			}
		}else
		{
			$sizeLang = pdapp_lang('teams', 'system');
			foreach($team as $t)
			{
				if(isset($t['size']) && isset($t['size']['size']) && isset($item['sizes'][$t['size']['size']]))
				{
					$size = $item['sizes'][$t['size']['size']];
					$name = isset($t['name']) && $t['name'] != '' ? $t['name'] : '';
					$number = isset($t['number']) && $t['number'] != '' ? $t['number'] : '';
					$teamName = ($name != '' && $number != '') ? $name .'/'. $number : $name . $number;
					
					$quanty[] = count($item['sizes']) > 1 ? $teamName .': '. $size['title'] . '-' . (int) $t['size']['qty'] : (int) $t['size']['qty'];

					if((int) $t['size']['qty'] > 0)
					{
						$qtyAttr[$size['key']] = isset($qtyAttr[$size['key']]) ? $qtyAttr[$size['key']] + (int) $t['size']['qty'] : (int) $t['size']['qty'];
						$sizes[] = (int) $t['size']['qty'];
					}
				}
			}
		}

		$options[$sizeLang] = implode(', ', $quanty);

		$thumbs = [];
		foreach($item['thumb'] as $thumb)
		{
			$thumb = pdapp_write_image('/carts/' .$folder. '/thumb', $thumb);
			$thumbs[] = $thumb;
		}

		if ( !$woocommerce->session )
		{
			$woocommerce->session = new WC_Session_Handler();
			$woocommerce->session->init();
		}

		if ( !$woocommerce->customer )
		{
			$woocommerce->customer = new WC_Customer( get_current_user_id(), true );
		}

		if ( !$woocommerce->cart )
		{
			$woocommerce->cart = new WC_Cart();
		}

		$otps = [
			"color"=>$item['color'],
			"extra"=>$item['extra'],
			"sizes"=>$sizes
		];

		$woocommerce->cart->add_to_cart(
			$productID,
			$itemQty,
			0,
			[],
			[
				"pdappDesign"=>[
					"designID"=>$designID,
					"options"=>$options,
					"price"=>$price,
					"regular_price"=>$regular_price,
					"print"=>$print,
					"file"=>$files,
					"thumb"=>$thumbs,
					"team"=>$team,
					"folder"=>$folder,
					"attrs"=>$qtyAttr,
					"otps"=>$otps,
					"note"=>$note
				]
			]
		);
	}
}

/*
* add to cart
*/
if(!function_exists('pdapp_get_cart_item'))
{
	function pdapp_get_cart_item($cart_item_key)
	{
		$cart = WC()->cart ? WC()->cart->get_cart() : [];

		if(isset($cart[$cart_item_key]))
		{
			return $cart[$cart_item_key];
		}

		return false;
	}
}

/*
* Order
* Add order
*/
if(!function_exists('pdapp_save_woo_order'))
{
	function pdapp_save_woo_order($orderID=0, $data=[])
	{
		$data['email'] = sanitize_email($data['email']);
		$updateData = ["oid"=>$data['oid'], "phone"=>$data['phone'], "email"=>$data['email'], "type"=>$data['type'], "status"=>$data['status'], "thumb"=>pdapp_json_encode($data['thumb']), "created"=>$data['created']];
		
		$cacheFolder = $data['type'] == 'o' ? 'order' : 'quote';
		$cacheFile = $data['type'] == 'o' ? 'new-orders' : 'new-quotes';
		if($orderID != 0)
		{
			pdapp_update_db(PDAPP_DB_ORDERS, $updateData, ["id"=>$orderID], ["%d", "%s", "%s", "%s", "%s", "%s", "%s"], ["%d"]);
		}else
		{
			$orderID = pdapp_insert_db(PDAPP_DB_ORDERS, $updateData, ["%d", "%s", "%s", "%s", "%s", "%s", "%s"]);

			$orders = pdapp_get_cache($cacheFolder. 's', $cacheFile);
			if(!$orders)
			{
				$orders = [];
			}
			$orders[] = $orderID;
			pdapp_set_cache($cacheFolder. 's', $cacheFile, $orders);
		}

		if($orderID != 0)
		{
			$data["id"] = $orderID;
			pdapp_set_cache('woos', $cacheFolder. '-'. $data['oid'], $data);
			pdapp_delete_cache($cacheFolder. 's', 'lists');
			
			return $orderID;
		}else
		{
			return false;
		}
	}
}

/*
* save Order Item
*/
if(!function_exists('pdapp_save_order_item'))
{
	function pdapp_save_order_item($type="", $data=[])
	{
		$itemID = pdapp_insert_db(PDAPP_DB_ORDER_DETAIL, $data, ["%d", "%d", "%s", "%f", "%d", "%s", "%s", "%s", "%s", "%s", "%s", "%s"]);
		$orderID = $data['oid'];
		if($itemID != 0)
		{
			$cacheData = pdapp_get_cache($type. 's', $type. '-'. $orderID);
			if(!$cacheData)
			{
				$cacheData = [];
				global $wpdb;
				$res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `oid`=%d", [PDAPP_DB_ORDER_DETAIL, $orderID]), ARRAY_A);
				foreach($res as $row)
				{
					$cacheData[] = ["id"=>$row['id'], "oid"=>$row['oid'], "did"=>$row['did'], "product"=>json_decode($row['product'], true), "price"=>$row['price'], "folder"=>$row['folder'], "qty"=>$row['qty'], "print"=>json_decode($row['print'], true), "options"=>json_decode($row['options'], true), "file"=>json_decode($row['file'], true), "team"=>json_decode($row['team'], true), "thumb"=>json_decode($row['thumb'], true), "note"=>$row['note']];
				}
			}else
			{
				$row = $data;
				$row['id'] = $itemID;
				$cacheData[] = ["id"=>$row['id'], "oid"=>$row['oid'], "did"=>$row['did'], "product"=>json_decode($row['product'], true), "price"=>$row['price'], "folder"=>$row['folder'], "qty"=>$row['qty'], "print"=>json_decode($row['print'], true), "options"=>json_decode($row['options'], true), "file"=>json_decode($row['file'], true), "team"=>json_decode($row['team'], true), "thumb"=>json_decode($row['thumb'], true), "note"=>$row['note']];
			}
			pdapp_set_cache($type. 's', $type. '-'. $orderID, $cacheData);

			return $itemID;
		}else
		{
			return false;
		}
	}
}

/*
* remove Order Item
*/
if(!function_exists('pdapp_remove_order_item'))
{
	function pdapp_remove_order_item($orderID=0, $detailID=0, $folder="", $thumb=[])
	{
		$del = pdapp_delete_db(PDAPP_DB_ORDER_DETAIL, ["id"=>$detailID, "oid"=>$orderID], ["%d", "%d"]);
		if($del)
		{
			pdapp_delete_cache('orders', 'order-'. $orderID);

			$orderDesign = pdapp_get_woo_order('order', $orderID);
			$thumbnail = isset($thumb[0]) ? $thumb[0] : '';
			if(isset($orderDesign['id']))
			{
				$newThumbs = [];
				foreach($orderDesign['thumb'] as $t)
				{
					if(strpos($t, $thumbnail) == false)
					{
						$newThumbs[] = $t;
					}
				}
				$orderDesign['thumb'] = $newThumbs;
				pdapp_save_woo_order($orderID, $orderDesign);
			}

			pdapp_delete_dir(PDAPP_UPLOAD_DIR .'orders/' .$folder);
		}
	}
}

/*
* remove Order
*/
if(!function_exists('pdapp_remove_order'))
{
	function pdapp_remove_order($orderID=0)
	{
		$orderDesign = pdapp_get_woo_order('order', $orderID);
		if(isset($orderDesign['id']))
		{
			$del = pdapp_delete_db(PDAPP_DB_ORDERS, ["id"=>$orderDesign['id']], ["%d"]);
			if($del)
			{
				pdapp_delete_cache('orders', 'order-'. $orderDesign['id']);
				pdapp_delete_cache('woos', 'order-'. $orderID);
				pdapp_delete_cache('orders', 'lists');
				pdapp_delete_db(PDAPP_DB_ORDER_DETAIL, ["oid"=>$orderDesign['id']], ["%d"]);

				foreach($orderDesign['thumb'] as $thumb)
				{
					$thumb1 = explode('/thumb/', $thumb);
					if(isset($thumb1[1]))
					{
						pdapp_delete_dir(PDAPP_UPLOAD_DIR .'orders/' .$thumb1[0]);
					}
				}
			}
		}
	}
}

/*
* get Order
*/
if(!function_exists('pdapp_get_woo_order'))
{
	function pdapp_get_woo_order($type="", $orderID=0)
	{
		$order = pdapp_get_cache('woos', $type .'-'. $orderID);

		if(!$order)
		{
			global $wpdb;
			$row = $wpdb->get_row($wpdb->prepare("SELECT `id`, `oid`, `thumb`, `created` FROM %i WHERE `oid`=%d", [PDAPP_DB_ORDERS, $orderID]), ARRAY_A);
			if(isset($row['id']))
			{
				$order = $row;
				$order['thumb'] = json_decode($order['thumb'], true);
				pdapp_set_cache('woos', $type .'-'. $orderID, $order);
				pdapp_delete_cache($type .'s', 'lists');
			}
		}

		return $order;
	}
}

/*
* add Order
*/
if(!function_exists('pdapp_add_woo_order'))
{
	function pdapp_add_woo_order($orderStatus, $order, $pdappDesign, $item_id, $order_id)
	{
		$orderID = 0;
		$folder = $pdappDesign['folder'];
		$thumbnail = '';
		$orderDesign = pdapp_get_woo_order('order', $order_id);
		if(isset($orderDesign['id']))
		{
			$orderID = $orderDesign['id'];
			if(isset($pdappDesign['thumb'][0]))
			{
				$orderDesign['thumb'][] = $folder .'/thumb/'. $pdappDesign['thumb'][0];
				$thumbnail = PDAPP_UPLOAD_URL .'carts/'. $folder .'/thumb/'. $pdappDesign['thumb'][0];
			}
		}else
		{
			$thumb = isset($pdappDesign['thumb'][0]) ? $pdappDesign['thumb'][0] : '';
			if(isset($pdappDesign['thumb'][0]))
			{
				$thumbnail = PDAPP_UPLOAD_URL .'carts/'. $folder .'/thumb/'. $pdappDesign['thumb'][0];
			}
			$thumbs = [];
			$thumbs[] = $folder .'/thumb/'. $thumb;
			$orderDesign = [
				"oid"=>$order_id,
				"status"=>$orderStatus,
				"thumb"=>$thumbs,
				"created"=>gmdate('Y-m-d H:i:s')
			];
		}
		
		$orderDesign['phone'] = '';
		$orderDesign['email'] = '';
		$orderDesign['type'] = 'o';
		$orderID = pdapp_save_woo_order($orderID, $orderDesign);

		$designID = $pdappDesign['designID'];
		$options = $pdappDesign['options'];
		$print = $pdappDesign['print'];
		$file = $pdappDesign['file'];
		$team = $pdappDesign['team'];
		$thumb = $pdappDesign['thumb'];
		$note = $pdappDesign['note'];

		$product = ["id"=>$order['product_id'], "name"=>$order['name']];
		$designItem = [
			"oid"=>$orderID,
			"did"=>$designID,
			"product"=>pdapp_json_encode($product),
			"price"=>$order['total'],
			"qty"=>$order['quantity'],
			"folder"=>$folder,
			"options"=>pdapp_json_encode($options),
			"print"=>pdapp_json_encode($print),
			"file"=>pdapp_json_encode($file),
			"team"=>pdapp_json_encode($team),
			"thumb"=>pdapp_json_encode($thumb),
			"note"=>$note
		];
		$detailID = pdapp_save_order_item('order', $designItem);

		$printLabel = pdapp_lang('printing_type');
		$options[$printLabel] = $print['title'];
		$pdappDesign = [
			'designID'=>$designID,
			'orderID'=>$orderID,
			'detailID'=>$detailID,
			'options'=>$options,
			'folder'=>$folder,
			'thumb'=>$thumb,
			'note'=>$note
		];

		/*Update stock*/
		if(isset($pdappDesign['attrs']))
		{
			pdapp_update_stock($designID, $pdappDesign['attrs']);
		}

		wc_add_order_item_meta($item_id, "pdappDesign", $pdappDesign);
		if(is_dir(PDAPP_UPLOAD_DIR .'carts/' .$folder))
		{
			pdapp_move_files(PDAPP_UPLOAD_DIR .'carts/' .$folder, PDAPP_UPLOAD_DIR .'orders/' .$folder);
			pdapp_remove_attachment($thumbnail);
		}
	}
}

/*
* get New Orders
*/
if(!function_exists('pdapp_new_orders'))
{
	function pdapp_new_orders()
	{
		$orders = pdapp_get_cache('orders', 'new-orders');
		if(!$orders)
		{
			$orders = [];
		}

		return $orders;
	}
}

/*
* get New Quotes
*/
if(!function_exists('pdapp_new_quotes'))
{
	function pdapp_new_quotes()
	{
		return [];
	}
}

/*
* opended Order
*/
if(!function_exists('pdapp_opened_order'))
{
	function pdapp_opened_order($type="", $id=0)
	{
		$res = pdapp_get_cache($type. 's', 'new-'. $type .'s');
		if($res && is_array($res))
		{
			$newVal = [];
			foreach($res as $val)
			{
				if($id != $val)
				{
					$newVal[] = $val;
				}
			}

			pdapp_set_cache($type. 's', 'new-'. $type .'s', $newVal);
		}
	}
}

/*
* Update stock
*/
if(!function_exists('pdapp_update_stock'))
{
	function pdapp_update_stock($id=0, $attrs=[])
	{
		global $wpdb;
		$isCache = true;
		$product = pdapp_get_cache('products', 'product-'. $id);
		if(!$product)
		{
			$isCache = false;
			$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_PRODUCTS, $id]), ARRAY_A);
			$product = ["id"=>$res['id'], "vid"=>$res['vid'], "title"=>$res["title"], "pid"=>$res['pid'], "thumb"=>$res['thumb'], "created"=>$res['created']];
		}
			
		if(!isset($product['vid']))
		{
			return false;
		}
		$value = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_VALUES, $product['vid']]), ARRAY_A);

		if(!isset($value['values']))
		{
			return false;
		}
		$value['values'] = json_decode($value['values'], true);

		if(isset($value['values']['attributes']) && isset($value['values']['attributes']['values']))
		{
			$attributes = $value['values']['attributes']['values'];
			foreach($attributes as $ind=>$attr)
			{
				$key = $attr['key'];
				if(isset($attrs[$key]) && $attrs[$key] != 0)
				{
					$stock = $attributes[$ind]['stock'];
					$stock = $stock - $attrs[$key];
					if($stock < 0)
					{
						$stock = 0;
					}
					$attributes[$ind]['stock'] = $stock;
				}
			}

			if(!$isCache)
			{
				$product = pdapp_merge_value($product, $value['values']);
			}

			$value['values']['attributes']['values'] = $attributes;
			pdapp_update_db(PDAPP_DB_VALUES, ['values'=>pdapp_json_encode($value['values'])], ['id'=>$product['vid']], ["%s"], ["%d"]);

			$product['attributes']['values'] = $attributes;
			pdapp_set_cache('products', 'product-'. $id, $product);
		}
	}
}

/*
* Update cart stock
*/
if(!function_exists('pdapp_get_cart_stock'))
{
	function pdapp_get_cart_stock($id=0, $attrs=[])
	{
		$result = [];
		$product = pdapp_get_product($id);
		$discount = 0;

		if(isset($product['attributes']) && isset($product['attributes']['values']))
		{
			$attributes = $product['attributes']['values'];
			foreach($attributes as $ind=>$attr)
			{
				$key = $attr['key'];
				if(isset($attrs[$key]) && $attrs[$key] != 0)
				{
					$stock = (int) $attr['stock'];
					if($stock - $attrs[$key] < 0)
					{
						$result[$key] = $stock;
						$price = (int) $attr['price'];
						$discount = $discount + ($attrs[$key] - $stock)*$price;
					}
				}
			}
		}
		$result['discount'] = $discount;
		
		if(isset($product['advanced']) && isset($product['advanced']['minQty']))
		{
			$minQty = (int) $product['advanced']['minQty'];
			$result['minQty'] = $minQty;
		}

		return $result;
	}
}

/******************* Cronjobs *********************/
/*
* Expired token
*/
if(!function_exists('pdapp_clean_expired_token'))
{
	function pdapp_clean_expired_token()
	{
		$timeCheck = gmdate("YmdH", strtotime("-". PDAPP_TOKEN_DATE ." days"));
		$files = pdapp_files_folder(PDAPP_PLUGIN_DIR .'cache/tokens');
		foreach($files as $file)
		{
			$time = str_replace('.txt', '', $file);
			if($timeCheck > $time)
			{
				pdapp_delete_cache('tokens', $time);
			}
		}
	}
}

/*
* Expired upload files
*/
if(!function_exists('pdapp_clean_upload'))
{
	function pdapp_clean_upload()
	{
		$timeCheck = gmdate("Ymd", strtotime("-". PDAPP_TOKEN_DATE ." days"));
		$folders = pdapp_files_folder(PDAPP_UPLOAD_DIR .'uploads', false);
		foreach($folders as $folder)
		{
			$folderCheck = (int) str_replace('-', '', $folder);
			if($timeCheck > $folderCheck)
			{
				$path = PDAPP_UPLOAD_DIR .'uploads/' .$folder;
				pdapp_delete_dir($path);
			}
		}

		if(PDAPP_CLEAN_CART)
		{
			$folders = pdapp_files_folder(PDAPP_UPLOAD_DIR .'carts', false);
			foreach($folders as $folder)
			{
				$folderCheck = (int) str_replace('-', '', $folder);
				if($timeCheck > $folderCheck)
				{
					$path = PDAPP_UPLOAD_DIR .'carts/' .$folder;
					pdapp_delete_dir($path);
				}
			}
		}
	}
}

/*
* Crop image
*/
if(!function_exists('pdapp_crop_photo'))
{
	function pdapp_crop_photo($original='', $origW=0, $crop=[], $path='')
	{
		$ext = '.png';
		$type = exif_imagetype($original);
		$originalImage = false;
		if($type == IMAGETYPE_JPEG)
		{
			$originalImage = imagecreatefromjpeg($original);
			$ext = '.jpg';
		}else if($type == IMAGETYPE_PNG)
		{
			$originalImage = imagecreatefrompng($original);
		}
		
		if(!$originalImage)
		{
			return false;
		}

		$imgWidth = imagesx($originalImage);

		$ratio = $imgWidth/$origW;
		$startY = (int) ($crop["top"] * $ratio);
		$startX = (int) ($crop["left"] * $ratio);
		$cropWidth = (int) ($crop["width"] * $ratio);
		$cropHeight = (int) ($crop["height"] * $ratio);

		$croppedImage = imagecreatetruecolor($cropWidth, $cropHeight);
		imagecopyresampled($croppedImage, $originalImage, 0, 0, $startX, $startY, $cropWidth, $cropHeight, $cropWidth, $cropHeight);

		ob_start();
		imagepng($croppedImage);
		$newImgData = ob_get_contents();
		imagedestroy($originalImage);
		imagedestroy($croppedImage);
		ob_end_clean();

		if($path != '')
		{
			if(!is_dir($path))
			{
				if (!wp_mkdir_p($path))
				{
					return array('error'=> pdapp_lang('error_wriable_permission', 'system').' '. $path);
				}
			}

			$filename = uniqid('layer-crop-') . $ext;
			$file = $path .'/'. $filename;
			pdapp_write_file($file, $newImgData);
			return $filename;
		}
		
		return $newImgData;
	}
}

/*
* Replace image
*/
if(!function_exists('pdapp_replace_image_svg'))
{
	function pdapp_replace_image_svg($svg='')
	{
		if(strpos($svg, 'image/svg+xml;base64,') !== false)
		{
			$str = str_replace('data:image/svg+xml;base64,', '', $svg);
			$svg = base64_decode($str);
		}
		$pattern = '/xlink:href="([^"]+)"/';

		if(preg_match_all($pattern, $svg, $matches))
		{
			if(isset($matches[1]))
			{
				$imageLinks = $matches[1];
			
				foreach ($imageLinks as $imageLink)
				{
					$file = str_replace(PDAPP_UPLOAD_URL, PDAPP_UPLOAD_DIR, $imageLink);
					if(file_exists($file))
					{
						$img = pdapp_read_file($file);
						$ext_parts = explode(".", $file);
						$ext       = strtolower($ext_parts[count($ext_parts)-1]);
						
						$base64 = $ext == 'png' || $ext == 'PNG' ? 'data:image/png;base64,'. base64_encode($img) : 'data:image/jpeg;base64,'.base64_encode($img);
						$svg = str_replace($imageLink, $base64, $svg);
					}else if(strpos($imageLink, '://') !== false)
					{
						$ext_parts = explode(".", $file);
						$ext       = strtolower($ext_parts[count($ext_parts)-1]);
						$type = $ext == 'png' || $ext == 'PNG' ? 'image/png' : 'image/jpeg';
						$img = pdapp_open_url($imageLink, $type);
						$base64 = 'data:'. $type .';base64,'. base64_encode($img);
						$svg = str_replace($imageLink, $base64, $svg);
					}
				}
			}
		}

		return $svg;
	}
}

/*
* Load image
*/
if(!function_exists('pdapp_load_image_svg'))
{
	function pdapp_load_image_svg($svg='', $path='')
	{
		$pattern = '/xlink:href="([^"]+)"/';

		if(preg_match_all($pattern, $svg, $matches))
		{
			if(isset($matches[1]))
			{
				$imageLinks = $matches[1];
			
				foreach ($imageLinks as $num=>$imageLink)
				{
					if(strpos($imageLink, ';base64,') !== false)
					{
						$ext = strpos($imageLink, 'image/png') !== false ? '.png' : '.jpg';
						$filename = 'up-design-'.$num. $ext;
						$file = $path. '/' .$filename;
						if(!file_exists($file))
						{
							$imgs = explode(';base64,', $imageLink);
							$data = base64_decode($imgs[1]);
							if(isset($imgs[1]))
							{
								if(pdapp_write_file($file, $data))
								{
									$file = str_replace(PDAPP_UPLOAD_DIR, PDAPP_UPLOAD_URL, $file);
									$svg = str_replace($imageLink, $file, $svg);
								}
							}
						}else
						{
							$file = str_replace(PDAPP_UPLOAD_DIR, PDAPP_UPLOAD_URL, $file);
							$svg = str_replace($imageLink, $file, $svg);
						}
					}else if(strpos($imageLink, '://') === false)
					{
						$svg = str_replace($imageLink, PDAPP_UPLOAD_URL . $imageLink, $svg);
					}
				}
			}
		}

		return $svg;
	}
}

/*
* Get image attach by image url
*/
if(!function_exists('pdapp_get_attachment_id'))
{
	function pdapp_get_attachment_id($image_url, $file_path)
	{
		global $wpdb;
		$attach_id = 0;
		$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM %i WHERE guid=%s", [$wpdb->posts, $image_url]));
		if(isset($attachment[0]))
		{
			$attach_id = $attachment[0];
		}else
		{
			if(!file_exists($file_path))
			{
				return 0;
			}
			
			$file_type = wp_check_filetype($file_path);
			$file_name = 'cart-'. gmdate("m-Y") .'-'. uniqid() . '.' .$file_type['ext'];
			
			$attachment = array(
				'guid'           => $image_url,
				'post_mime_type' => $file_type['type'],
				'post_title'     => sanitize_file_name($file_name),
				'post_content'   => '',
				'post_status'    => 'inherit',
			);
			$attach_id = wp_insert_attachment($attachment, $file_path, 0);
		}

		return $attach_id;
	}
}

/*
* Remove image attach by image url
*/
if(!function_exists('pdapp_remove_attachment'))
{
	function pdapp_remove_attachment($image_url)
	{
		global $wpdb;
		$attach_id = 0;
		$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM %i WHERE guid=%s", [$wpdb->posts, $image_url]));
		if(isset($attachment[0]))
		{
			$attach_id = $attachment[0];
			if($attach_id)
			{
				wp_delete_attachment($attach_id);
			}
		}
	}
}

/*
* Check block woo
*/
if(!function_exists('pdapp_check_woo_block'))
{
	function pdapp_check_woo_block()
	{
		$type = '';
		if(is_cart())
		{
			$type = 'cart';
		}elseif(is_checkout())
		{
			$type = 'checkout';
		}elseif(defined('REST_REQUEST') && REST_REQUEST)
		{
			$type = 'mini-cart';
		}
		
		if($type == '')
		{
			return false;
		}
		
		if($type == 'mini-cart' && class_exists('\Automattic\WooCommerce\Blocks\BlockTypes\MiniCart'))
		{
        	return true;
		}
		
		$page_id = wc_get_page_id($type);
		if($page_id)
		{
			$content = get_post_field('post_content', $page_id);
			return has_block('woocommerce/'. $type, $content);
		}

		return false;
	}
}
?>