<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminReservations extends pjAdmin
{
	public function pjActionCheckDaysoff()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['date']) || empty($_GET['date']))
			{
				echo 'false';
				exit;
			}
			$date = pjUtil::formatDate($_GET['date'], $this->option_arr['o_date_format']);
			$pjDateModel = pjDateModel::factory()->where("('$date' BETWEEN `start_date` AND `end_date`)");
			
			echo $pjDateModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminReservations.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetReservation()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjReservationModel = pjReservationModel::factory()
				->join('pjMultiLang', "t2.model='pjBooth' AND t2.foreign_id=t1.booth_id AND t2.field='type' AND t2.locale='".$this->getLocaleId()."'", 'left outer');
				
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjReservationModel->where("(t1.id = '$q' OR t1.uuid = '$q' OR t1.c_name LIKE '%$q%' OR t2.content LIKE '%$q%')");
			}
			
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('confirmed','cancelled','pending')))
			{
				$pjReservationModel->where('t1.status', $_GET['status']);
			}
			if (isset($_GET['booth_id']) && (int) $_GET['booth_id'] > 0)
			{
				$pjReservationModel->where('t1.booth_id', $_GET['booth_id']);
			}
			
			$column = 'created';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjReservationModel->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();
			
			$data = $pjReservationModel
				->select("t1.*, t2.content as type, 
								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`")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			
			foreach($data as $k => $v)
			{
				$v['date'] = date($this->option_arr['o_date_format'], strtotime($v['date']));
				$v['total'] = pjUtil::formatCurrencySign($v['total'], $this->option_arr['o_currency']);
				$data[$k] = $v;
			}
			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionSaveReservation()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjReservationModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionExportReservation()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjReservationModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Reservations-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionDeleteReservation()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjReservationModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjReservationExtraModel::factory()->where('reservation_id', $_GET['id'])->eraseAll();
				pjReservationPaymentModel::factory()->where('reservation_id', $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteReservationBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjReservationModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjReservationExtraModel::factory()->whereIn('extra_id', $_POST['record'])->eraseAll();
				pjReservationPaymentModel::factory()->whereIn('extra_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['reservation_create']))
			{
				$data = array();
				
				$data['uuid'] = time();
				$data['date'] = pjUtil::formatDate($_POST['date'], $this->option_arr['o_date_format']);
				$data['ip'] = pjUtil::getClientIp();
				
				$id = pjReservationModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_POST['extra_id']) && count($_POST['extra_id']) > 0)
					{
						$pjExtraModel = pjExtraModel::factory();
						$pjReservationExtraModel = pjReservationExtraModel::factory();
						
						foreach ($_POST['extra_id'] as $k => $extra_arr)
						{
							if(is_array($extra_arr) && count($extra_arr) > 0)
							{
								foreach($extra_arr as $x => $eid)
								{
									$extra_price = 0;
									$_arr = $pjExtraModel
										->reset()
										->find($eid)
										->getData();
									if(!empty($_arr) && !empty($_arr['price']))
									{
										$extra_price = $_arr['price'];
									}
									$pjReservationExtraModel
										->reset()
										->setAttributes(array(
											'reservation_id' => $id,
											'extra_id' => $eid,
											'category_id' => $_POST['category_id'][$k],
											'price' => $extra_price,
											'cnt' => $_POST['extra_cnt'][$k][$x]
									))->insert();
								}
							}
						}
					}
					$err = 'AR03';
				}else{
					$err = 'AR04';
				}
				
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminReservations&action=pjActionIndex&err=$err");
			}else{
				
				$category_arr = pjCategoryModel::factory()
					->select('t1.*, t2.content as name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('status', 'T')
					->orderBy("name ASC")
					->findAll()
					->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('category_arr', $category_arr);
				$this->set('country_arr', $country_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminReservations.js');
			}
		} else {
			
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['reservation_update']))
			{
				$pjReservationModel = pjReservationModel::factory();
				
				$arr = pjReservationModel::factory()->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminOrders&action=pjActionIndex&err=AR08");
				}
				
				
				$data = array();
				
				$data['date'] = pjUtil::formatDate($_POST['date'], $this->option_arr['o_date_format']);
				$data['ip'] = pjUtil::getClientIp();
				$pjReservationModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				
				$pjReservationExtraModel = pjReservationExtraModel::factory();
				$pjReservationExtraModel->where('reservation_id', $_POST['id'])->eraseAll();
				
				if (isset($_POST['extra_id']) && count($_POST['extra_id']) > 0)
				{
					$pjExtraModel = pjExtraModel::factory();
				
					foreach ($_POST['extra_id'] as $k => $extra_arr)
					{
						if(is_array($extra_arr) && count($extra_arr) > 0)
						{
							foreach($extra_arr as $x => $eid)
							{
								$extra_price = 0;
								$_arr = $pjExtraModel
									->reset()
									->find($eid)
									->getData();
								if(!empty($_arr) && !empty($_arr['price']))
								{
									$extra_price = $_arr['price'];
								}
								$pjReservationExtraModel
									->reset()
									->setAttributes(array(
											'reservation_id' => $_POST['id'],
											'extra_id' => $eid,
											'category_id' => $_POST['category_id'][$k],
											'price' => $extra_price,
											'cnt' => $_POST['extra_cnt'][$k][$x]
									))->insert();
							}
						}
					}
				}
				
				$err = 'AR01';
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminReservations&action=pjActionIndex&err=$err");
			}else{
				
				$arr = pjReservationModel::factory()->find($_GET['id'])->getData();
				if(count($arr) <= 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminReservations&action=pjActionIndex&err=AR08");
				}
				$this->set('arr', $arr);
				
				$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('country_arr', $country_arr);
				
				$category_arr = pjCategoryModel::factory()
					->select('t1.*, t2.content as name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('status', 'T')
					->orderBy("name ASC")
					->findAll()
					->getData();
				$this->set('category_arr', $category_arr);
				
				$_reserved_extra_arr = pjReservationExtraModel::factory()->where('t1.reservation_id', $_GET['id'])->findAll()->getData();
				
				$reserved_extra_arr = array();
				foreach($_reserved_extra_arr as $v)
				{
					if(isset($reserved_extra_arr[$v['category_id']]))
					{
						$reserved_extra_arr[$v['category_id']][] = $v;
					}else{
						$reserved_extra_arr[$v['category_id']] = array();
						$reserved_extra_arr[$v['category_id']][] = $v;
					}
				}
				$this->set('reserved_extra_arr', $reserved_extra_arr);
				
				$extra_arr = array();
				if(!empty($reserved_extra_arr))
				{
					$_extra_arr = pjCategoryExtraModel::factory()
						->select('t1.*, t2.content as title, t3.price')
						->join('pjMultiLang', "t2.model='pjExtra' AND t2.foreign_id=t1.extra_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->join('pjExtra', "t1.extra_id=t3.id", 'left outer')
						->whereIn('t1.category_id', array_keys($reserved_extra_arr))
						->findAll()
						->getData();
					
					foreach($_extra_arr as $v)
					{
						if(isset($extra_arr[$v['category_id']]))
						{
							$extra_arr[$v['category_id']][] = $v;
						}else{
							$extra_arr[$v['category_id']] = array();
							$extra_arr[$v['category_id']][] = $v;
						}
					}
					
				}
				
				$this->set('extra_arr', $extra_arr);
				
				$where_str = " AND `TR`.id <> '".$arr['id']."'";
				$date = $arr['date'];
				$booth_arr = pjBoothModel::factory()
					->select("t1.*, t2.content AS type,
								(SELECT SUM(`TR`.cnt) FROM `".pjReservationModel::factory()->getTable()."` AS `TR` WHERE `TR`.`date`='".$date."' AND `TR`.status <> 'cancelled' AND `TR`.booth_id=t1.id".$where_str.") AS cnt_booked,
								(SELECT `TP`.price FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.`date`='".$date."' AND `TP`.booth_id=t1.id LIMIT 1) AS custom_price")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjBooth' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'type'", 'left')
					->orderBy("type ASC")
					->findAll()
					->getData();
					
				$this->set('booth_arr', $booth_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminReservations.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetExtras()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_GET['category_id']) && (int) $_GET['category_id'] > 0)
			{
				$extra_arr = pjExtraModel::factory()
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
					->select("t1.*, t2.content AS title")
					->where("t1.id IN (SELECT TCE.extra_id FROM `".pjCategoryExtraModel::factory()->getTable()."` AS TCE WHERE TCE.category_id=".$_GET['category_id'].")")
					->orderBy("title ASC")
					->findAll()
					->getData();
				$this->set('extra_arr', $extra_arr);
			}
		}
	}
	
	public function pjActionGetBooths()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['date']) && !empty($_POST['date']))
			{
				$date = pjUtil::formatDate($_POST['date'], $this->option_arr['o_date_format']);
				
				$pjDateModel = pjDateModel::factory()->where("('$date' BETWEEN `start_date` AND `end_date`)");
				
				if($pjDateModel->findCount()->getData() == 0)
				{
					$where_str = '';
					if(isset($_POST['id']) && (int) $_POST['id'] > 0)
					{
						$where_str .= " AND `TR`.id <> '".$_POST['id']."'";
					}
					
					$booth_arr = pjBoothModel::factory()
						->select("t1.*, t2.content AS type, 
								(SELECT SUM(`TR`.cnt) FROM `".pjReservationModel::factory()->getTable()."` AS `TR` WHERE `TR`.`date`='".$date."' AND `TR`.status <> 'cancelled' AND `TR`.booth_id=t1.id".$where_str.") AS cnt_booked,
								(SELECT `TP`.price FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.`date`='".$date."' AND `TP`.booth_id=t1.id LIMIT 1) AS custom_price")
						->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjBooth' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'type'", 'left')
						->orderBy("type ASC")
						->findAll()
						->getData();
					
					$this->set('booth_arr', $booth_arr);
				}
			}
		}
	}
	
	public function pjActionPrint()
	{
		$this->checkLogin();
	
		$this->setLayout('pjActionPrint');
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$pjReservationModel = pjReservationModel::factory();
			$today_arr = $pjReservationModel
				->select("t1.*, t2.content as type")
				->join('pjMultiLang', "t2.model='pjBooth' AND t2.foreign_id=t1.booth_id AND t2.field='type' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where("(DATE(date)=CURDATE() AND (t1.status='confirmed' OR t1.status='pending'))")
				->findAll()
				->getData();
			
			$reservation_id_arr = $pjReservationModel->findAll()->getDataPair(null, 'id');
			
			$extras = array();
			$category_id_arr = array();
			$extra_id_arr = array();
			$category_arr = array();
			$extra_arr = array();
			if(!empty($reservation_id_arr))
			{
				$pjReservationExtraModel = pjReservationExtraModel::factory();
				$_arr = $pjReservationExtraModel
					->whereIn('reservation_id', $reservation_id_arr)
					->findAll()
					->getData();
				foreach($_arr as $k => $v)
				{
					$extras[$v['reservation_id']][$v['category_id']][$v['extra_id']] = array('cnt' => $v['cnt'], 'price' => $v['price']);
					if(!in_array($v['category_id'], $category_id_arr))
					{
						$category_id_arr[] = $v['category_id'];
					}
					if(!in_array($v['extra_id'], $extra_id_arr))
					{
						$extra_id_arr[] = $v['extra_id'];
					}
				}
			}
			if(!empty($category_id_arr))
			{
				$category_arr = pjCategoryModel::factory()
					->select('t1.*, t2.content as name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->whereIn('t1.id', $category_id_arr)
					->findAll()
					->getDataPair('id', 'name');
			}
			if(!empty($extra_id_arr))
			{
				$extra_arr = pjExtraModel::factory()
					->select("t1.*, t2.content AS title")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
					->whereIn('t1.id', $extra_id_arr)
					->findAll()
					->getDataPair('id', 'title');
			}
			
			$this->set('today_arr', $today_arr);
			$this->set('extras', $extras);
			$this->set('category_arr', $category_arr);
			$this->set('extra_arr', $extra_arr);
		} else {
			$this->set('status', 2);
		}
	}
}
?>