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

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

/*
* Auth
*
* check Token
*/
add_action('wp_ajax_pdapp-verify-token', 'pdapp_verify_token');
add_action('wp_ajax_nopriv_pdapp-verify-token', 'pdapp_verify_token');
if(!function_exists('pdapp_verify_token'))
{
	function pdapp_verify_token()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		pdapp_response(0, "");
	}
}

/*
* Settings
*
* get default settings
*/
add_action('wp_ajax_pdapp-settings', 'pdapp_settings');
add_action('wp_ajax_nopriv_pdapp-settings', 'pdapp_settings');
if(!function_exists('pdapp_settings'))
{
	function pdapp_settings()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$langs = pdapp_languages('front');
		if(pdapp_get('langs') == 1)
		{
			pdapp_response(0, "", $langs);
		}

		$general = pdapp_get('general');
		$layout = pdapp_get('layout');
		$text = pdapp_get('text');
		$font = pdapp_get('font');
		$shape = pdapp_get('shape');
		$filter = pdapp_get('filter');
		$general = $general == 1 ? true : false;
		$layout = $layout == 1 ? true : false;
		$text = $text == 1 ? true : false;
		$font = $font == 1 ? true : false;
		$shape = $shape == 1 ? true : false;
		$filter = $filter == 1 ? true : false;

		$settings = pdapp_get_settings($general, $layout, $text, $font, $shape, $filter);

		if(pdapp_get('all') == '')
		{
			pdapp_response(0, "", $settings);
		}
		
		$menus = pdapp_get_menus();

		$fontsize = pdapp_get_font_size();

		$res = [
			"langs"=>$langs,
			"settings"=>$settings,
			"menus"=>$menus,
			"fontsize"=>$fontsize
		];
		
		pdapp_response(0, "", $res);
	}
}

/*
* Product
*
* get Product Detail
*/
add_action('wp_ajax_pdapp-product', 'pdapp_product');
add_action('wp_ajax_nopriv_pdapp-product', 'pdapp_product');
if(!function_exists('pdapp_product'))
{
	function pdapp_product()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$productID = (int) pdapp_get('id');

		if($productID == 0)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$pDesign = pdapp_woo_get_product(["pid"=>$productID]);
		if(isset($pDesign['did']))
		{
			$designID = $pDesign['did'];
		}else
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$product = pdapp_get_product($designID);
		if(!isset($product['id']))
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		if(!WC()->cart->is_empty())
		{
			foreach ( WC()->cart->get_cart() as $cart_item )
			{
				if (isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['attrs']))
				{
					$id = $cart_item['pdappDesign']['designID'];
					if($designID == $id && isset($product['attributes']) && isset($product['attributes']['values']))
					{
						$attributes = $product['attributes']['values'];
						foreach($attributes as $ind=>$attr)
						{
							$key = $attr['key'];
							if(isset($cart_item['pdappDesign']['attrs'][$key]) && $cart_item['pdappDesign']['attrs'][$key] != 0)
							{
								$stock = (int) $attr['stock'];
								$stock = $stock - (int) $cart_item['pdappDesign']['attrs'][$key];
								$product['attributes']['values'][$ind]['stock'] = $stock < 0 ? 0 : $stock;
							}
						}
					}
				}
			}
		}

		$product['temp'] = pdapp_get_template($pDesign['values']);

		if(!isset($product['advanced']['artID']))
		{
			$product['advanced']['artID'] = 0;
		}
		if(!isset($product['advanced']['tempID']))
		{
			$product['advanced']['tempID'] = 0;
		}

		pdapp_response(0, "", $product);
	}
}

/*
* Templates
*
* get Folder
*/
add_action('wp_ajax_pdapp-temp-folders', 'pdapp_temp_folders');
add_action('wp_ajax_nopriv_pdapp-temp-folders', 'pdapp_temp_folders');
if(!function_exists('pdapp_temp_folders'))
{
	function pdapp_temp_folders()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$folders = pdapp_get_template_folders();
		pdapp_response(0, "", $folders);
	}
}

