<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
require_once PJ_CONTROLLERS_PATH . 'pjAdmin.controller.php';
class pjAdminBookings extends pjAdmin
{                  
	public function pjActionCheckUniqueId()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() && isset($_GET['uuid']))
		{
			$pjBookingModel = pjBookingModel::factory();
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjBookingModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjBookingModel->where('t1.uuid', $_GET['uuid'])->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionGetBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBookingModel = pjBookingModel::factory()
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.listing_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer');;
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjBookingModel->where('t1.uuid LIKE', "%$q%");
				$pjBookingModel->orWhere('t1.c_name LIKE', "%$q%");
				$pjBookingModel->orWhere('t1.c_email LIKE', "%$q%");
				$pjBookingModel->orWhere('t1.c_phone LIKE', "%$q%");
			}
			if($this->isOwner())
			{
				$pjBookingModel->where("(t1.listing_id IN (SELECT TL.id FROM `".pjListingModel::factory()->getTable()."` AS TL WHERE TL.owner_id = '".$this->getUserId()."') )");
			}			
			if (isset($_GET['listing_id']) && (int) $_GET['listing_id'] > 0)
			{
				$pjBookingModel->where('t1.listing_id', $_GET['listing_id']);
			}
			if (isset($_GET['week_start']) && $_GET['week_start'] != '')
			{
				$pjBookingModel->where("week_start", $_GET['week_start']);
			}
			if (isset($_GET['uuid']) && $_GET['uuid'] != '')
			{
				$uuid = pjObject::escapeString($_GET['uuid']);
				$pjBookingModel->where('t1.uuid LIKE', "%$uuid%");
			}
			if (isset($_GET['c_name']) && $_GET['c_name'] != '')
			{
				$customer_name = pjObject::escapeString($_GET['c_name']);
				$pjBookingModel->where('t1.c_name LIKE', "%$customer_name%");
			}
			if (isset($_GET['c_email']) && $_GET['c_email'] != '')
			{
				$customer_email = pjObject::escapeString($_GET['c_email']);
				$pjBookingModel->where('t1.c_email LIKE', "%$customer_email%");
			}
			if (isset($_GET['from_price']) && $_GET['from_price'] != '')
			{
				$from = $_GET['from_price'];
				$pjBookingModel->where("t1.total >=" , $from);
			}
			if (isset($_GET['to_price'])  && $_GET['to_price'] != '')
			{
				$to = $_GET['to_price'];
				$pjBookingModel->where("t1.total <=" , $to);
			}
			if (isset($_GET['status']) && !empty($_GET['status']))
			{
				$pjBookingModel->where('t1.status', $_GET['status']);
			}
			
			$column = 'created';
			$direction = 'DESC';
			$allowed_columns = array('c_name', 'week_start', 'title', 'status');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjBookingModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$pages = ceil($total / $rowCount);
			$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}
			$data = array();
			$arr = $pjBookingModel
				->select("t1.*, t2.content as title")
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			
			foreach($arr as $k => $v)
			{
				$v['week_start'] = date($this->option_arr['o_date_format'], strtotime($v['week_start'])) . ' - ' . date($this->option_arr['o_date_format'], strtotime($v['week_start']) + 6 * 60 * 60 * 24);
				unset($v['cc_type']);
				unset($v['cc_num']);
				unset($v['cc_exp_month']);
				unset($v['cc_exp_year']);
				unset($v['cc_code']);
				$data[$k] = $v;
			}
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			$pjListingModel = pjListingModel::factory();
			if($this->isOwner())
			{
				$pjListingModel->where('t1.owner_id', $this->getUserId());
			}
			$listing_arr = $pjListingModel
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->select(" t1.*, t2.content as title")
				->where("t1.for", "rent")
				->where("t1.status", "T")
				->orderBy("t1.created DESC")
				->findAll()
				->getData();
			$this->set('listing_arr', $listing_arr);
			
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminBookings.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExportBooking()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjBookingModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Bookings-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['booking_create']))
			{
				$data = array();
				
				$pjBookingModel = pjBookingModel::factory();
				
				$data['uuid'] = pjUtil::uuid();
				$data['ip']= pjUtil::getClientIp();
				
				$post = array_merge($_POST, $data);

				if (!$pjBookingModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR04");
				}
				
				$insert_id = $pjBookingModel->setAttributes($post)->insert()->getInsertId();
				if ($insert_id !== false && (int) $insert_id > 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR03");
				} else {
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR04");
				}
			}else{
				$pjBookingModel = pjBookingModel::factory();
				$pjListingModel = pjListingModel::factory();
				
				$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();
				if($this->isOwner())
				{
					$pjListingModel->where('t1.owner_id', $this->getUserId());
				}
				$listing_arr = $pjListingModel
					->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select(" t1.*, t2.content as title")
					->where("t1.for", "rent")
					->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))")
					->orderBy("t1.created DESC")
					->findAll()
					->getData();
				
				
				$this->set('listing_arr', $listing_arr);
				$this->set('country_arr', $country_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminBookings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			$pjBookingModel = pjBookingModel::factory();
			$pjListingModel = pjListingModel::factory();

			$pjBookingModel = pjBookingModel::factory();
			if (isset($_REQUEST['id']) && (int) $_REQUEST['id'] > 0)
			{
				$pjBookingModel->where('t1.id', $_REQUEST['id']);
			} elseif (isset($_GET['uuid']) && !empty($_GET['uuid'])) {
				$pjBookingModel->where('t1.uuid', $_GET['uuid']);
			}
			$arr = $pjBookingModel
				->select(sprintf("t1.*,
					AES_DECRYPT(t1.cc_num, '%1\$s') AS `cc_num`,
					AES_DECRYPT(t1.cc_exp_month, '%1\$s') AS `cc_exp_month`,
					AES_DECRYPT(t1.cc_exp_year, '%1\$s') AS `cc_exp_year`,
					AES_DECRYPT(t1.cc_code, '%1\$s') AS `cc_code`", PJ_SALT))
				->join('pjEvent', 't2.id=t1.event_id')
				->limit(1)
				->findAll()
				->getData();
			
			if (empty($arr))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR08");
			}
			$booking = $arr[0];
			
			$listing_id = $booking['listing_id'];
			
			$listing = $pjListingModel->find($listing_id)->getData();
			if (empty($listing) || count($listing) == 0)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR09");
			}
			
			if (isset($_POST['booking_update']))
			{
				$data = array();
				
				$data['ip']= pjUtil::getClientIp();
				$post = array_merge($_POST, $data);
				
				if (!$pjBookingModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR02");
				}
				
				$pjBookingModel->reset()->set('id', $_POST['id'])->modify($post);
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR01");
			} else {
				$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();
				
				$pjListingModel->reset();
				if($this->isOwner())
				{
					$pjListingModel->where('t1.owner_id', $this->getUserId());
				}
				$listing_arr = $pjListingModel
					->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select(" t1.*, t2.content as title")
					->where("t1.for", "rent")
					->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))")
					->orderBy("t1.created DESC")
					->findAll()
					->getData();
				
				$week_arr = array();
				$price_arr = pjPriceModel::factory()
					->where('listing_id', $booking['listing_id'])
					->where("(t1.price IS NOT NULL)")
					->where("t1.start_date NOT IN (SELECT TB.week_start FROM `".$pjBookingModel->getTable()."` AS TB WHERE TB.listing_id='".$booking['listing_id']."' AND TB.id <>'".$booking['id']."' AND TB.status='confirmed')")
					->orderBy("start_date ASC")
					->findAll()
					->getDataPair("start_date", "price");
				foreach($price_arr as $k => $v)
				{
					$week_arr[$k] = $this->getPrices($v, $this->option_arr);
				}
				$this->set('week_arr', $week_arr);
				
				$this->set('arr', $arr);
				$this->set('listing_arr', $listing_arr);
				$this->set('country_arr', $country_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminBookings.js');
				
				$this->set('arr', $booking);
			}
		}
	}
	
	public function pjActionResend()
	{
		if(isset($_POST['resend_email']))
		{
			$booking_id = $_POST['id'];
	
			if(!empty($_POST['to']))
			{
				$subject = stripslashes($_POST['subject']);
				$to = stripslashes($_POST['to']);
				$from = $this->getAdminEmail();
				$message = stripslashes($_POST['message']);
	
				$pjEmail = new pjEmail();
	
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$pjEmail
						->setTransport('smtp')
						->setSmtpHost($this->option_arr['o_smtp_host'])
						->setSmtpPort($this->option_arr['o_smtp_port'])
						->setSmtpUser($this->option_arr['o_smtp_user'])
						->setSmtpPass($this->option_arr['o_smtp_pass'])
						->setSender($this->option_arr['o_smtp_user'])
					;
				}
	
				$pjEmail->setContentType('text/html');
				$pjEmail->setFrom($from);
				$pjEmail->setSubject($subject);
				$pjEmail->setTo($to);
				$pjEmail->send(pjUtil::textToHtml($message));
	
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionResend&id=$booking_id&err=AR10");
			}else{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionResend&id=$booking_id&err=AR11");
			}
				
		}else{
				
			$booking_id = $_GET['id'];
				
			$arr = pjBookingModel::factory()
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.listing_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
				->select("t1.*,
						AES_DECRYPT(t1.cc_type, '".PJ_SALT."') AS `cc_type`,
						AES_DECRYPT(t1.cc_num, '".PJ_SALT."') AS `cc_num`,
						AES_DECRYPT(t1.cc_exp_month, '".PJ_SALT."') AS `cc_exp_month`,
						AES_DECRYPT(t1.cc_exp_year, '".PJ_SALT."') AS `cc_exp_year`,
						AES_DECRYPT(t1.cc_code, '".PJ_SALT."') AS `cc_code`, 
						t2.content as title, t3.content as country_title")
				->find($booking_id)
				->getData();

			$tokens = pjAppController::getData($this->option_arr, $arr, PJ_SALT, $this->getLocaleId());
			
			$pjMultiLangModel = pjMultiLangModel::factory();
			
			$locale_id = $this->getLocaleId();
			$foreign_id = 1;
			
			$listing_arr = pjListingModel::factory()->find($arr['listing_id'])->getData();
			if(!empty($listing_arr['owner_id']))
			{
				$foreign_id = $listing_arr['owner_id'];
			}
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_payment_subject')
				->limit(0, 1)
				->findAll()->getData();
			
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
			
				$arr['payment_subject'] = $lang_subject[0]['content'];
				$arr['payment_message'] = $message;
			}
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_confirmation_subject')
				->limit(0, 1)
				->findAll()->getData();
				
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
					
				$arr['confirm_subject'] = $lang_subject[0]['content'];
				$arr['confirm_message'] = $message;
			}
			
			$this->set('arr', $arr);
				
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdminBookings.js');
		}
	}
	
	public function pjActionDeleteBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			$pjBookingModel = pjBookingModel::factory();
			$arr = $pjBookingModel->find($_GET['id'])->getData();
			if ($pjBookingModel->reset()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjBookingPaymentModel::factory()->where('booking_id', $_GET['id'])->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteBookingBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjBookingModel = pjBookingModel::factory();
				
				$pjBookingModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
				pjBookingPaymentModel::factory()->whereIn('booking_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionSaveBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjBookingModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionGetWeeks()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$week_arr = array();
			$pjPriceModel = pjPriceModel::factory();
			if(isset($_GET['id']) && $_GET['id'] != '')
			{
				$pjPriceModel->where("t1.start_date NOT IN (SELECT TB.week_start FROM `".pjBookingModel::factory()->getTable()."` AS TB WHERE TB.listing_id='".$_GET['listing_id']."' AND TB.id <>'".$_GET['id']."' AND TB.status='confirmed')");
			}else{
				$pjPriceModel->where("t1.start_date NOT IN (SELECT TB.week_start FROM `".pjBookingModel::factory()->getTable()."` AS TB WHERE TB.listing_id='".$_GET['listing_id']."' AND TB.status='confirmed')");
			}
			$arr = $pjPriceModel
				->where('listing_id', $_GET['listing_id'])
				->where("(DATE_FORMAT(t1.start_date,'%Y-%m-%d') > NOW())")
				->where("(t1.price IS NOT NULL)")
				->orderBy("start_date ASC")
				->findAll()
				->getDataPair("start_date", "price");
			foreach($arr as $k => $v)
			{
				$week_arr[$k] = $this->getPrices($v, $this->option_arr);
			}
			$this->set('week_arr', $week_arr);
		}
	}
}
?>