<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{	
	public $defaultCaptcha = 'pjCatering_Captcha';
	
	public $defaultLocale = 'pjCatering_LocaleId';
	
	public $defaultFrontUser = 'pjCatering_User';
	
	public $defaultLangMenu = 'pjCatering_LangMenu';
	
	public $defaultStore = 'pjCatering_Store';
	
	public $defaultForm = 'pjCatering_Form';
	
	public function __construct()
	{
		$this->setLayout('pjActionFront');
		
		self::allowCORS();
	}
	
	public function _get($key)
	{
		if ($this->_is($key))
		{
			return $_SESSION[$this->defaultStore][$key];
		}
		return false;
	}
	
	public function _is($key)
	{
		return isset($_SESSION[$this->defaultStore]) && isset($_SESSION[$this->defaultStore][$key]);
	}
	
	public function _set($key, $value)
	{
		$_SESSION[$this->defaultStore][$key] = $value;
		return $this;
	}
	
	public function _unset($key)
	{
		if ($this->_is($key))
		{
			unset($_SESSION[$this->defaultStore][$key]);
		}
	}
	
	public function afterFilter()
	{		
		if (!isset($_GET['hide']) || (isset($_GET['hide']) && (int) $_GET['hide'] !== 1) &&
			in_array($_GET['action'], array('pjActionMenu', 'pjActionPackages', 'pjActionProducts', 'pjActionPackage')))
		{
			$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file, t2.title')
				->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
				->where('t2.file IS NOT NULL')
				->orderBy('t1.sort ASC')->findAll()->getData();			
			$this->set('locale_arr', $locale_arr);
		}
		$category_arr = pjCategoryModel::factory()
			->select("t1.id, t1.parent_id, t1.image, t2.content as name, t3.content as description")
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjCategory' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjCategory' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
			->where("t1.parent_id IS NULL")
			->orderBy("`order` ASC")
			->findAll()
			->getData();
		$this->set('category_arr', $category_arr);
		
		if(in_array($_GET['action'], array('pjActionMenu', 'pjActionPackages', 'pjActionProducts', 'pjActionPackage')))
		{
			$product_in_cart = array();
			$package_in_cart = array();
			if($this->_is('products'))
			{
				$product_in_cart = $this->_get('products');
			}
			if($this->_is('packages'))
			{
				$package_in_cart = $this->_get('packages');
			}
			$cart_arr = pjAppController::getCart($product_in_cart, $package_in_cart, $this->getLocaleId(), $this->option_arr);
			$this->set('cart_arr', $cart_arr);
		}
	}
	
	public function beforeFilter()
	{
		$OptionModel = pjOptionModel::factory();
		$this->option_arr = $OptionModel->getPairs($this->getForeignId());
		$this->set('option_arr', $this->option_arr);
		$this->setTime();

		if (isset($_GET['locale']) && (int) $_GET['locale'] > 0)
		{
			$this->pjActionSetLocale($_GET['locale']);
		}
			
		if ($this->pjActionGetLocale() === FALSE)
		{
			$locale_arr = pjLocaleModel::factory()->where('is_default', 1)->limit(1)->findAll()->getData();
			if (count($locale_arr) === 1)
			{
				$this->pjActionSetLocale($locale_arr[0]['id']);
			}
		}
		if (!in_array($_GET['action'], array('pjActionLoadCss')))
		{
			$this->loadSetFields();
		}
	}
	
	public function beforeRender()
	{
		if (isset($_GET['iframe']))
		{
			$this->setLayout('pjActionIframe');
		}
	}
	
	public function pjActionLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_GET['locale_id']))
			{
				$this->pjActionSetLocale($_GET['locale_id']);
				
				$this->loadSetFields(true);
				
				$day_names = __('day_names', true);
				ksort($day_names, SORT_NUMERIC);
				
				$months = __('months', true);
				ksort($months, SORT_NUMERIC);
				
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Locale have been changed.', 'opts' => array(
					'day_names' => array_values($day_names),
					'month_names' => array_values($months)
				)));
			}
		}
		exit;
	}
	private function pjActionSetLocale($locale)
	{
		if ((int) $locale > 0)
		{
			$_SESSION[$this->defaultLocale] = (int) $locale;
		}
		return $this;
	}
	
	public function pjActionGetLocale()
	{
		return isset($_SESSION[$this->defaultLocale]) && (int) $_SESSION[$this->defaultLocale] > 0 ? (int) $_SESSION[$this->defaultLocale] : FALSE;
	}
	
	public function pjActionCaptcha()
	{
		$this->setAjax(true);
		$Captcha = new pjCaptcha(PJ_INSTALL_PATH.  'app/web/obj/Anorexia.ttf', $this->defaultCaptcha, 6);
		$Captcha->setImage(PJ_INSTALL_PATH . 'app/web/img/button.png')->init(isset($_GET['rand']) ? $_GET['rand'] : null);
	}

	public function pjActionCheckCaptcha()
	{
		$this->setAjax(true);
		if (!isset($_GET['captcha']) || empty($_GET['captcha']) || strtoupper($_GET['captcha']) != $_SESSION[$this->defaultCaptcha]){
			echo 'false';
		}else{
			echo 'true';
		}
		exit;
	}
	
	public function pjActionLoadCss()
	{
		$dm = new pjDependencyManager(PJ_INSTALL_PATH, PJ_THIRD_PARTY_PATH);
		$dm->load(PJ_CONFIG_PATH . 'dependencies.php')->resolve();
		
		$theme = isset($_GET['theme']) ? $_GET['theme'] : $this->option_arr['o_layout'];
		if((int) $theme > 0)
		{
			$theme = 'theme' . $theme;
		}
		$arr = array(
				array('file' => 'font-awesome.min.css', 'path' => $dm->getPath('font_awesome') . 'css/'),
				array('file' => 'bootstrap-datetimepicker.min.css', 'path' => $dm->getPath('pj_bootstrap_datetimepicker')),
				array('file' => 'style.css', 'path' => PJ_CSS_PATH),
				array('file' => "$theme.css", 'path' => PJ_CSS_PATH . "themes/")
		);
		header("Content-Type: text/css; charset=utf-8");
		foreach ($arr as $item)
		{
			ob_start();
			@readfile($item['path'] . $item['file']);
			$string = ob_get_contents();
			ob_end_clean();
			
			if ($string !== FALSE)
			{
				echo str_replace(
					array('../img/', '../fonts/fontawesome', '../fonts/', 'images/', '../fonts/glyphicons', "pjWrapper"),
					array(
						PJ_INSTALL_URL . PJ_IMG_PATH,
						PJ_INSTALL_URL . $dm->getPath('font_awesome') . 'fonts/fontawesome',
						PJ_INSTALL_URL . 'app/web/fonts/',
						PJ_INSTALL_URL . PJ_IMG_PATH . 'frontend/',
						PJ_INSTALL_URL . PJ_FRAMEWORK_LIBS_PATH . 'pj/fonts/glyphicons',
						"pjWrapperCatering_" . $theme
					),
					$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
		if(isset($_GET['locale']) && $_GET['locale'] > 0)
		{
			$this->pjActionSetLocale($_GET['locale']);
			$this->loadSetFields(true);
		}
	}
	
	public function pjActionAddCart()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_POST['id']) && (int) $_POST['id'] > 0 && isset($_POST['type']) && in_array($_POST['type'], array('products', 'packages')))
			{
				$product_in_cart = array();
				$package_in_cart = array();
				if($_POST['type'] == 'products')
				{
					if($this->_is('products'))
					{
						$product_in_cart = $this->_get('products');
					}
					if(array_key_exists($_POST['id'], $product_in_cart))
					{
						if(is_array($product_in_cart[$_POST['id']]))
						{
							foreach($_POST['qty'][$_POST['id']] as $size_id => $qty)
							{
								if((int) $qty > 0)
								{
									$product_in_cart[$_POST['id']][$size_id] = $qty;
								}else{
									unset($product_in_cart[$_POST['id']][$size_id]);
								}
							}
							if(empty($product_in_cart[$_POST['id']]))
							{
								unset($product_in_cart[$_POST['id']]);
							}
						}else{
							if((int) $_POST['qty'][$_POST['id']] > 0)
							{
								$product_in_cart[$_POST['id']] = $_POST['qty'][$_POST['id']];
							}else{
								unset($product_in_cart[$_POST['id']]);
							}
						}
					}else{
						if(is_array($_POST['qty'][$_POST['id']]))
						{
							foreach($_POST['qty'][$_POST['id']] as $size_id => $qty)
							{
								if((int) $qty > 0)
								{
									$product_in_cart[$_POST['id']][$size_id] = $qty;
								}
							}
						}else{
							if((int) $_POST['qty'][$_POST['id']] > 0)
							{
								$product_in_cart[$_POST['id']] = $_POST['qty'][$_POST['id']];
							}
						}
					}
					
					$this->_set('products', $product_in_cart);
				}else{
					if($this->_is('packages'))
					{
						$package_in_cart = $this->_get('packages');
					}
					if(array_key_exists($_POST['id'], $package_in_cart))
					{
						if((int) $_POST['qty'][$_POST['id']] > 0)
						{
							$package_in_cart[$_POST['id']] = $_POST['qty'][$_POST['id']];
						}else{
							unset($package_in_cart[$_POST['id']]);
						}
					}else{
						$package_in_cart[$_POST['id']] = $_POST['qty'][$_POST['id']];
					}
						
					$this->_set('packages', $package_in_cart);
				}
				
				$product_in_cart = array();
				$package_in_cart = array();
				if($this->_is('products'))
				{
					$product_in_cart = $this->_get('products');
				}
				if($this->_is('packages'))
				{
					$package_in_cart = $this->_get('packages');
				}
				$cart_arr = pjAppController::getCart($product_in_cart, $package_in_cart, $this->getLocaleId(), $this->option_arr);
				
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => '', 'empty' => $cart_arr['empty'], 'subtotal' => pjUtil::formatCurrencySign(number_format($cart_arr['subtotal'], 2), $this->option_arr['o_currency'])));
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			}
			exit;
		}
	}
	public function pjActionUpdateCart()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_GET['id']) && (int) $_GET['id'] > 0 && isset($_GET['qty']) && (int) $_GET['qty'] > 0 && isset($_GET['type']) && in_array($_GET['type'], array('products', 'packages')))
			{
				if($_GET['type'] == 'products')
				{
					$product_in_cart = array();
					if($this->_is('products'))
					{
						$product_in_cart = $this->_get('products');
					}
					if(array_key_exists($_GET['id'], $product_in_cart))
					{
						if(is_array($product_in_cart[$_GET['id']]))
						{
							$product_in_cart[$_GET['id']][$_GET['size_id']] = $_GET['qty'];
						}else{
							$product_in_cart[$_GET['id']] = $_GET['qty'];
						}
					}	
					$this->_set('products', $product_in_cart);
				}else{
					$package_in_cart = array();
					if($this->_is('packages'))
					{
						$package_in_cart = $this->_get('packages');
					}
					if(array_key_exists($_GET['id'], $package_in_cart))
					{
						$package_in_cart[$_GET['id']] = $_GET['qty'];
					}
	
					$this->_set('packages', $package_in_cart);
				}
	
				$product_in_cart = array();
				$package_in_cart = array();
				if($this->_is('products'))
				{
					$product_in_cart = $this->_get('products');
				}
				if($this->_is('packages'))
				{
					$package_in_cart = $this->_get('packages');
				}
				$cart_arr = pjAppController::getCart($product_in_cart, $package_in_cart, $this->getLocaleId(), $this->option_arr);
				$this->set('cart_arr', $cart_arr);
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			}
		}
	}
	public function pjActionRemoveCart()
	{
		$this->setAjax(true);
		
		if($this->isXHR())
		{
			if (isset($_GET['id']) && (int) $_GET['id'] > 0 && isset($_GET['type']) && in_array($_GET['type'], array('products', 'packages')))
			{
				if($_GET['type'] == 'products')
				{
					$product_in_cart = array();
					if($this->_is('products'))
					{
						$product_in_cart = $this->_get('products');
					}
					if(array_key_exists($_GET['id'], $product_in_cart))
					{
						if(is_array($product_in_cart[$_GET['id']]) && isset($_GET['size_id']) && (int) $_GET['size_id'] > 0 )
						{
							unset($product_in_cart[$_GET['id']][$_GET['size_id']]);
							if(empty($product_in_cart[$_GET['id']]))
							{
								unset($product_in_cart[$_GET['id']]);
							}
						}else{
							unset($product_in_cart[$_GET['id']]);
						}
					}
					$this->_set('products', $product_in_cart);
				}else{
					$package_in_cart = array();
					if($this->_is('packages'))
					{
						$package_in_cart = $this->_get('packages');
					}
					if(array_key_exists($_GET['id'], $package_in_cart))
					{
						unset($package_in_cart[$_GET['id']]);
					}
		
					$this->_set('packages', $package_in_cart);
				}
		
				$product_in_cart = array();
				$package_in_cart = array();
				if($this->_is('products'))
				{
					$product_in_cart = $this->_get('products');
				}
				if($this->_is('packages'))
				{
					$package_in_cart = $this->_get('packages');
				}
				$cart_arr = pjAppController::getCart($product_in_cart, $package_in_cart, $this->getLocaleId(), $this->option_arr);
				if(!empty($cart_arr['product_arr']) || !empty($cart_arr['package_arr']))
				{
					$this->set('cart_arr', $cart_arr);
				}else{
					pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => ''));
				}
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			}
		}
	}
	public function pjActionMenu()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			
		}
	}
	
	public function pjActionPackages()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			$arr = pjPackageModel::factory()
				->select('t1.*, t2.content as name')
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjPackage' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
				->where('t1.status', 'T')
				->orderBy("`name` ASC")
				->findAll()
				->getData();

			$this->set('arr', $arr);
		}
	}
	
	public function pjActionProducts()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if(isset($_GET['cid']) && (int) $_GET['cid'] > 0)
			{
				$pjCategoryModel = pjCategoryModel::factory();
				$pjProductModel = pjProductModel::factory();
				
				$category = $pjCategoryModel
					->select('t1.*, t2.content as name, t3.content as description')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjCategory' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjCategory' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
					->find($_GET['cid'])
					->getData();
				
				$sub_categories = $pjCategoryModel
					->reset()
					->select('t1.*, t2.content as name')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjCategory' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->where('t1.parent_id', $_GET['cid'])
					->orderBy("t1.order ASC")
					->findAll()
					->getData();
				
				$tpp_table = pjProductPriceModel::factory()->getTable();
				$tm_table = pjMultiLangModel::factory()->getTable();
				
				$sub_arr = array();
				$main_arr = $pjProductModel
					->select("t1.*, t2.content as name, t3.content as description, 
							(SELECT GROUP_CONCAT(CONCAT_WS('~|~', TPP.id,TPP.price,TM.content) SEPARATOR '~:~') FROM `".$tpp_table."` AS `TPP` LEFT OUTER JOIN `".$tm_table."` AS TM ON (TM.foreign_id = TPP.id AND TM.model = 'pjProductPrice' AND TM.locale = '".$this->getLocaleId()."' AND TM.field = 'price_name') WHERE TPP.product_id=t1.id) AS prices")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjProduct' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjProduct' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
					->where('t1.status', 'T')
					->where("t1.category_id", $_GET['cid'])
					->where("t1.parent_category_id IS NULL")
					->orderBy("`order` ASC")
					->findAll()
					->toArray("prices", "~:~")
					->getData();
				
				if(count($sub_categories) > 0)
				{
					
					$_arr = $pjProductModel
						->reset()
						->select("t1.*, t2.content as name, t3.content as description,
							(SELECT GROUP_CONCAT(CONCAT_WS('~|~', TPP.id,TPP.price,TM.content) SEPARATOR '~:~') FROM `".$tpp_table."` AS `TPP` LEFT OUTER JOIN `".$tm_table."` AS TM ON (TM.foreign_id = TPP.id AND TM.model = 'pjProductPrice' AND TM.locale = '".$this->getLocaleId()."' AND TM.field = 'price_name') WHERE TPP.product_id=t1.id) AS prices")
						->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjProduct' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
						->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjProduct' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
						->where('t1.status', 'T')
						->where("t1.parent_category_id", $_GET['cid'])
						->orderBy("`order` ASC")
						->findAll()
						->toArray("prices", "~:~")
						->getData();
					
					foreach($_arr as $v)
					{
						if(!empty($v['category_id']))
						{
							$sub_arr[$v['category_id']][] = $v;
						}
					}
				}
				
				$this->set('main_arr', $main_arr);
				$this->set('sub_arr', $sub_arr);
				$this->set('category', $category);
				$this->set('sub_categories', $sub_categories);
			}
		}
	}
	
	public function pjActionPackage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if(isset($_GET['package_id']) && (int) $_GET['package_id'] > 0)
			{
				$arr = pjPackageModel::factory()
					->select('t1.*, t2.content as name, t3.content as description')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjPackage' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjPackage' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
					->find($_GET['package_id'])
					->getData();
				
				$product_arr = pjProductModel::factory()
					->select("t1.*, t2.content as name, t3.content as description, t4.content as category, t5.qty, t6.content as price_name")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjProduct' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjProduct' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
					->join('pjMultiLang', "t4.foreign_id = t1.category_id AND t4.model = 'pjCategory' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'name'", 'left')
					->join('pjPackageProduct', "t1.id=t5.product_id", 'left')
					->join('pjMultiLang', "t6.foreign_id = t5.size_id AND t6.model = 'pjProductPrice' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'price_name'", 'left')
					->where("t1.id IN (SELECT t4.product_id FROM `".pjPackageProductModel::factory()->getTable()."` AS t4 WHERE t4.package_id = '".$_GET['package_id']."')")
					->where("(t5.package_id = '".$arr['id']."')")
					->where('t1.status', 'T')
					->orderBy("`name` ASC")
					->findAll()
					->getData();
				
				$this->set('arr', $arr);
				$this->set('product_arr', $product_arr);
			}
		}
	}
	public function pjActionCheckout()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if(isset($_POST['cs_checkout']))
			{
				$_SESSION[$this->defaultForm] = $_POST;
			
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200));
			}else{
				$product_arr = array();
				$package_arr = array();
				
				$product_in_cart = array();
				$package_in_cart = array();
				if($this->_is('products'))
				{
					$product_in_cart = $this->_get('products');
				}
				if($this->_is('packages'))
				{
					$package_in_cart = $this->_get('packages');
				}
	
				$country_arr = pjCountryModel::factory()
					->select('t1.id, t2.content AS country_title')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('`country_title` ASC')
					->findAll()
					->getData();
				
				$_terms_conditions = pjMultiLangModel::factory()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_terms')
					->limit(0, 1)
					->findAll()->getData();
				$terms_conditions = '';
				if(!empty($_terms_conditions))
				{
					$terms_conditions = $_terms_conditions[0]['content'];
				}
				
				$cart_arr = pjAppController::getCart($product_in_cart, $package_in_cart, $this->getLocaleId(), $this->option_arr);
				
				$this->set('cart_arr', $cart_arr);
				$this->set('country_arr', $country_arr);
				$this->set('terms_conditions', $terms_conditions);
			}
		}
	}
	public function pjActionPreview()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_SESSION[$this->defaultStore]) &&
					count($_SESSION[$this->defaultStore]) > 0 &&
					(isset($_SESSION[$this->defaultStore]['products']) || isset($_SESSION[$this->defaultStore]['packages'])))
			{
				$product_arr = array();
				$package_arr = array();
				
				$product_in_cart = array();
				$package_in_cart = array();
				if($this->_is('products'))
				{
					$product_in_cart = $this->_get('products');
				}
				if($this->_is('packages'))
				{
					$package_in_cart = $this->_get('packages');
				}
				$cart_arr = pjAppController::getCart($product_in_cart, $package_in_cart, $this->getLocaleId(), $this->option_arr);
				
				if(isset($_SESSION[$this->defaultForm]['c_country']) && (int) $_SESSION[$this->defaultForm]['c_country'] > 0)
				{
					$country_arr = pjCountryModel::factory()
						->select('t1.id, t2.content AS country_title')
						->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->find($_SESSION[$this->defaultForm]['c_country'])
						->getData();
					$this->set('country_arr', $country_arr);
				}
				
				$this->set('cart_arr', $cart_arr);
				
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				exit;
			}
		}
	}
	public function pjActionSaveOrder()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_POST['cs_preview']) || !isset($_SESSION[$this->defaultForm]) || empty($_SESSION[$this->defaultForm]) || !isset($_SESSION[$this->defaultStore]) || empty($_SESSION[$this->defaultStore]))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 109));
			}
			if ((int) $this->option_arr['o_bf_include_captcha'] === 3 && (!isset($_SESSION[$this->defaultForm]['captcha']) ||
					!pjCaptcha::validate($_SESSION[$this->defaultForm]['captcha'], $_SESSION[$this->defaultCaptcha]) ))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 110));
			}
	
			$STORE = @$_SESSION[$this->defaultStore];
			$FORM = @$_SESSION[$this->defaultForm];
	
			$delivery_date_arr = pjUtil::convertDateTime($FORM['delivery_date'] . ' ' . $FORM['delivery_time'], $this->option_arr['o_date_format'], 'h:i A');
			
			$product_in_cart = array();
			$package_in_cart = array();
			if($this->_is('products'))
			{
				$product_in_cart = $this->_get('products');
			}
			if($this->_is('packages'))
			{
				$package_in_cart = $this->_get('packages');
			}
			$cart_arr = pjAppController::getCart($product_in_cart, $package_in_cart, $this->getLocaleId(), $this->option_arr);
			
			$data = array();
	
			$data['uuid'] = time();
			$data['delivery_dt'] = $delivery_date_arr['iso_date_time'];
			
			$data['subtotal'] = $cart_arr['subtotal'];
			$data['tax'] = $cart_arr['tax'];
			$data['total'] = $cart_arr['total'];
			$data['deposit'] = $cart_arr['deposit'];
			
			$data['ip'] = pjUtil::getClientIp();
			$data['status'] = $this->option_arr['o_booking_status'];
			$data['created'] = date('Y-m-d H:i:s');
			$payment = ':NULL';
			if(isset($FORM['payment_method']))
			{
				$payment = $FORM['payment_method'];
				if($payment != 'creditcard')
				{
					$data['cc_exp_month'] = '';
					$data['cc_exp_year'] = '';
				}
			}
						
			$pjOrderModel = pjOrderModel::factory();
			$id = $pjOrderModel->setAttributes(array_merge($FORM, $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				$pjOrderProductModel = pjOrderProductModel::factory();
				
				$product_arr = $cart_arr['product_arr'];
				$package_arr = $cart_arr['package_arr'];
				foreach($product_arr as $k => $product)
				{
					if($product['set_different_sizes'] == 'T')
					{
						if(is_array($product['prices']))
						{
							foreach($product['prices'] as $price)
							{
								list($pid, $p, $p_name) = explode("~|~", $price);
								if(isset($product_in_cart[$product['id']][$pid]) && (int) $product_in_cart[$product['id']][$pid] > 0)
								{
									$op_data = array();
									$op_data['order_id'] = $id;
									$op_data['type'] = 'products';
									$op_data['product_id'] = $product['id'];
									$op_data['package_id'] = ':NULL';
									$op_data['size_id'] = $pid;
									$op_data['unit_price'] = $p;
									$op_data['qty'] = $product_in_cart[$product['id']][$pid];
									$op_data['price'] = $product_in_cart[$product['id']][$pid] * $p;
									$pjOrderProductModel->reset()->setAttributes($op_data)->insert();
								}
							}
						}
					}else{
						$op_data = array();
						$op_data['order_id'] = $id;
						$op_data['type'] = 'products';
						$op_data['product_id'] = $product['id'];
						$op_data['package_id'] = ':NULL';
						$op_data['size_id'] = ':NULL';
						$op_data['unit_price'] = $product['price'];
						$op_data['qty'] = $product_in_cart[$product['id']];
						$op_data['price'] = $product_in_cart[$product['id']] * $product['price'];
						$pjOrderProductModel->reset()->setAttributes($op_data)->insert();
					}
				}
				foreach($package_arr as $k => $package)
				{
					$op_data = array();
					$op_data['order_id'] = $id;
					$op_data['type'] = 'packages';
					$op_data['product_id'] = ":NULL";
					$op_data['package_id'] = $package['id'];
					$op_data['size_id'] = ':NULL';
					$op_data['unit_price'] = $package['price'];
					$op_data['qty'] = $package_in_cart[$package['id']];
					$op_data['price'] = $package_in_cart[$package['id']] * $package['price'];
					$pjOrderProductModel->reset()->setAttributes($op_data)->insert();
				}
				
				$arr = $pjOrderModel->reset()->find($id)->getData();
	
				$pdata = array();
				$pdata['order_id'] = $id;
				$pdata['payment_method'] = $payment;
				$pdata['payment_type'] = 'online';
				$pdata['amount'] = $arr['deposit'];
				$pdata['status'] = 'notpaid';
				pjOrderPaymentModel::factory()->setAttributes($pdata)->insert();
	
				pjFront::pjActionConfirmSend($this->option_arr, $arr, PJ_SALT, 'confirm');
	
				unset($_SESSION[$this->defaultStore]);
				unset($_SESSION[$this->defaultForm]);
	
				$json = array('code' => 200, 'text' => '', 'order_id' => $id, 'payment' => $payment);
				pjAppController::jsonResponse($json);
			}else {
				pjAppController::jsonResponse(array('code' => 'ERR', 'code' => 119));
			}
		}
	}
	public function pjActionCancel()
	{
		$this->setLayout('pjActionCancel');
	
		$pjOrderModel = pjOrderModel::factory();
	
		if (isset($_POST['order_cancel']))
		{
			$order_arr = $pjOrderModel->find($_POST['id'])->getData();
			if (count($order_arr) > 0)
			{
				$sql = "UPDATE `".$pjOrderModel->getTable()."` SET status = 'cancelled' WHERE SHA1(CONCAT(`id`, `created`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
	
				$pjOrderModel->reset()->execute($sql);
	
				pjFront::pjActionConfirmSend($this->option_arr, $order_arr, PJ_SALT, 'cancel');
	
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjFront&action=pjActionCancel&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = $pjOrderModel->find($_GET['id'])->getData();
				if (count($arr) == 0)
				{
					$this->set('status', 2);
				}else{
					if ($arr['status'] == 'cancelled')
					{
						$this->set('status', 4);
					}else{
						$hash = sha1($arr['id'] . $arr['created'] . PJ_SALT);
						if ($_GET['hash'] != $hash)
						{
							$this->set('status', 3);
						}else{
							$locale_id = $this->getLocaleId();
							$pjOrderProductModel = pjOrderProductModel::factory();
							$order_product_arr = $pjOrderProductModel
								->select('t1.*, t2.content AS product_name, t3.content AS price_name')
								->join('pjMultiLang', "t2.model='pjProduct' AND t2.foreign_id=t1.product_id AND t2.field='name' AND t2.locale='".$locale_id."'", 'left outer')
								->join('pjMultiLang', "t3.model='pjProductPrice' AND t3.foreign_id=t1.size_id AND t3.field='price_name' AND t3.locale='".$locale_id."'", 'left outer')
								->where('t1.type', 'products')
								->where('t1.order_id', $arr['id'])
								->findAll()
								->getData();
							$order_package_arr = $pjOrderProductModel
								->reset()
								->select('t1.*, t2.content AS package_name')
								->join('pjMultiLang', "t2.model='pjPackage' AND t2.foreign_id=t1.package_id AND t2.field='name' AND t2.locale='".$locale_id."'", 'left outer')
								->where('t1.type', 'packages')
								->where('t1.order_id', $arr['id'])
								->findAll()
								->getData();
							$country = '';
							$country_arr = pjCountryModel::factory()
								->select('t1.id, t2.content AS country_title')
								->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$locale_id."'", 'left outer')
								->find($arr['c_country'])
								->getData();
							if (!empty($country_arr))
							{
								$country = $country_arr['country_title'];
							}
							
							$this->set('arr', $arr);
							$this->set('country', $country);
							$this->set('order_product_arr', $order_product_arr);
							$this->set('order_package_arr', $order_package_arr);
						}
					}
				}
			}else if (!isset($_GET['err'])) {
				$this->set('status', 1);
			}
		}
	}
	
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjOrderModel::factory()->find($_GET['order_id'])->getData();
				
			if (!empty($arr))
			{
				switch ($arr['payment_method'])
				{
					case 'paypal':
						$this->set('params', array(
							'name' => 'csPaypal',
							'id' => 'csPaypal',
							'business' => $this->option_arr['o_paypal_address'],
							'item_name' => pjSanitize::html($arr['uuid']),
							'custom' => $arr['id'],
							'amount' => $arr['deposit'],
							'currency_code' => $this->option_arr['o_currency'],
							'return' => $this->option_arr['o_thankyou_page'],
							'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionConfirmPaypal',
							'target' => '_self',
							'charset' => 'utf-8'
						));
						break;
					case 'authorize':
						$this->set('params', array(
							'name' => 'csAuthorize',
							'id' => 'csAuthorize',
							'target' => '_self',
							'timezone' => $this->option_arr['o_authorize_timezone'],
							'transkey' => $this->option_arr['o_authorize_transkey'],
							'x_login' => $this->option_arr['o_authorize_merchant_id'],
							'x_description' => pjSanitize::html($arr['uuid']),
							'x_amount' => $arr['deposit'],
							'x_invoice_num' => $arr['id'],
							'x_receipt_link_url' => $this->option_arr['o_thankyou_page'],
							'x_relay_url' => PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionConfirmAuthorize'
						));
						break;
				}
			}
			$this->set('arr', $arr);
			$this->set('get', $_GET);
		}
	}
	
	public function pjActionConfirmAuthorize()
	{
		$this->setAjax(true);
	
		if (pjObject::getPlugin('pjAuthorize') === NULL)
		{
			$this->log('Authorize.NET plugin not installed');
			exit;
		}
		$pjOrderModel = pjOrderModel::factory();
	
		$order_arr = $pjOrderModel
			->find($_POST['x_invoice_num'])
			->getData();
		if (count($order_arr) == 0)
		{
			$this->log('No such order');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}
	
		if (count($order_arr) > 0)
		{
			$params = array(
					'transkey' => $this->option_arr['o_authorize_transkey'],
					'x_login' => $this->option_arr['o_authorize_merchant_id'],
					'md5_setting' => $this->option_arr['o_authorize_md5_hash'],
					'key' => md5($this->option_arr['private_key'] . PJ_SALT)
			);
				
			$response = $this->requestAction(array('controller' => 'pjAuthorize', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
			if ($response !== FALSE && $response['status'] === 'OK')
			{
				$pjOrderModel->reset()
					->setAttributes(array('id' => $response['transaction_id']))
					->modify(array('status' => $this->option_arr['o_payment_status'], 'processed_on' => ':NOW()'));
	
				pjOrderPaymentModel::factory()
					->setAttributes(array('order_id' => $response['transaction_id'], 'payment_type' => 'online'))
					->modify(array('status' => 'paid'));
					
				pjFront::pjActionConfirmSend($this->option_arr, $order_arr, PJ_SALT, 'payment');
	
			} elseif (!$response) {
				$this->log('Authorization failed');
			} else {
				$this->log('Booking not confirmed. ' . $response['response_reason_text']);
			}
			?>
			<script type="text/javascript">window.location.href="<?php echo $this->option_arr['o_thankyou_page']; ?>";</script>
			<?php
			return;
		}
	}
	
	public function pjActionConfirmPaypal()
	{
		$this->setAjax(true);
	
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			exit;
		}
		$pjOrderModel = pjOrderModel::factory();
	
		$order_arr = $pjOrderModel
			->find($_POST['custom'])
			->getData();
		if (count($order_arr) == 0)
		{
			$this->log('No such order');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}
	
		$params = array(
				'txn_id' => @$order_arr['txn_id'],
				'paypal_address' => $this->option_arr['o_paypal_address'],
				'deposit' => @$order_arr['deposit'],
				'currency' => $this->option_arr['o_currency'],
				'key' => md5($this->option_arr['private_key'] . PJ_SALT)
		);
		$response = $this->requestAction(array('controller' => 'pjPaypal', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
	
		if ($response !== FALSE && $response['status'] === 'OK')
		{
			$this->log('Order confirmed');
			$pjOrderModel->reset()->setAttributes(array('id' => $order_arr['id']))->modify(array(
					'status' => $this->option_arr['o_payment_status'],
					'txn_id' => $response['transaction_id'],
					'processed_on' => ':NOW()'
			));
			pjOrderPaymentModel::factory()
				->setAttributes(array('order_id' => $order_arr['id'], 'payment_type' => 'online'))
				->modify(array('status' => 'paid'));
				
			pjFront::pjActionConfirmSend($this->option_arr, $order_arr, PJ_SALT, 'payment');
				
		} elseif (!$response) {
			$this->log('Authorization failed');
		} else {
			$this->log('Booking not confirmed');
		}
		pjUtil::redirect($this->option_arr['o_thankyou_page']);
	}
	
	public function pjActionConfirmSend($option_arr, $order_arr, $salt, $opt)
	{
		$Email = new pjEmail();
		if ($option_arr['o_send_email'] == 'smtp')
		{
			$Email
				->setTransport('smtp')
				->setSmtpHost($option_arr['o_smtp_host'])
				->setSmtpPort($option_arr['o_smtp_port'])
				->setSmtpUser($option_arr['o_smtp_user'])
				->setSmtpPass($option_arr['o_smtp_pass'])
			;
		}
		$Email->setContentType('text/html');
	
		$admin_email = $this->getAdminEmail();
		$admin_phone = $this->getAdminPhone();
		$admin_emails = $this->getAllEmails();
		$admin_phones = $this->getAllPhones();
		
		$from_email = $admin_email;
	
		$locale_id = $this->getLocaleId();
	
		$tokens = pjAppController::getTokens($order_arr, $option_arr, PJ_SALT, $locale_id);
	
		$pjMultiLangModel = pjMultiLangModel::factory();
	
		if ($option_arr['o_email_payment'] == 1 && $opt == 'payment')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_payment_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($order_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if ($option_arr['o_admin_email_payment'] == 1 && $opt == 'payment' && !empty($admin_emails))
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_payment_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				foreach($admin_emails as $email)
				{
					$Email
					->setTo($email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
				}
			}
		}
		if(!empty($admin_phones) && $opt == 'payment')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_sms_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				if($message != '')
				{
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($option_arr['private_key'] . PJ_SALT)
					);
					foreach($admin_phones as $phone)
					{
						$params['number'] = $phone;
						$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
					}
				}
			}
		}
	
		if ($option_arr['o_email_confirmation'] == 1 && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_confirmation_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
					
				$Email
					->setTo($order_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if ($option_arr['o_admin_email_confirmation'] == 1 && $opt == 'confirm' && !empty($admin_emails))
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_confirmation_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				
				foreach($admin_emails as $email)
				{
					$Email
					->setTo($email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
				}
			}
		}
		if(!empty($order_arr['c_phone']) && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_sms_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				if($message != '')
				{
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $order_arr['c_phone'];
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
		}
		if(!empty($admin_phones) && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_sms_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				if($message != '')
				{
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($option_arr['private_key'] . PJ_SALT)
					);
					foreach($admin_phones as $phone)
					{
						$params['number'] = $phone;
						$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
					}
				}
			}
		}
	
		if ($option_arr['o_email_cancel'] == 1 && $opt == 'cancel')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_cancel_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_cancel_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($order_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if ($option_arr['o_admin_email_cancel'] == 1 && $opt == 'cancel' && !empty($admin_emails))
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_cancel_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_cancel_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				foreach($admin_emails as $email)
				{
					$Email
						->setTo($email)
						->setFrom($from_email)
						->setSubject($lang_subject[0]['content'])
						->send(pjUtil::textToHtml($message));
				}
			}
		}
	}
	
	
	public function isXHR()
	{
		return parent::isXHR() || isset($_SERVER['HTTP_ORIGIN']);
	}
	
	static protected function allowCORS()
	{
		$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
		header('P3P: CP="ALL DSP COR CUR ADM TAI OUR IND COM NAV INT"');
		header("Access-Control-Allow-Origin: $origin");
		header("Access-Control-Allow-Credentials: true");
		header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
		header("Access-Control-Allow-Headers: Origin, X-Requested-With");
	}
}
?>