/*
* Templates
*
* get Templates
*/
add_action('wp_ajax_pdapp-templates', 'pdapp_templates');
add_action('wp_ajax_nopriv_pdapp-templates', 'pdapp_templates');
if(!function_exists('pdapp_templates'))
{
	function pdapp_templates()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		$folderID = pdapp_get('folder');
		if($folderID == '')
		{
			$folderID = 0;
		}

		$templates = pdapp_get_cache('templates', 'templates-'. $folderID);
		if(!$templates)
		{
			$templates = [];
			global $wpdb;
			$res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `pid`=%d AND `type`='t'", [PDAPP_DB_TEMPLATES, $folderID]), ARRAY_A);
			foreach($res as $val)
			{
				$templates[] = ["id"=>$val['id'], "pid"=>$val['pid'], "title"=>json_decode($val["title"], true), "price"=>$val['price'], "size"=>json_decode($val["size"], true), "thumb"=>$val['thumb'], "created"=>$val['created']];
			}
			pdapp_set_cache('templates', 'templates-'. $folderID, $templates);
		}

		pdapp_response(0, "", $templates);
	}
}

/*
* get Template
*/
add_action('wp_ajax_pdapp-template', 'pdapp_template');
add_action('wp_ajax_nopriv_pdapp-template', 'pdapp_template');
if(!function_exists('pdapp_template'))
{
	function pdapp_template()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		$tempID = (int) pdapp_get('id');
		if($tempID == 0)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$file = PDAPP_UPLOAD_DIR .'templates/template-'. md5(PDAPP_PREFIX . $tempID) .'.pda';
		$temp = pdapp_read_file($file);
		if($temp)
		{
			pdapp_response(0, md5(PDAPP_PREFIX . $tempID), $temp);
		}
		
		pdapp_response(1, pdapp_lang('file_empty', 'system'));
	}
}

/*
* Artworks
*
* get Folders
*/
add_action('wp_ajax_pdapp-art-folders', 'pdapp_art_folders');
add_action('wp_ajax_nopriv_pdapp-art-folders', 'pdapp_art_folders');
if(!function_exists('pdapp_art_folders'))
{
	function pdapp_art_folders()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$folders = pdapp_get_art_folders();
		pdapp_response(0, "", $folders);
	}
}

/*
* get Artworks
*/
add_action('wp_ajax_pdapp-artworks', 'pdapp_artworks');
add_action('wp_ajax_nopriv_pdapp-artworks', 'pdapp_artworks');
if(!function_exists('pdapp_artworks'))
{
	function pdapp_artworks()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		$folderID = pdapp_get('folder');
		if($folderID == '')
		{
			$folderID = 0;
		}

		$arts = pdapp_get_cache('arts', 'arts-'. $folderID);
		if(!$arts)
		{
			$arts = [];
			global $wpdb;
			$res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `pid`=%d AND `type`='a'", [PDAPP_DB_ARTWORKS, $folderID]), ARRAY_A);
			foreach($res as $val)
			{
				$arts[] = ["id"=>$val['id'], "pid"=>$val['pid'], "title"=>json_decode($val["title"], true), "price"=>$val['price'], "filetype"=>$val['filetype'], "thumb"=>$val['thumb'], "created"=>$val['created']];
			}
			pdapp_set_cache('arts', 'arts-'. $folderID, $arts);
		}

		pdapp_response(0, "", $arts);
	}
}

/*
* get Artwork
*/
add_action('wp_ajax_pdapp-artwork', 'pdapp_artwork');
add_action('wp_ajax_nopriv_pdapp-artwork', 'pdapp_artwork');
if(!function_exists('pdapp_artwork'))
{
	function pdapp_artwork()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		$artID = (int) pdapp_get('id');
		if($artID == 0)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$filetype = pdapp_get('type');
		
		$file = PDAPP_UPLOAD_DIR .'arts/art-'. md5(PDAPP_PREFIX . $artID) .'.'. $filetype;
		$art = pdapp_read_file($file);
		if($art)
		{
			$res = '';
			if($filetype == 'svg')
			{
				$res = $art;
			}else
			{
				$res = 'data:image/' . $filetype . ';base64,' . base64_encode($art);
			}

			if($res != '')
			{
				pdapp_response(0, "", $res);
			}
		}
		
		pdapp_response(1, pdapp_lang('file_empty', 'system'));
	}
}

