<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{
	public $defaultCaptcha = 'StivaSoftCaptcha';
	
	public $defaultLocale = 'front_locale_id';
	
	public $defaultRater = 'front_rater';
	
	public $defaultThread = 'front_thread_id';
	
	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");
		header('P3P: CP="ALL DSP COR CUR ADM TAI OUR IND COM NAV INT"');
		
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
		{
			exit;
		}
	}

	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 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';
		}
	}
	
	public function pjActionSetLocale()
	{
		$this->setLocaleId(@$_GET['locale']);
		pjUtil::redirect($_SERVER['HTTP_REFERER']);
	}
	
	public function pjActionLoadCss()
	{
		$theme = isset($_GET['theme']) ? $_GET['theme'] : $this->option_arr['o_theme'];
		if((int) $theme > 0)
		{
			$theme = 'theme' . $theme;
		}
		$dm = new pjDependencyManager(PJ_INSTALL_PATH, PJ_THIRD_PARTY_PATH);
		$dm->load(PJ_CONFIG_PATH . 'dependencies.php')->resolve();
		$arr = array(
			array('file' => 'jquery-ui.custom.min.css', 'path' => $dm->getPath('pj_jquery_ui') . 'css/smoothness/'),
			array('file' => 'jquery-ui-timepicker-addon.css', 'path' => $dm->getPath('pj_datetimepicker') ),
			array('file' => 'css?family=Open+Sans:400,600,700', 'path' => "https://fonts.googleapis.com/"),
			array('file' => 'pjCallbackWidget.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]/', 'images/ui'),
					array(
						PJ_INSTALL_URL . PJ_IMG_PATH . 'frontend/',
						PJ_INSTALL_URL . PJ_IMG_PATH . 'frontend/',
						PJ_INSTALL_URL . $dm->getPath('pj_jquery_ui') . 'css/smoothness/images/ui',
					),
					$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			$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();
			$reason_arr = pjReasonModel::factory()
				->select("t1.*")
				->where('t1.status', 'T')
				->orderBy("t1.reason ASC")
				->findAll()
				->getData();
			
			$o_arr = pjOptionModel::factory()
				->where('t1.foreign_id', $this->getForeignId())
				->where('`key`', 'o_timezone')
				->orderBy('t1.key ASC')
				->findAll()
				->getData();
			
			$this->set('country_arr', $country_arr);
			$this->set('reason_arr', $reason_arr);
			$this->set('timezone_arr', $o_arr[0]);
		}
	}
	
	public function pjActionSave()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			$response = array();
			
			$data = array();

			$datetime_arr = pjUtil::convertDateTime($_POST['besttime'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			
			$call_timezone = $_POST['timezone'];
			$script_timezone = $this->option_arr['o_timezone'];
			
			if($datetime_arr != false)
			{
				$best_ts = $datetime_arr['ts'];
				if($call_timezone > $script_timezone)
				{
					$best_ts = $best_ts - ($call_timezone - $script_timezone);
				}else if($call_timezone < $script_timezone){
					$best_ts = $best_ts + ($script_timezone - $call_timezone);
				}
				$data['besttime'] = $datetime_arr['iso_date_time'];
				if($best_ts <= time())
				{
					$data['actual_besttime'] = date('Y-m-d H:i:s', $best_ts + 24*60*60);
				}else{
					$data['actual_besttime'] = date('Y-m-d H:i:s', $best_ts);
				}
			}else{
				$data['besttime'] = ':NULL';
				$data['actual_besttime'] = ':NULL';
			}
			$data['ip'] = pjUtil::getClientIp();
			$data['created'] =  date('Y-m-d H:i:s', time());

			$id = pjRequestModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				$arr = pjRequestModel::factory()
					->select('t1.*, t2.reason, t3.content as country')
					->join('pjReason', 't1.reason_id=t2.id', 'left')
					->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.country_id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
					->find($id)
					->getData();
				$timezone = null;
				if(!empty($data['timezone']))
				{
					$timezone = $data['timezone']/3600;
					if($timezone > 0)
					{
						$timezone = '+' . str_pad($timezone, 2, '0', STR_PAD_LEFT) . ':00';
					}else if($timezone < 0){
						$timezone = '-' . str_pad($timezone, 2, '0', STR_PAD_LEFT) . ':00';
					}else{
						$timezone = '';
					}
					$timezone = 'GMT' . $timezone;
				}
				pjFront::pjActionConfirmSend($this->option_arr, $arr);
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionConfirmSend($option_arr, $arr)
	{
		$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_arr = $this->getAdminEmails();
		$admin_phone = $this->getAdminPhone();
		$from_email = $this->getFromEmail();
		
		$tokens = pjAppController::getTokens($arr, $option_arr);
	
		if (!empty($arr['email']) && !empty($option_arr['o_email_request_subject']) && !empty($option_arr['o_email_request_message']))
		{
			$subject = $option_arr['o_email_request_subject'];
			$message = str_replace($tokens['search'], $tokens['replace'], $option_arr['o_email_request_message']);
			$Email
				->setTo($arr['email'])
				->setFrom($from_email)
				->setSubject($subject)
				->send($message);
		}
		if(!empty($arr['phone']) && !empty($option_arr['o_sms_request_message']))
		{
			$message = str_replace($tokens['search'], $tokens['replace'], $option_arr['o_sms_request_message']);
			$params = array(
					'text' => $message,
					'type' => 'unicode',
					'key' => md5($option_arr['private_key'] . PJ_SALT)
			);
			$params['number'] = $arr['phone'];
			$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
		}
		if (!empty($option_arr['o_admin_email_request_subject']) && !empty($option_arr['o_admin_email_request_message']))
		{
			$subject = $option_arr['o_admin_email_request_subject'];
			$message = str_replace($tokens['search'], $tokens['replace'], $option_arr['o_admin_email_request_message']);
			foreach($admin_email_arr as $admin_email)
			{
				$Email
					->setTo($admin_email)
					->setFrom($from_email)
					->setSubject($subject)
					->send($message);
			}
		}
		if(!empty($admin_phone) && !empty($option_arr['o_sms_email_request_message']))
		{
			$message = str_replace($tokens['search'], $tokens['replace'], $option_arr['o_sms_email_request_message']);
			$params = array(
					'text' => $message,
					'type' => 'unicode',
					'key' => md5($option_arr['private_key'] . PJ_SALT)
			);
			$params['number'] = $admin_phone;
			$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
		}
	}
}
?>