<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{
	public $defaultCaptcha = 'PHPJabbersCaptcha';
	
	public $defaultLocale = 'front_locale_id';
	
	public function __construct()
	{
		$this->setLayout('pjActionFrontJS');
		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"');
	}
	
	public function pjActionGetLocale()
	{
		return isset($_SESSION[$this->defaultLocale]) && (int) $_SESSION[$this->defaultLocale] > 0 ? (int) $_SESSION[$this->defaultLocale] : FALSE;
	}
	
	public function afterFilter()
	{
		$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
			->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);
	}
	
	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);
		$this->setLayout('pjActionEmpty');
		header("Cache-Control: max-age=3600, private");
		$pjCaptcha = new pjCaptcha(PJ_WEB_PATH . 'obj/Anorexia.ttf', $this->defaultCaptcha . @$_GET['group_id'], 6);
		$pjCaptcha->setImage(PJ_IMG_PATH . 'button.png')->init(@$_GET['rand']);
		exit;
	}

	public function pjActionCheckCaptcha()
	{
		$this->setAjax(true);
		if (!isset($_POST['captcha']) || empty($_POST['captcha']) || strtoupper($_POST['captcha']) != $_SESSION[$this->defaultCaptcha . @$_POST['group_id']]){
			echo 'false';
		}else{
			echo 'true';
		}
		exit;
	}
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
		if ($this->isXHR())
		{
		    if (!isset($_POST['email']) || empty($_POST['email']))
			{
				echo 'false';
				exit;
			}
			$pjSubscriberModel = pjSubscriberModel::factory()->where('t1.email', $_POST['email']);
			if(isset($_POST['group_id']) && (int) $_POST['group_id'] > 0)
			{
			    $pjSubscriberModel->where(sprintf("(t1.id IN (SELECT `TGS`.`subscriber_id` FROM `%s` AS `TGS` WHERE `TGS`.`group_id`='%u'))", pjGroupSubscriberModel::factory()->getTable(), $_POST['group_id']));
			}
			echo $pjSubscriberModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		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' => 'front.css', 'path' => PJ_CSS_PATH),
			array('file' => "$theme.css", 'path' => PJ_CSS_PATH)
		);
		header("Content-Type: text/css; charset=utf-8");
		foreach ($arr as $item)
		{
			$string = FALSE;
			if ($stream = fopen($item['path'] . $item['file'], 'rb'))
			{
				$string = stream_get_contents($stream);
				fclose($stream);
			}
			if ($string !== FALSE)
			{
				echo str_replace(
					array('../img/', "pjWrapper"),
					array(
						PJ_INSTALL_URL . PJ_IMG_PATH,
						"pjWrapperNewsletter_" . $theme
					),
					$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoadForm()
	{
		if(isset($_GET['group_id']) && (int) $_GET['group_id'] > 0)
		{
			$group_id = $_GET['group_id'];
			
			$arr = pjGroupModel::factory()->find($group_id)->getData();
			$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();
			$this->set('arr', $arr);
			$this->set('country_arr', $country_arr);
		}else{
			$group_arr = pjGroupModel::factory()
				->where('status', 'T')
				->orderBy('group_title ASC')
				->findAll()
				->getData();
				
			$this->set('group_arr', $group_arr);
		}
	}
	
	public function pjActionLoadField()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['group_id']) && (int) $_GET['group_id'] > 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')
					->orderBy('`country_title` ASC')->findAll()->getData();
				$group_id = $_GET['group_id'];
				$arr = pjGroupModel::factory()->find($group_id)->getData();
				$this->set('arr', $arr);
				$this->set('country_arr', $country_arr);
			}
		}
	}
	
	public function pjActionFormSave()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$code = 100;
			
			if(isset($_POST['group_id']) && (int) $_POST['group_id'] > 0)
			{
				if(!isset($_POST['captcha']))
				{
					$code = 201;
				}
				if (isset($_POST['captcha']) && !pjValidation::pjActionNotEmpty($_POST['captcha']))
				{
					$code = 202;
				}
				if ($_SESSION[$this->defaultCaptcha . $_POST['group_id']] == "" || $_POST['captcha'] == "" || strtoupper($_POST['captcha']) != $_SESSION[$this->defaultCaptcha . $_POST['group_id']])
				{
					$code = 203;
				}
				
				$group_arr = pjGroupModel::factory()->find($_POST['group_id'])->getData();
				$subscribed_fields = explode(',', $group_arr['subscribed_fields']);
				
				if(in_array('first_name', $subscribed_fields))
				{
					if(!isset($_POST['first_name']))
					{
						$code = 204;
					}
					if (isset($_POST['first_name']) && !pjValidation::pjActionNotEmpty($_POST['first_name']))
					{
						$code = 205;
					}
				}
				if(in_array('last_name', $subscribed_fields))
				{
					if(!isset($_POST['last_name']))
					{
						$code = 206;
					}
					if (isset($_POST['last_name']) && !pjValidation::pjActionNotEmpty($_POST['last_name']))
					{
						$code = 207;
					}
				}
				if(!isset($_POST['email']))
				{
					$code = 208;
				}
				if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
				{
					$code = 209;
				}
				if (isset($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
				{
					$code = 210;
				}
				if(in_array('phone', $subscribed_fields))
				{
					if(!isset($_POST['phone']))
					{
						$code = 211;
					}
					if (isset($_POST['phone']) && !pjValidation::pjActionNotEmpty($_POST['phone']))
					{
						$code = 212;
					}
				}
				if(in_array('website', $subscribed_fields))
				{
					if(!isset($_POST['website']))
					{
						$code = 213;
					}
					if (isset($_POST['website']) && !pjValidation::pjActionNotEmpty($_POST['website']))
					{
						$code = 214;
					}
				}
				if(in_array('gender', $subscribed_fields))
				{
					if(!isset($_POST['gender']))
					{
						$code = 215;
					}
					if (isset($_POST['gender']) && !pjValidation::pjActionNotEmpty($_POST['gender']))
					{
						$code = 216;
					}
				}
				if(in_array('age', $subscribed_fields))
				{
					if(!isset($_POST['age']))
					{
						$code = 217;
					}
					if (isset($_POST['age']) && !pjValidation::pjActionNotEmpty($_POST['age']))
					{
						$code = 218;
					}
				}
				if(in_array('birthday', $subscribed_fields))
				{
					if(!isset($_POST['day']))
					{
						$code = 219;
					}
					if (isset($_POST['day']) && !pjValidation::pjActionNotEmpty($_POST['day']))
					{
						$code = 220;
					}
					if(!isset($_POST['month']))
					{
						$code = 221;
					}
					if (isset($_POST['month']) && !pjValidation::pjActionNotEmpty($_POST['month']))
					{
						$code = 222;
					}
					if(!isset($_POST['year']))
					{
						$code = 233;
					}
					if (isset($_POST['year']) && !pjValidation::pjActionNotEmpty($_POST['year']))
					{
						$code = 234;
					}
				}
				if(in_array('address', $subscribed_fields))
				{
					if(!isset($_POST['address']))
					{
						$code = 223;
					}
					if (isset($_POST['address']) && !pjValidation::pjActionNotEmpty($_POST['address']))
					{
						$code = 224;
					}
				}
				if(in_array('city', $subscribed_fields))
				{
					if(!isset($_POST['city']))
					{
						$code = 225;
					}
					if (isset($_POST['city']) && !pjValidation::pjActionNotEmpty($_POST['city']))
					{
						$code = 226;
					}
				}
				if(in_array('state', $subscribed_fields))
				{
					if(!isset($_POST['state']))
					{
						$code = 235;
					}
					if (isset($_POST['state']) && !pjValidation::pjActionNotEmpty($_POST['state']))
					{
						$code = 236;
					}
				}
				if(in_array('country', $subscribed_fields))
				{
					if(!isset($_POST['country_id']))
					{
						$code = 227;
					}
					if (isset($_POST['country_id']) && !pjValidation::pjActionNotEmpty($_POST['country_id']))
					{
						$code = 228;
					}
				}
				if(in_array('zip', $subscribed_fields))
				{
					if(!isset($_POST['zip']))
					{
						$code = 229;
					}
					if (isset($_POST['zip']) && !pjValidation::pjActionNotEmpty($_POST['zip']))
					{
						$code = 230;
					}
				}
				if(in_array('company_name', $subscribed_fields))
				{
					if(!isset($_POST['company_name']))
					{
						$code = 231;
					}
					if (isset($_POST['company_name']) && !pjValidation::pjActionNotEmpty($_POST['company_name']))
					{
						$code = 232;
					}
				}
			}else{
				$code = 200;
			}
			
			if($code == 100)
			{
				$pjSubscriberModel = pjSubscriberModel::factory();
				
				$arr = $pjSubscriberModel->where('t1.email', $_POST['email'])->findAll()->getData();
				if(count($arr) > 0)
				{
				    $id = $arr[0]['id'];
				}else{
				    $data = array();
				    $data['ip'] = pjUtil::getClientIp();
				    $data = array_merge($_POST, $data);
    				$id = $pjSubscriberModel->reset()->setAttributes($data)->insert()->getInsertId();
				}
				if ($id !== false && (int) $id > 0)
				{
					if(isset($_POST['group_id']))
					{
						$data = array();
						$data['group_id'] = $_POST['group_id'];
						$data['subscriber_id'] = $id;
						pjGroupSubscriberModel::factory()->setAttributes($data)->insert();
					}
					
					$group_arr = pjGroupModel::factory()->find($_POST['group_id'])->getData();
					
					if($group_arr['send_confirm'] == 'T')
					{
						$this->pjSendConfirmMessage($_POST['group_id'], $id);
						$pjSubscriberModel->reset()->where('id', $id)->limit(1)->modifyAll(array('subscribed' => 'F'));
					}else{
						$pjSubscriberModel->reset()->where('id', $id)->limit(1)->modifyAll(array('subscribed' => 'T'));
					}
					if($group_arr['send_response'] == 'T' && $group_arr['send_confirm'] == 'F')
					{
					    $this->pjSendResponseMessage($_POST['group_id'], $id);
					}
					
					$code = 100;
				} else {
					$code = 101;
				}
			}
			echo $code;
		}
		exit;
	}
	
	public function pjActionConfirm()
	{
		$this->setLayout('pjActionFront');
		
		$hash = $_GET['hash'];
		if($hash == md5(PJ_SALT . $_GET['id']))
		{
			$pjSubscriberModel = pjSubscriberModel::factory();
			if($pjSubscriberModel->where('id', $_GET['id'])->where('subscribed', 'T')->findCount()->getData() == 0)
			{
				$pjSubscriberModel->reset()->where('id', $_GET['id'])->limit(1)->modifyAll(array('subscribed'=>'T'));
				
				$group_arr = pjGroupModel::factory()->find($_GET['group_id'])->getData();
				
				if($group_arr['send_response'] == 'T')
				{
					$this->pjSendResponseMessage($_GET['group_id'], $_GET['id']);
				}
				
				$err = 'FC01';
			}else{
				$err = 'FC03';
			}
		}else{
			$err = 'FC02';
		}
		$this->set('status', $err);
		$this->appendCss('front.css');
	}
	
	public function pjActionUnsubscribe()
	{
		$this->setLayout('pjActionFront');
		
		$hash = $_GET['hash'];
		if($hash == md5(PJ_SALT . $_GET['id']))
		{
			$pjSubscriberModel = pjSubscriberModel::factory();
			if($pjSubscriberModel->where('id', $_GET['id'])->where('subscribed', 'F')->findCount()->getData() == 0)
			{
				$pjSubscriberModel->reset()->where('id', $_GET['id'])->limit(1)->modifyAll(array('subscribed'=>'F'));
				
				$err = 'FS01';
			}else{
				$err = 'FS03';
			}
		}else{
			$err = 'FS02';
		}
		$this->set('status', $err);
		$this->appendCss('front.css');
	}
	
	public function pjActionSetLocale()
	{
		$this->setLocaleId(@$_GET['locale']);
		pjUtil::redirect($_SERVER['HTTP_REFERER']);
	}
	
	public function pjActionCron()
	{
		$this->setLayout('pjActionEmpty');
		
		set_time_limit(0);

		$pjQueueModel = pjQueueModel::factory();
		$pjFileModel = pjFileModel::factory();
		
		$admin_arr = pjUserModel::factory()->find(1)->getData();
		$admin_email = $admin_arr['email'];	
		
		$option_arr = pjOptionModel::factory()->getPairs(1);
		
		$pjQueueModel->join('pjMessage', 't2.id=t1.message_id', 'left')
					->join('pjSubscriber', 't3.id=t1.subscriber_id', 'left')
					->join('pjMultiLang', "t4.model='pjCountry' AND t4.foreign_id=t3.country_id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.status', 'inprogress')
					->where('t1.date_sent <', date('Y-m-d H:i:s'))
					->select('t1.id AS queue_id, t1.message_id, t1.subscriber_id, t1.date_sent, t1.status, t2.subject, t2.tinymce_message, t2.plain_message, 
									t3.id, t3.first_name, t3.last_name, t3.email, t3.phone, 
									t3.website, t3.gender, t3.age, t3.birthday, t3.address, 
									t3.city, t3.state, t4.content as country_title, t3.zip, t3.company_name');
		
		$queue_arr = $pjQueueModel->orderBy("t1.date_sent ASC")->findAll()->getData();
		
		$file_arr = $pjFileModel->where("t1.message_id IN(SELECT TQ.message_id FROM `".$pjQueueModel->getTable()."` AS TQ WHERE TQ.status = 'inprogress' AND TQ.date_sent < '".date('Y-m-d H:i:s')."')")
					->findAll()->getData();
		
		$attach_arr = array();	
		foreach($file_arr as $f)
		{
			$attach_arr[$f['message_id']][] = $f; 
		}
		foreach($queue_arr as $queue)
		{
			if(!empty($queue['email']))
			{
				
				$data = pjAppController::getData($queue, $option_arr, PJ_SALT, false);
				$message = str_replace($data['search'], $data['replace'], $queue['tinymce_message']);
				$subject = 	str_replace($data['search'], $data['replace'], $queue['subject']);
				$data = pjAppController::getData($queue, $option_arr, PJ_SALT, true);
				$plain_message = str_replace($data['search'], $data['replace'], $message_arr['plain_message']);
				
				pjAppController::sendMessage($queue['email'], $subject, $message, $plain_message, $option_arr, $attach_arr[$queue['message_id']]);
				
				$pjQueueModel->reset()->set('id', $queue['queue_id'])->modify(array('status' => 'completed'));
			}
		}
		echo 'done';
		exit;
	}
	
	public function pjSendConfirmMessage($group_id, $subscriber_id)
	{
		$arr = pjSubscriberModel::factory()
				->select('t1.*, t2.content as country_title')
				->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.country_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->find($subscriber_id)
				->getData();
		$group_arr = pjGroupModel::factory()->find($group_id)->getData();
		
		$data = pjAppController::getData($arr, $this->option_arr, PJ_SALT, true, $group_id);
									
		$message = str_replace($data['search'], $data['replace'], $group_arr['confirm_message']);
		$subject = 	str_replace($data['search'], $data['replace'], $group_arr['confirm_subject']);
		
		pjAppController::sendConfirm($arr['email'], $subject, $message, $this->option_arr);
	}
	
	public function pjSendResponseMessage($group_id, $subscriber_id)
	{
		$arr = pjSubscriberModel::factory()
				->select('t1.*, t2.content as country_title')
				->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.country_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->find($subscriber_id)
				->getData();
		$group_arr = pjGroupModel::factory()->find($group_id)->getData();
		
		$data = pjAppController::getData($arr, $this->option_arr, PJ_SALT, true, $group_id);
		$message = str_replace($data['search'], $data['replace'], $group_arr['response_message']);
		$subject = 	str_replace($data['search'], $data['replace'], $group_arr['response_subject']);
								
		pjAppController::sendConfirm($arr['email'], $subject, $message, $this->option_arr);
	}
}
?>