/*
* Design
* get Designs
*/
add_action('wp_ajax_pdapp-your-designs', 'pdapp_your_designs');
add_action('wp_ajax_nopriv_pdapp-your-designs', 'pdapp_your_designs');
if(!function_exists('pdapp_your_designs'))
{
	function pdapp_your_designs()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$productID = (int) pdapp_get('id');
		$email = pdapp_get('email');
		if($email == '')
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		if($productID == 0)
		{
			$designs = pdapp_get_cache('designs', 'lists-'. md5($email));
		}else
		{
			$designs = pdapp_get_cache('designs', 'product-'. $productID .'-'. md5($email));
		}

		if(!$designs)
		{
			global $wpdb;
			if($productID == 0)
			{
				$designs = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `email`=%s", [PDAPP_DB_DESIGNS, $email]), ARRAY_A);
			}else
			{
				$designs = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `email`=%s AND `pid`=%d", [PDAPP_DB_DESIGNS, $email, $productID]), ARRAY_A);
			}
			
			if(count($designs))
			{
				foreach($designs as $key=>$design)
				{
					$designs[$key]['values'] = json_decode($design['values'], true);
				}
				if($productID == 0)
				{
					pdapp_set_cache('designs', 'lists-'. md5($email), $designs);
				}else
				{
					pdapp_set_cache('designs', 'product-'. $productID .'-'. md5($email), $designs);
				}
			}
		}
		
		pdapp_response(0, '', $designs);
	}
}

/*
* get Design
*/
add_action('wp_ajax_pdapp-load-design', 'pdapp_load_design');
add_action('wp_ajax_nopriv_pdapp-load-design', 'pdapp_load_design');
if(!function_exists('pdapp_load_design'))
{
	function pdapp_load_design()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$designID = (int) pdapp_get('id');
		$email = pdapp_get('email');
		if($email == '' || $designID == 0)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		$design = pdapp_get_cache('designs', 'design-'. $designID);
		if(!$design)
		{
			global $wpdb;
			$design = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `email`=%s AND `id`=%d", [PDAPP_DB_DESIGNS, $email, $designID]), ARRAY_A);
			if(isset($design['id']))
			{
				$design['values'] = json_decode($design['values'], true);
				pdapp_set_cache('designs', 'design-'. $designID, $design);
			}
		}
		
		if(isset($design['id']) && $design['email'] == $email && count($design['values']))
		{
			$check = false;
			$files = [];
			$path = '';
			$tokenNone = pdapp_get('pdapp-token');
			$token = explode('-', $tokenNone);
			if(count($token) == 2)
			{
				$folder = substr($token[0], 0, 4) .'-'. substr($token[0], 4, 2) .'-'. substr($token[0], 6, 2);
				$path = PDAPP_UPLOAD_DIR .'uploads/' .$folder .'/'. $token[1] .'/upload';
			}
			foreach($design['values'] as $val)
			{
				$array = explode('-', $val);
				if(!isset($array[0]))
				{
					$array[0] = 0;
				}
				if(!isset($array[1]))
				{
					$array[1] = 0;
				}

				$file = PDAPP_UPLOAD_DIR .'designs/d'. $designID .'/'. $val .'-'. md5(PDAPP_PREFIX . $designID) .'.pda';
				$data = pdapp_read_file($file);
				if(!isset($files[$array[0]][$array[1]]))
				{
					$files[$array[0]][$array[1]] = '';
				}
				if($data)
				{
					$check = true;
					
					if(!is_dir($path))
					{
						wp_mkdir_p($path);
					}
					if($path == '' || !is_dir($path))
					{
						pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
					}

					$svg = pdapp_load_image_svg($data, $path);
					$files[$array[0]][$array[1]] = $svg;
				}
			}
			if($check)
			{
				pdapp_response(0, '', $files);
			}
		}
		
		pdapp_response(1, pdapp_lang('design.load_design_error'));
	}
}

