<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{	
	public $defaultCaptcha = 'pjSugPrice_Captcha';
	
	public $defaultLocale = 'pjSugPrice_LocaleId';
	
	public $defaultLangMenu = 'pjSugPrice_LangMenu';
		
	public $defaultForm = 'pjSugPrice_Form';
	
	public $defaultProduct = 'pjSugPrice_Product';
	
	public function __construct()
	{
		$this->setLayout('pjActionFront');
		self::allowCORS();
	}

	public function isXHR()
	{
		return parent::isXHR() || isset($_SERVER['HTTP_ORIGIN']);
	}
	
	static protected function allowCORS()
	{
		$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
		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");
	}
	
	public function afterFilter()
	{		
		
	}
	
	public function beforeFilter()
	{
		$OptionModel = pjOptionModel::factory();
		$this->option_arr = $OptionModel->getPairs($this->getForeignId());
		$this->set('option_arr', $this->option_arr);
		$this->setTime();

		if (!isset($_SESSION[$this->defaultLocale]))
		{
			$locale_arr = pjLocaleModel::factory()->where('is_default', 1)->limit(1)->findAll()->getData();
			if (count($locale_arr) === 1)
			{
				$this->setLocaleId($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);
		header("Cache-Control: max-age=3600, private");
		$Captcha = new pjCaptcha(PJ_WEB_PATH.'obj/Anorexia.ttf', $this->defaultCaptcha, 6);
		$Captcha->setImage(PJ_IMG_PATH.'button.png')->init(isset($_GET['rand']) ? $_GET['rand'] : null);
		exit;
	}

	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()
	{
		$theme = isset($_GET['theme']) ? $_GET['theme'] : $this->option_arr['o_theme'];
		if((int) $theme > 0)
		{
			$theme = 'theme' . $theme;
		}
		$arr = array(
			array('file' => 'css?family=Open+Sans:400,600,700', 'path' => "https://fonts.googleapis.com/"),
			array('file' => 'pjMakeOffer.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('../images/', 'images/'),
					array(
						PJ_INSTALL_URL . PJ_IMG_PATH . 'frontend/',
						PJ_INSTALL_URL . PJ_IMG_PATH . 'frontend/'
					),
					$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
		
		$status = 'OK';
		if(isset($_GET['product_id']))
		{
			$arr = pjProductModel::factory()->find($_GET['product_id'])->getData();
			if(!empty($arr))
			{
				if($arr['status'] == 'T')
				{
					$_SESSION[$this->defaultProduct] = $arr;
				}else{
					$status = 'ERR';
				}
			}else{
				$status = 'ERR';
			}
		}else{
			$status = 'ERR';
		}
		if($status == 'ERR' && isset($_SESSION[$this->defaultProduct]))
		{
			unset($_SESSION[$this->defaultProduct]);
		}
	}
	
	public function pjActionForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if(isset($_SESSION[$this->defaultProduct]) && !empty($_SESSION[$this->defaultProduct]))
			{
				$this->set('status', 'OK');
			}else{
				$this->set('status', 'ERR');
			}
		}
	}
	
	public function pjActionSave()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			$response = array();
				
			if (isset($_POST['price']))
			{
				$data = array();
				$product = $_SESSION[$this->defaultProduct];
				
				$price = $_POST['price'];
				
				$opt = 1;
				$action = '';
				$message = '';
				
				$range_1 = $product['price'] * 0 / 100;
				$range_2 = $product['price'] * 33.33 / 100;
				$range_3 = $range_2 + 0.01;
				$range_4 = $product['price'] * 66.66 / 100;
				$range_5 = $range_4 + 0.01;
				$range_6 = $product['price'] * 100 / 100;
				
				switch ($product['suggest_type']) {
					case 'suggest':
						if($price >= $range_1 && $price <= $range_2)
						{
							$opt = 1;
						}else if($price >= $range_3 && $price <= $range_4){
							$opt = 2;
						}else if($price >= $range_5 && $price <= $range_6){
							$opt = 3;
						}
						$action = $product['price_range_'.$opt.'_action'];
						
					break;
					case 'offer':
						if($price == $product['price_suggest_1'])
						{
							$opt = 1;
						}
						if($price == $product['price_suggest_2'])
						{
							$opt = 2;
						}
						if($price == $product['price_suggest_3'])
						{
							$opt = 3;
						}
						$action = $product['price_suggest_'.$opt.'_action'];
						break;
				}
				
				$data['product_id'] = $product['id'];
				$data['price'] = $price;
				$data['price_option'] = $opt;
				$data['ip'] = pjUtil::getClientIp();
				$data['type'] = $action;
				
				if($action == 'email')
				{
					if($action == 'thank')
					{
						$action = 'message';
					}
					$_SESSION[$this->defaultForm] = $data;
					if($product['suggest_type'] == 'suggest')
					{
						$message =  $product['price_range_'.$opt.'_' . $action];
					}else{
						$message =  $product['price_suggest_'.$opt.'_' . $action];
					}
					$response['code'] = 201;
				}else{
					$data['promo_code'] = ':NULL';
					$data['thankyou_message'] = ':NULL';
					if($action == 'thank')
					{
						$action = 'message';
					}
					if($product['suggest_type'] == 'suggest')
					{
						$message =  $product['price_range_'.$opt.'_' . $action];
					}else{
						$message =  $product['price_suggest_'.$opt.'_' . $action];
					}
					if($data['type'] == 'thank')
					{
						$data['thankyou_message'] = $message;
					}else{
						$data['promo_code'] = $message;
					}
					$id = pjOfferModel::factory($data)->insert()->getInsertId();
					pjFront::pjActionConfirmSend($this->option_arr, $product, $data['price']);
					$response['offer_id'] = $id;
					$response['code'] = 200;
				}
				$response['opt'] = $opt;
				$response['message'] = $message;
				$response['data'] = $data;
			} else {
				$response['code'] = 100;
			}
				
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionSaveEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			$response = array();
	
			if (isset($_POST['email']))
			{
				$data = array();
				$data = $_SESSION[$this->defaultForm];
				$data['email'] = $_POST['email'];
	
				$id = pjOfferModel::factory($data)->insert()->getInsertId();
				$product = $_SESSION[$this->defaultProduct];
				unset($_SESSION[$this->defaultForm]);
				
				pjFront::pjActionConfirmSend($this->option_arr, $product, $data['price']);
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
	
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionConfirmSend($option_arr, $product, $price)
	{
		$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'])
				->setSender($option_arr['o_smtp_user'])
			;
		}
		
		$Email->setContentType('text/html');
	
		$admin_email = $this->getAdminEmail();
		$admin_phone = $this->getAdminPhone();
		$from_email = $admin_email;
		
		$search = array('{Product}','{PriceOffer}');
		$replace = array(@$product['name'], pjUtil::formatCurrencySign($price, $option_arr['o_currency']));
		$tokens = compact('search', 'replace');
		
		if (!empty($admin_email) && !empty($option_arr['o_admin_email_confirmation_subject']) && !empty($option_arr['o_admin_email_confirmation_message']))
		{
			$subject = str_replace($tokens['search'], $tokens['replace'], $option_arr['o_admin_email_confirmation_subject']);
			$message = str_replace($tokens['search'], $tokens['replace'], $option_arr['o_admin_email_confirmation_message']);
			
			$Email
				->setTo($admin_email)
				->setFrom($from_email)
				->setSubject($subject)
				->send($message);
		}
		if(!empty($admin_phone) && !empty($option_arr['o_admin_sms_confirmation_message']))
		{
			$message = str_replace($tokens['search'], $tokens['replace'], $option_arr['o_admin_sms_confirmation_message']);
			$params = array(
					'number' => $admin_phone,
					'text' => $message,
					'type' => 'unicode',
					'key' => md5($option_arr['private_key'] . PJ_SALT)
			);
			$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
		}
	}
}
?>