<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFrontPublic extends pjFront
{
	public function __construct()
	{
		parent::__construct();
		
		$this->setAjax(true);
		
		$this->setLayout('pjActionEmpty');
	}
	
	public function pjActionCalendar()
	{
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if (isset($_GET['_escaped_fragment_']))
			{
				preg_match('/\/date:([\d\-\.\/]+)?/', $_GET['_escaped_fragment_'], $matches);
				if (!empty($matches))
				{
					$date = $matches[1];
				}
			} else {
				$date = @$_GET['date'];
			}
			
			$year = $month = $day = NULL;
			if (!empty($date))
			{
				list($year, $month, $day) = explode("-", $date);
			}
			$this->set('calendar', $this->getCalendar($_GET['cid'], $year, $month, $day));
		}
	}
	
	public function pjActionCart()
	{
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
		    $cart_arr = $this->getCart($_GET['cid']);
		    $this->set('cart_arr', $cart_arr);
			if ((int) $this->option_arr['o_hide_prices'] === 0)
			{
				$this->set('cart_price_arr', pjAppController::getCartPrices($_GET['cid'], $this->cart, @$_SESSION[$this->defaultOwnerCalendarId]));
			}
		}
	}
	
	public function pjActionCheckout()
	{
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if (isset($_POST['ts_checkout']))
			{
				$_SESSION[$this->defaultForm] = array_merge($_SESSION[$this->defaultForm], $_POST);
				
				if (!isset($_GET['cid']) || (int) $_GET['cid'] <= 0)
				{
					pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
				}
				
				$response = $this->validateCheckout($_GET['cid']);
				pjAppController::jsonResponse($response);
				
			} else {
				if (!$this->cart->isEmpty())
				{
					if (in_array($this->option_arr['o_bf_country'], array(2,3)))
					{
						$pjCountryModel = pjCountryModel::factory();
						$calendar_arr = pjCalendarModel::factory()->select('t1.*, t2.role_id')
							->join('pjUser', 't2.id=t1.user_id', 'left outer')
							->find($_GET['cid'])
							->getData();
						if ($calendar_arr['role_id'] == 3) {
							$pjCountryModel->where('t1.id IN (SELECT `class_id` FROM `'.pjUserClassModel::factory()->getTable().'` WHERE `user_id`='.$calendar_arr['user_id'].')');
						}
						
						$this->set('country_arr', $pjCountryModel
							->select('t1.*, t2.content AS name')
							->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->pjActionGetLocale()."'", 'left outer')
							->where('t1.status', 'T')
							->orderBy('`name` ASC')
							->findAll()
							->getData()
						);
					}
					
					$this->set('terms_arr', $this->getTerms($_GET['cid']));
					$this->set('amount', pjAppController::getCartTotal($_GET['cid'], $this->cart, $this->option_arr, @$_SESSION[$this->defaultOwnerCalendarId]));
					
					$this->set('status', 'OK');
					//$this->set('summary', $this->getSummary());
					$this->set('cart_arr', $this->getCart($_GET['cid']));
					if ((int) $this->option_arr['o_hide_prices'] === 0)
					{
						$this->set('cart_price_arr', pjAppController::getCartPrices($_GET['cid'], $this->cart, @$_SESSION[$this->defaultOwnerCalendarId]));
					}
					$this->set('terms_arr', $this->getTerms($_GET['cid']));
				} else {
					$this->set('status', 'ERR');
					$this->set('code', '101'); //Empty cart
				}
			}
		}
	}
		
	public function pjActionPreview()
	{
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if (!$this->cart->isEmpty())
			{
				if(isset($_GET['duplicated']) && (int) $_GET['duplicated'] == 1)
				{
					$this->set('cart_arr', $this->getCart($_GET['cid']));
					if ((int) $this->option_arr['o_hide_prices'] === 0)
					{
						$this->set('cart_price_arr', pjAppController::getCartPrices($_GET['cid'], $this->cart, @$_SESSION[$this->defaultOwnerCalendarId]));
					}
					$_SESSION[$this->defaultCart] = NULL;
					unset($_SESSION[$this->defaultCart]);
					
					$this->set('status', 'OK');
					$this->set('duplicated', true);
				}else{
					if (!isset($_SESSION[$this->defaultForm]) || empty($_SESSION[$this->defaultForm]) || !isset($_SESSION[$this->defaultCart]) || empty($_SESSION[$this->defaultCart]))
					{
						$this->set('status', 'ERR');
						$this->set('code', '102'); 
					} else {
						if (in_array($this->option_arr['o_bf_country'], array(2,3)) && (int) @$_SESSION[$this->defaultForm]['customer_country'] > 0)
						{
							$this->set('country_arr', pjCountryModel::factory()
								->select('t1.*, t2.content AS name')
								->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]['customer_country'])
								->getData()
							);
						}
						$this->set('amount', pjAppController::getCartTotal($_GET['cid'], $this->cart, $this->option_arr, @$_SESSION[$this->defaultOwnerCalendarId]));
						$this->set('status', 'OK');
						
						$this->set('cart_arr', $this->getCart($_GET['cid']));
						if ((int) $this->option_arr['o_hide_prices'] === 0)
						{
							$this->set('cart_price_arr', pjAppController::getCartPrices($_GET['cid'], $this->cart, @$_SESSION[$this->defaultOwnerCalendarId]));
						}
					}
				}
			} else {
				$this->set('status', 'ERR');
				$this->set('code', '101'); 
			}
		}
	}
	
	public function pjActionTimeslots()
	{
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if (isset($_GET['_escaped_fragment_']))
			{
				preg_match('/\/date:([\d\-\.\/]+)?/', $_GET['_escaped_fragment_'], $matches);
				if (!empty($matches))
				{
					$date = $matches[1];
				}
			} else {
				$date = @$_GET['date'];
			}
			
			$year = $month = $day = NULL;
			if (!empty($date))
			{
				list($year, $month, $day) = explode("-", $date);
			}
			
			$result = $this->getTimeslots($_GET['cid'], $date);
			
			foreach ($result as $key => $value)
			{
				$this->set($key, $value);
			}
			
			$cut_off_data = pjUtil::getCutOffRange($this->option_arr);
			if($cut_off_data != FALSE)
			{
			    $cut_off_range_arr = $cut_off_data['range'];
			    if(!in_array($date, $cut_off_range_arr))
			    {
			        if($date <= end($cut_off_range_arr))
			        { 
			            $this->set('cut_off_date_time', $cut_off_data['cut_off_dt']);
			        }
			    }
			}
		}
	}

	public function pjActionBooking()
	{
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			$this->set('status', 'OK');
			
			if (isset($_GET['booking_uuid']) && !empty($_GET['booking_uuid']))
			{
				$booking_uuid = $_GET['booking_uuid'];
			} elseif (isset($_GET['_escaped_fragment_'])) {
				preg_match('/\/Booking\/([A-Z]{2}\d{10})/', $_GET['_escaped_fragment_'], $matches);
				if (isset($matches[1]))
				{
					$booking_uuid = $matches[1];
				}
			}
			
			$booking_arr = pjBookingModel::factory()->select('t1.*, t2.content AS calendar_title')
				->join('pjMultiLang', "t2.model='pjCalendar' AND t2.foreign_id=t1.calendar_id AND t2.field='title' AND t2.locale='".$this->pjActionGetLocale()."'", 'left outer')
				->where('t1.ref_uuid', $booking_uuid)
				->orderBy('t2.content ASC')
				->findAll()->limit(1)->getData();
			if (!empty($booking_arr))
			{
				$paid_deposit = 0;
				$desc_arr = array();
				foreach ($booking_arr as $val) {
					$desc_arr[] = $val['calendar_title'].' - '.$val['uuid'];
					$paid_deposit += $val['booking_deposit'];
				}
				$booking_arr = $booking_arr[0];	
				switch ($booking_arr['payment_method'])
				{
					case 'paypal':
						$this->set('params', array(
							'name' => 'tsPaypal',
							'id' => 'tsPaypal',
							'target' => '_self',
							'business' => $this->option_arr['o_paypal_address'],
							'item_name' => implode(' | ', $desc_arr),
							'custom' => $booking_uuid,
							'amount' => $paid_deposit,
							'currency_code' => $this->option_arr['o_currency'],
							'return' => $this->option_arr['o_thankyou_page'],
							'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjFrontEnd&action=pjActionConfirmPaypal',
							'submit' => __('payment_paypal_submit', true),
							'submit_class' => 'tsSelectorButton tsButton tsButtonGreen'
						));
						break;
					case 'authorize':
						$this->set('params', array(
							'name' => 'tsAuthorize',
							'id' => 'tsAuthorize',
							'target' => '_self',
							'timezone' => $this->option_arr['o_authorize_tz'],
							'transkey' => $this->option_arr['o_authorize_key'],
							'x_login' => $this->option_arr['o_authorize_mid'],
							'x_description' => implode(' | ', $desc_arr),
							'x_amount' => $paid_deposit,
							'x_invoice_num' => $booking_uuid,
							'x_receipt_link_url' => $this->option_arr['o_thankyou_page'],
							'x_relay_url' => PJ_INSTALL_URL . 'index.php?controller=pjFrontEnd&action=pjActionConfirmAuthorize',
							'submit' => __('payment_authorize_submit', true),
							'submit_class' => 'tsSelectorButton tsButton tsButtonGreen'
						));
						break;
					case 'stripe':
					    
					    $cancel_hash = sha1($booking_arr['uuid'].strtotime($booking_arr['created']).PJ_SALT);
					    
					    require_once ROOT_PATH . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
					    
						 $decryptedKey = $this->decrypt($this->option_arr['o_stripe_secret_key']);

							// Check if decryption was successful
							if (empty($decryptedKey)) {
								throw new Exception("Stripe Secret Key decryption failed.");
							}

					    \Stripe\Stripe::setApiKey($decryptedKey);
					    \Stripe\Stripe::setApiVersion('2020-03-02');

					    $session = \Stripe\Checkout\Session::create(array(
					        'payment_method_types' => array('card'),
						'customer_email' => @$booking_arr['customer_email'],
						'payment_intent_data'=>['description' => implode(' | ', $desc_arr)],
					        'line_items' => array(
					            array(
					                'name' => $booking_uuid,
					                'description' => $booking_uuid,
					                'amount' => round($paid_deposit * 100),
					                'currency' => $this->option_arr['o_currency'],
					                'quantity' => 1,
					            )
					        ),
					        'client_reference_id' => $booking_uuid,
					        'success_url' => PJ_INSTALL_URL . 'index.php?controller=pjFrontEnd&action=pjActionConfirmStripe&cid=' . $booking_arr['calendar_id'] . "&reference_id=" . $booking_uuid,
					        'cancel_url' => PJ_INSTALL_URL . 'index.php?controller=pjFrontEnd&action=pjActionConfirmStripe&cid=' . $booking_arr['calendar_id'] . "&reference_id=" . $booking_uuid . "&cancel_hash=" . $cancel_hash,
					    ));
					    
					    $this->set('params', array(
					        'sessionId' => $session->id
					    ));
					    break;
				}
				
				$this->set('booking_arr', $booking_arr);
				$paypal_emails = $this->getPaypalEmailsFromWhiteList();
				$this->set('paypal_emails', $paypal_emails);
			}
		}
	}

	private function decrypt($data)
	{
		$key = hash('sha256', PJ_SALT, true);
		$data = base64_decode($data);
		$iv = substr($data, 0, 16);
		$ciphertext = substr($data, 16);
		return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
	}

	public function pjActionWeekly()
	{
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			if (isset($_GET['_escaped_fragment_']))
			{
				preg_match('/\/date:([\d\-\.\/]+)?/', $_GET['_escaped_fragment_'], $matches);
				if (!empty($matches))
				{
					$date = $matches[1];
				}
			} else {
				$date = @$_GET['date'];
			}
			
			$week_arr = pjUtil::getWeekRange($date, $this->option_arr['o_week_start']);
			$date = $week_arr[0];
			
			$result = $this->getWeeklyTimeslots($_GET['cid'], $date);
			
			foreach ($result as $key => $value)
			{
				$this->set($key, $value);
			}
			
			$cut_off_data = pjUtil::getCutOffRange($this->option_arr);
			$this->set('cut_off_data', $cut_off_data);
		}
	}
	
	public function pjActionRouter()
	{
		$this->setAjax(false);

		if (isset($_GET['_escaped_fragment_']))
		{
			$templates = array('Checkout', 'Preview', 'Timeslots', 'Booking', 'Calendar', 'Cart', 'Weekly');
			preg_match('/^\/(\w+).*/', $_GET['_escaped_fragment_'], $m);
			if (isset($m[1]) && in_array($m[1], $templates))
			{
				$template = 'pjAction'.$m[1];
			
				if (method_exists($this, $template))
				{
					$this->$template();
				}
				$this->setTemplate('pjFrontPublic', $template);
			}
		}
	}
}
?>