/*
* save Design
*/
add_action('wp_ajax_pdapp-save-design', 'pdapp_save_design');
add_action('wp_ajax_nopriv_pdapp-save-design', 'pdapp_save_design');
if(!function_exists('pdapp_save_design'))
{
	function pdapp_save_design()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		$error = pdapp_lang('design.save_error');

		$post = pdapp_upload_jsons('design', ['id'=>"key", 'title'=>"text", 'email'=>"email", 'thumb'=>"text", 'design'=>"text", 'designID'=>"key", 'productID'=>"key"]);
		if(!$post)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$post['thumb'] = is_string($post['thumb']) ? json_decode($post['thumb'], true) : $post['thumb'];
		$post['design'] = is_string($post['design']) ? json_decode($post['design'], true) : $post['design'];

		if(!$post['email'])
		{
			pdapp_response(1, $error);
		}
		
		$designID = (int) $post['designID'];
		$productID = (int) $post['productID'];
		if($designID == 0 || $productID == 0)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		$did = $post['id'] ? (int) $post['id'] : pdapp_insert_db(PDAPP_DB_DESIGNS, ["did"=>$designID, "pid"=>$productID, "title"=>$post['title'], "email"=>$post['email'], "thumb"=>"", "values"=>"[]", "created"=>gmdate('Y-m-d H:i:s')], ["%d", "%d", "%s", "%s", "%s", "%s", "%s"]);
		if(!$did)
		{
			pdapp_response(1, $error);
		}

		$thumb = $post['thumb'] ? pdapp_write_image('designs/d'. $did, $post['thumb']) : '';
		$update = ["did"=>$designID, "pid"=>$productID, "title"=>$post['title'], "thumb"=>$thumb];
		$update['values'] = pdapp_save_designs($post['design'], $did);
		
		if($post['id'])
		{
			$error = pdapp_lang('design.update_error');
			pdapp_update_db(PDAPP_DB_DESIGNS, pdapp_verify_field($update, ["did", "pid", "title", "thumb", "values"]), ["id"=>$did], ["%d", "%d", "%s", "%s", "%s"], ["%d"]);

			$res = ["id"=>$did, "did"=>$designID, "pid"=>$productID, "title"=>$post['title'], "email"=>$post['email'], "thumb"=>$thumb, "values"=>$update['values'], "created"=>$post['created']];
			pdapp_delete_cache('designs', 'lists-'. md5($post['email']));
			pdapp_delete_cache('designs', 'product-'. $productID .'-'. md5($post['email']));
			pdapp_delete_cache('designs', 'design-'. $did);
			pdapp_response(0, pdapp_lang('design.update_success'), $res);
		}else
		{
			if(pdapp_update_db(PDAPP_DB_DESIGNS, pdapp_verify_field($update, ["did", "pid", "title", "thumb", "values"]), ["id"=>$did], ["%d", "%d", "%s", "%s", "%s"], ["%d"]))
			{
				$res = ["id"=>$did, "did"=>$designID, "pid"=>$productID, "title"=>$post['title'], "email"=>$post['email'], "thumb"=>$thumb, "values"=>$update['values'], "created"=>gmdate('Y-m-d H:i:s')];
				pdapp_delete_cache('designs', 'lists-'. md5($post['email']));
				pdapp_delete_cache('designs', 'product-'. $productID .'-'. md5($post['email']));
				pdapp_set_cache('designs', 'design-'. $did, $res);
				pdapp_response(0, pdapp_lang('design.save_success'), $res);
			}
		}

		pdapp_response(1, $error);
	}
}

