<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{	
	public $defaultCaptcha = 'pjFundrasing_Captcha';
	
	public $defaultLocale = 'pjFundrasing_LocaleId';
	
	public $defaultAmount = 'pjFundrasing_Amount';
	
	public function __construct()
	{
		$this->setLayout('pjActionFront');
	}

	public function afterFilter()
	{		
		if (!isset($_GET['hide']) || (isset($_GET['hide']) && (int) $_GET['hide'] !== 1) &&
			in_array($_GET['action'], array('pjActionIndex', 'pjActionPreview')))
		{
			$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);
		}
		$arr = array();
		
		$arr = pjCampaignModel::factory()
			->select("t1.*, (SELECT SUM(`TD`.`amount`) FROM `".pjDonationModel::factory()->getTable()."` AS TD WHERE TD.campaign_id=".$_GET['cid']." AND TD.status='P') AS received")
			->find($_GET['cid'])->getData();
		
		if(!empty($arr) && $arr['status'] == 'T')
		{
			$received_amount = 0;
			$needed_amount = $arr['amount'];
			$percentage = 0;
			$days_left = 0;
			if(isset($arr['received']) && $arr['received'] > 0)
			{
				$received_amount = $arr['received'];
			}
			if($needed_amount > 0)
			{
				$percentage = number_format(($received_amount * 100) / $needed_amount, 0);
			}
				
			$now = time();
			$deadline_ts = strtotime($arr['deadline']);
			$datediff = $now - $deadline_ts;
			$days_left = abs(floor($datediff/(60*60*24)));
				
			$donations = pjDonationModel::factory()->where("campaign_id", $_GET['cid'])->where('status', 'P')->findCount()->getData();
				
			$this->set('percentage', $percentage);
			$this->set('received_amount', $received_amount);
			$this->set('days_left', $days_left);
			$this->set('donations', $donations);
		}
		$this->set('arr', $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 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';
		}
	}
	
	public function pjActionLoadCss()
	{
		$arr = array(
			array('file' => 'front_lib.css', 'path' => PJ_CSS_PATH),
			array('file' => 'Fundrasing.css', 'path' => PJ_CSS_PATH)
		);
		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/', '[URL]', 'images/'),
					array(
						PJ_INSTALL_URL . PJ_IMG_PATH,
						PJ_INSTALL_URL,
						PJ_INSTALL_URL . PJ_LIBS_PATH . 'pjQ/css/images/'),
					$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionSetAmount()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if(isset($_POST['amount']) && is_numeric($_POST['amount']))
			{
				$_SESSION[$this->defaultAmount] = $_POST['amount'];
				pjAppController::jsonResponse(array('status' => 'OK'));
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR'));
			}
			exit;
		}
	}
	
	public function pjActionLoadCampaign()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			
		}
	}
	
	public function pjActionLoadForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			
		}
	}
	
	public function pjActionDonate()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if (!isset($_GET['cid']) || (int) $_GET['cid'] <= 0)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => __('front_campaign_not_existing', true, false)));
			}

			$pjDonationModel = pjDonationModel::factory();
			
			$data = array();
			$data['campaign_id'] = $_GET['cid'];
			$data['ip'] = pjUtil::getClientIp();
			if (isset($FORM['payment_method']) && $FORM['payment_method'] != 'creditcard')
			{
				unset($FORM['cc_type']);
				unset($FORM['cc_num']);
				unset($FORM['cc_code']);
				unset($FORM['cc_exp_month']);
				unset($FORM['cc_exp_year']);
			}
			$donation_id = $pjDonationModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
			if ($donation_id === false || empty($donation_id))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => __('front_donation_could_not_saved', true, false)));
			}
			
			$donation_arr = $pjDonationModel
				->reset()
				->join('pjCampaign', "t2.id=t1.campaign_id", 'left')
				->select('t1.*, t2.title')
				->find($donation_id)
				->getData();
			
			pjFront::pjActionConfirmSend($this->option_arr, $donation_arr, PJ_SALT, 'confirm');
			
			$_SESSION[$this->defaultAmount] = NULL;
			unset($_SESSION[$this->defaultAmount]);
			
			pjAppController::jsonResponse(array(
				'status' => 'OK',
				'code' => 200,
				'text' => __('front_donation_saved', true, false),
				'donation_id' => $donation_id,
				'payment_method' => $donation_arr['payment_method']
			));
		}
	}
	
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$arr = pjDonationModel::factory()
				->join('pjCampaign', "t2.id=t1.campaign_id", 'left')
				->select('t1.*, t2.title')
				->find($_GET['donation_id'])
				->getData();
			
			switch ($arr['payment_method'])
			{
				case 'paypal':
					$this->set('params', array(
						'name' => 'frPaypal',
						'id' => 'frPaypal',
						'business' => $this->option_arr['o_paypal_address'],
						'item_name' => pjSanitize::html($arr['title']),
						'custom' => $arr['id'],
						'amount' => number_format($arr['amount'], 2, '.', ''),
						'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' => 'frAuthorize',
						'id' => 'frAuthorize',
						'target' => '_self',
						'transkey' => $this->option_arr['o_authorize_transkey'],
						'x_login' => $this->option_arr['o_authorize_merchant_id'],
						'x_description' => pjSanitize::html($arr['title']),
						'x_amount' => number_format($arr['amount'], 2, '.', ''),
						'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('donation_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;
		}
		
		$pjDonationModel = pjDonationModel::factory();
		
		$donate_arr = $pjDonationModel
			->join('pjCampaign', "t2.id=t1.campaign_id", 'left')
			->select('t1.*, t2.title')
			->find($_POST['x_invoice_num'])
			->getData();	
		
		if (count($donate_arr) == 0)
		{
			$this->log('No such donation');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}					
		
		if (count($donate_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')
			{
				
				$pjDonationModel->reset()
					->setAttributes(array('id' => $response['transaction_id']))
					->modify(array('status' => 'P', 'processed_on' => ':NOW()'));
				
				pjDonationPaymentModel::factory()->setAttributes(array('donation_id' => $response['transaction_id'], 'payment_type' => 'online'))
												->modify(array('status' => 'paid'));
			
				pjFront::pjActionConfirmSend($this->option_arr, $donate_arr, PJ_SALT, 'payment');
				
			} elseif (!$response) {
				$this->log('Authorization failed');
			} else {
				$this->log('Booking not confirmed. ' . $response['response_reason_text']);
			}
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}
	}

	public function pjActionConfirmPaypal()
	{
		$this->setAjax(true);
		
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			exit;
		}
		$pjDonationModel = pjDonationModel::factory();
		
		$donate_arr = $pjDonationModel
			->join('pjCampaign', "t2.id=t1.campaign_id", 'left')
			->select('t1.*, t2.title')
			->find($_POST['custom'])
			->getData();
		if (count($donate_arr) == 0)
		{
			$this->log('No such booking');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}					
		
		$params = array(
			'txn_id' => @$donate_arr['txn_id'],
			'paypal_address' => $this->option_arr['o_paypal_address'],
			'deposit' => @$donate_arr['amount'],
			'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('Booking confirmed');
			$pjDonationModel->reset()->setAttributes(array('id' => $donate_arr['id']))->modify(array(
				'status' => 'P',
				'txn_id' => $response['transaction_id'],
				'processed_on' => ':NOW()'
			));
			pjDonationPaymentModel::factory()->setAttributes(array('donation_id' => $donate_arr['id'], 'payment_type' => 'online'))
											->modify(array('status' => 'paid'));
			
			pjFront::pjActionConfirmSend($this->option_arr, $donate_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, $data, $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();
		
		$pjMultiLangModel = pjMultiLangModel::factory();
		
		$tokens = pjAppController::getTokens($option_arr, $data, $salt, $this->getLocaleId());
		
		if ($option_arr['o_email_confirmation'] == 1 && $opt == 'confirm')
		{
			$lang_message = $option_arr['o_email_confirmation_message'];
			$lang_subject = $option_arr['o_email_confirmation_subject'];
			if (!empty($lang_message) && !empty($lang_subject))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message);
				$Email
					->setTo($data['email'])
					->setFrom($admin_email)
					->setSubject($lang_subject)
					->send(pjUtil::textToHtml($message));
			}
		}
		
		if ($option_arr['o_admin_email_confirmation'] == 1 && $opt == 'confirm')
		{
			$lang_message = $option_arr['o_admin_email_confirmation_message'];
			$lang_subject = $option_arr['o_admin_email_confirmation_subject'];
			if (!empty($lang_message) && !empty($lang_subject))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message);
				$Email
					->setTo($admin_email)
					->setFrom($admin_email)
					->setSubject($lang_subject)
					->send(pjUtil::textToHtml($message));
			}
		}
		
		if ($option_arr['o_email_payment'] == 1 && $opt == 'payment')
		{
			$lang_message = $option_arr['o_email_payment_message'];
			$lang_subject = $option_arr['o_email_payment_subject'];
			if (!empty($lang_message) && !empty($lang_subject))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message);
				$Email
					->setTo($data['email'])
					->setFrom($admin_email)
					->setSubject($lang_subject)
					->send(pjUtil::textToHtml($message));
			}
		}
		
		if ($option_arr['o_admin_email_payment'] == 1 && $opt == 'payment')
		{
			$lang_message = $option_arr['o_admin_email_payment_message'];
			$lang_subject = $option_arr['o_admin_email_payment_subject'];
			if (!empty($lang_message) && !empty($lang_subject))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message);
				$Email
					->setTo($admin_email)
					->setFrom($admin_email)
					->setSubject($lang_subject)
					->send(pjUtil::textToHtml($message));
			}
		}
	}
}
?>