/*
* remove Design
*/
add_action('wp_ajax_pdapp-remove-design', 'pdapp_remove_design');
add_action('wp_ajax_nopriv_pdapp-remove-design', 'pdapp_remove_design');
if(!function_exists('pdapp_remove_design'))
{
	function pdapp_remove_design()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$msg = pdapp_lang('remove_design_error');
		$id = pdapp_post('id', 'key', 0);
		$productID = pdapp_post('productID', 'key', 0);
		$email = pdapp_post('email', 'text', '');
		if($id && $productID && $email)
		{
			$del = pdapp_delete_db(PDAPP_DB_DESIGNS, ["id"=>$id, "pid"=>$productID, "email"=>$email], ["%d", "%d", "%s"]);
			if($del)
			{
				pdapp_delete_dir(PDAPP_UPLOAD_DIR .'designs/d'. $id);
				
				pdapp_delete_cache('designs', 'lists-'. md5($email));
				pdapp_delete_cache('designs', 'product-'. $productID .'-'. md5($email));
				pdapp_delete_cache('designs', 'design-'. $id);
				
				pdapp_response(0, pdapp_lang('remove_design_success'));
			}
		}
		
		pdapp_response(1, $msg);
	}
}

/*
* render Design
*/
add_action('wp_ajax_pdapp-render-design', 'pdapp_render_design');
add_action('wp_ajax_nopriv_pdapp-render-design', 'pdapp_render_design');
if(!function_exists('pdapp_render_design'))
{
	function pdapp_render_design()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$post = pdapp_upload_jsons('design', ['svg'=>"text"]);
		if(!$post)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		$svg = pdapp_replace_image_svg($post['svg']);
		
		pdapp_response(0, '', $svg);
	}
}

/*
* Print
*
* get Printing
*/
add_action('wp_ajax_pdapp-print', 'pdapp_print');
add_action('wp_ajax_nopriv_pdapp-print', 'pdapp_print');
if(!function_exists('pdapp_print'))
{
	function pdapp_print()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$id = (int) pdapp_get('id');
		if($id == 0)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$print = pdapp_get_cache('prints', 'print-'. $id);
		if(!$print)
		{
			global $wpdb;
			$res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_PRINTS, $id]), ARRAY_A);
			if(!isset($res['id']))
			{
				pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
			}
			$print = ["id"=>(int) $res['id'], "pid"=>$res['pid'], "title"=>$res["title"], "thumb"=>$res['thumb'], "created"=>$res['created']];
			
			$value = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_VALUES, $res['pid']]), ARRAY_A);
			if(!isset($value['values']))
			{
				pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
			}

			$value['values'] = json_decode($value['values'], true);
			$print['prints'] = $value['values'];
			pdapp_set_cache('prints', 'print-'. $id, $print);
		}
		
		pdapp_response(0, '', $print);
	}
}

/*
* 	PHOTOS
*
*	upload Image
*/
add_action('wp_ajax_pdapp-upload-image', 'pdapp_upload_image');
add_action('wp_ajax_nopriv_pdapp-upload-image', 'pdapp_upload_image');
if(!function_exists('pdapp_upload_image'))
{
	function pdapp_upload_image()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		
		$tokenNone = pdapp_get('pdapp-token');
		if($tokenNone != '' && isset($_FILES['file']) && !empty($_FILES['file']['name']))
		{
			$token = explode('-', $tokenNone);
			$path = '';
			if(count($token) == 2)
			{
				$folder = substr($token[0], 0, 4) .'-'. substr($token[0], 4, 2) .'-'. substr($token[0], 6, 2);
				$path = PDAPP_UPLOAD_DIR .'uploads/' .$folder .'/'. $token[1] .'/upload';

				$filename = uniqid('up-');
				$result = pdapp_upload('file', $path, ['png', 'jpg', 'jpeg'], $filename, ['jpg|jpeg|jpe'=>'image/jpeg', 'png'=>'image/png']);
				if($result['error'] == 0 && isset($result['filename']) && $result['filename'] != '')
				{
					pdapp_response(0, "", PDAPP_UPLOAD_URL. 'uploads/' .$folder .'/'. $token[1] .'/upload/'. $result['filename']);
				}else
				{
					pdapp_response(1, $result['message']);
				}
			}
		}else
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		pdapp_response(1, pdapp_lang('upload_error', 'system'));
	}
}

/*
*	load Image
*/
add_action('wp_ajax_pdapp-load-image', 'pdapp_load_image');
add_action('wp_ajax_nopriv_pdapp-load-image', 'pdapp_load_image');
if(!function_exists('pdapp_load_image'))
{
	function pdapp_load_image()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$post = [
			"url"=>pdapp_post('url', 'text', '')
		];
		$tokenNone = pdapp_get('pdapp-token');
		if ($post['url'] == '' || $tokenNone == '')
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		$imgURL = $post['url'];

		$token = explode('-', $tokenNone);
		$path = '';
		if(count($token) == 2)
		{
			$folder = substr($token[0], 0, 4) .'-'. substr($token[0], 4, 2) .'-'. substr($token[0], 6, 2);
			$path = PDAPP_UPLOAD_DIR .'uploads/' .$folder .'/'. $token[1] .'/upload';
			if(!is_dir($path))
			{
				wp_mkdir_p($path);
			}
		}
		
		if($path == '' || !is_dir($path))
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		$fileType = 'image/png';
		$fileEx = '.png';
		if(strpos($imgURL, 'fm=jpg') != false || strpos($imgURL, '.jpg') != false)
		{
			$fileType = 'image/jpg';
			$fileEx = '.jpg';
		}else if(strpos($imgURL, 'fm=jpeg') != false || strpos($imgURL, '.jpeg') != false)
		{
			$fileType = 'image/jpeg';
			$fileEx = '.jpeg';
		}

		$filename = !empty($post['id']) ? $post['id'] : uniqid();
		$filename = 'lib-'. $filename . $fileEx;
		$path = $path . '/' .$filename;
		if(!file_exists($path))
		{
			$image = pdapp_open_url($imgURL, $fileType);
			$check = pdapp_write_file($path, $image);
			
			if($check)
			{
				pdapp_response(0, "", PDAPP_UPLOAD_URL. 'uploads/' .$folder .'/'. $token[1] .'/upload/'. $filename);
			}
		}else
		{
			pdapp_response(0, "", PDAPP_UPLOAD_URL. 'uploads/' .$folder .'/'. $token[1] .'/upload/'. $filename);
		}
		
		pdapp_response(1, pdapp_lang('load_file_error', 'system'));
	}
}

/*
*	crop Image
*/
add_action('wp_ajax_pdapp-crop-image', 'pdapp_crop_image');
add_action('wp_ajax_nopriv_pdapp-crop-image', 'pdapp_crop_image');
if(!function_exists('pdapp_crop_image'))
{
	function pdapp_crop_image()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$post = [
			"file"=>pdapp_post('file', 'text', ),
			"origW"=>pdapp_post('origW', 'text', ),
			"crop"=>pdapp_post('crop', 'text', )
		];
		
		$tokenNone = pdapp_get('pdapp-token');
		if (empty($post['file']) || empty($post['origW']) || empty($post['crop']) || $tokenNone == '')
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		$file = $post['file'];
		$origW = $post['origW'];
		$crop = is_string($post['crop']) ? json_decode($post['crop'], true) : $post['crop'];
		$token = explode('-', $tokenNone);
		$path = '';
		if(count($token) == 2)
		{
			$folder = substr($token[0], 0, 4) .'-'. substr($token[0], 4, 2) .'-'. substr($token[0], 6, 2);
			$path = PDAPP_UPLOAD_DIR .'uploads/' .$folder .'/'. $token[1] .'/upload';
			if(!is_dir($path))
			{
				pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
			}
		}

		if($path == '' || !is_dir($path))
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		
		$file = str_replace(PDAPP_UPLOAD_URL, PDAPP_UPLOAD_DIR, $file);
		if(!file_exists($file))
		{
			pdapp_response(1, pdapp_lang('load_file_error', 'system'));
		}

		$filename = pdapp_crop_photo($file, $origW, $crop, $path);
		
		if($filename)
		{
			pdapp_response(0, "", PDAPP_UPLOAD_URL. 'uploads/' .$folder .'/'. $token[1] .'/upload/'. $filename);
		}else
		{
			pdapp_response(1, pdapp_lang('load_file_error', 'system'));
		}
	}
}

/*
*	get price
*/
add_action('wp_ajax_pdapp-get-art-price', 'pdapp_get_art_price');
add_action('wp_ajax_nopriv_pdapp-get-art-price', 'pdapp_get_art_price');
if(!function_exists('pdapp_get_art_price'))
{
	function pdapp_get_art_price()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$arts = pdapp_post('art', 'key');
		$temps = pdapp_post('temp', 'key');

		global $wpdb;
		$res = [];
		foreach($arts as $id)
		{
			$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_ARTWORKS, $id]), ARRAY_A);
			if(isset($row['id']))
			{
				$res[] = ["art-". $id => $row['price']];
			}
		}

		foreach($temps as $id)
		{
			$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_TEMPLATES, $id]), ARRAY_A);
			if(isset($row['id']))
			{
				$res[] = ["temp-". $id => $row['price']];
			}
		}
		
		pdapp_response(0, "", $res);
	}
}

/*
* Cart
* Request a quote
*/
add_action('wp_ajax_pdapp-request-quote', 'pdapp_request_quote');
add_action('wp_ajax_nopriv_pdapp-request-quote', 'pdapp_request_quote');
if(!function_exists('pdapp_request_quote'))
{
	function pdapp_request_quote()
	{
		pdapp_response(1, pdapp_lang('cart.send_quote_error'));
	}
}

/*
* Add to Cart
*/
add_action('wp_ajax_pdapp-add-to-cart', 'pdapp_add_to_cart');
add_action('wp_ajax_nopriv_pdapp-add-to-cart', 'pdapp_add_to_cart');
if(!function_exists('pdapp_add_to_cart'))
{
	function pdapp_add_to_cart()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$post = pdapp_upload_jsons('cart', ['pid'=>"key", 'did'=>"key", 'print'=>"text", 'items'=>"text", 'note'=>"text", 'designs'=>"text", 'qty'=>"key", 'total'=>"text"], ['regular_total'=>'text']);
		if(!$post)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$post['print'] = is_string($post['print']) ? json_decode($post['print'], true) : $post['print'];
		$post['items'] = is_string($post['items']) ? json_decode($post['items'], true) : $post['items'];
		$post['designs'] = is_string($post['designs']) ? json_decode($post['designs'], true) : $post['designs'];
		
		$team = isset($post['team']) ? $post['team'] : [];
		$tokenNone = pdapp_get('pdapp-token');
		$token = explode('-', $tokenNone);
		if(count($token) == 2)
		{
			$folder = substr($token[0], 0, 4) .'-'. substr($token[0], 4, 2) .'-'. substr($token[0], 6, 2);
			$pathSource = PDAPP_UPLOAD_DIR .'carts/' .$folder .'/'. $token[1];

			$designs = $post['designs'];
			
			$path = $pathSource .'/print';
			if(!is_dir($path))
			{
				wp_mkdir_p($path);
			}
			
			$files = [];
			foreach($designs as $key=>$design)
			{
				foreach($design as $k=>$val)
				{
					$val['svg'] = pdapp_replace_image_svg($val['svg']);

					pdapp_write_file($path. '/' .$key. '-' .$k. '-' .PDAPP_PREFIX. 'design.pda', $val['svg']);
					$files[] = $key. '-' .$k;
				}
			}

			$total = $post['total'];
			$regular_total = $post['regular_total'] != '' ? $post['regular_total'] : 0;

			foreach($post['items'] as $item)
			{
				$price = round($total/(int) $post['qty'], 2);
				$regular_price = round($regular_total/(int) $post['qty'], 2);
				pdapp_add_cart($item, $post['pid'], $post['did'], $post['print'], $team, $post['note'], $files, $price, $regular_price, $post['qty'], $folder.'/'.$token[1]);
			}
			
			pdapp_copy_files(PDAPP_UPLOAD_DIR .'uploads/' .$folder .'/'. $token[1], $pathSource);
			pdapp_response(0, "", wc_get_cart_url());
		}

		pdapp_response(1, pdapp_lang('cart.error'));
	}
}

/*
* FONTS
*
* get Fonts
*/
add_action('wp_ajax_pdapp-fonts', 'pdapp_fonts');
add_action('wp_ajax_nopriv_pdapp-fonts', 'pdapp_fonts');
if(!function_exists('pdapp_fonts'))
{
	function pdapp_fonts()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		
		$setting = pdapp_get_settings(false, false, false, true, false, false);
		$listFonts = $setting['font'];
		$datas = [
			"url"=> PDAPP_GG_FONT,
			"find"=> '',
			"category"=> '',
			"fonts"=> []
		];
		foreach($listFonts as $font)
		{
			$datas['fonts'][] = [
				"title"=>$font['title'],
				"variants"=>$font['variants'],
				"category"=>$font['category']
			];
		}

		pdapp_response(0, "", $datas);
	}
}

/*
*	load Font
*/
add_action('wp_ajax_pdapp-load-font', 'pdapp_load_font');
add_action('wp_ajax_nopriv_pdapp-load-font', 'pdapp_load_font');
if(!function_exists('pdapp_load_font'))
{
	function pdapp_load_font()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}
		$title = pdapp_post('title', 'text');
		if(!$title)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}

		$key = str_replace(' ', '-', strtolower($title));
		$font = pdapp_get_cache('fonts', $key);

		if(!$font)
		{
			$listFonts = pdapp_get_list_fonts();
			foreach($listFonts as $res)
			{
				if($res['title'] == $title)
				{
					$font = '';
					foreach($res['files'] as $type=>$file)
					{
						if($res['category'] == 'custom' || strpos($file, 'http') === false)
						{
							$fontData = pdapp_read_file(PDAPP_PLUGIN_DIR .'assets/fonts/'. $file);
						}else
						{
							$fontData = pdapp_open_url($file, 'font/truetype');
						}
						
						$fontData = base64_encode($fontData);

						$fontWeight = ($type == 'regular') ? 'normal' : '700';
						$font .= "@font-face{font-family: '$title';src: url(data:font/truetype;charset=utf-8;base64,$fontData) format('truetype');font-weight: $fontWeight;font-style: normal;}";
					}
						
					pdapp_set_cache('fonts', $key, $font);
				}
			}
		}
		
		if($font)
		{
			pdapp_response(0, "", ["fontface"=> $font]);
		}else
		{
			pdapp_response(1, pdapp_lang('cannot_load_font', 'system'));
		}
	}
}

/*
*	Download PNG 300DPI
*/
add_action('wp_ajax_pdapp-download-png', 'pdapp_download_png');
add_action('wp_ajax_nopriv_pdapp-download-png', 'pdapp_download_png');
if(!function_exists('pdapp_download_png'))
{
	function pdapp_download_png()
	{
		if (!pdapp_check_token())
		{
			pdapp_response(-1, pdapp_lang('token_error', 'system'));
		}

		$imgData = pdapp_post('imgData', 'text');
		if(!$imgData || strpos($imgData, ';base64,') === false)
		{
			pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
		}
		if(strpos($imgData, ';base64,') !== false)
		{
			$imgs = explode(';base64,', $imgData);
			if(isset($imgs[1]))
			{
				$imgData = base64_decode($imgs[1]);
			}
		}

		$convert = round(300/0.0254);
		if (extension_loaded('gd') && function_exists('imagesetresolution'))
		{
			$image = imagecreatefromstring($imgData);
			imagesetresolution($image, $convert, $convert);
			
			ob_start();
			imagepng($image);
			$newImgData = ob_get_contents();
			imagedestroy($image);
			ob_end_clean();
		}else
		{
			$incPos = strpos($imgData, 'IDAT') - 4;
			$chunk = 'pHYs'.pack('NNc', $convert, $convert, 1);
			$incData = pack('N', 9).$chunk.pack('N', crc32($chunk));
			$newImgData = substr_replace($imgData, $incData, $incPos, 0);
		}
		
		pdapp_response(0, "", 'data:image/png;base64,'. base64_encode($newImgData));
	}
}
?>