<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdmin extends pjAppController
{
	public $defaultUser = 'admin_user';
	
	public $requireLogin = true;
	
	protected $adminBooking = 'Admin_Booking';
	
	public function __construct($requireLogin=null)
	{
		$this->setLayout('pjActionAdmin');
		
		if (!is_null($requireLogin) && is_bool($requireLogin))
		{
			$this->requireLogin = $requireLogin;
		}
		
		if ($this->requireLogin)
		{
			if (!$this->isLoged() && !in_array(@$_GET['action'], array('pjActionLogin', 'pjActionForgot')))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
			}
		}
	}
	
	public function beforeRender()
	{
		
	}
		
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$pjBookingModel = pjBookingModel::factory();
			$pjItemModel = pjItemModel::factory();
			
			$cnt_today_bookings = $pjBookingModel->where("DATE(created) = CURDATE()")->findCount()->getData();
			$cnt_items_avail_today = 0;
			
			$price_period = sprintf(",
					(SELECT MIN(`price`) FROM `%1\$s`
						WHERE `foreign_id` = `t1`.`id`
						AND `type` = 'item'
						LIMIT 1) AS `price`,
					(SELECT `period`
						FROM `%1\$s`
						WHERE `foreign_id` = `t1`.`id`
						AND `type` = 'item'
						GROUP BY `period`
						HAVING MIN(`price`)
						LIMIT 1) AS `period`
					",
					pjPriceModel::factory()->getTable()
			);
			$booked_qty = sprintf(",
					(SELECT COALESCE(SUM(bi.qty), 0)
					FROM `%1\$s` AS `bi`
					INNER JOIN `%2\$s` AS `b` ON b.id = bi.booking_id
						AND b.dt_from <= '%6\$s'
						AND b.dt_to > '%5\$s'
						AND b.status = 'confirmed'
					WHERE (bi.foreign_id = t1.id AND bi.type = 'item')
					OR (bi.foreign_id IN (SELECT pi.package_id
							FROM `%3\$s` AS `pi`
							INNER JOIN `%4\$s` AS `p` ON p.id = pi.package_id
							WHERE pi.item_id = t1.id) AND bi.type = 'package')
					LIMIT 1) AS `booked_qty`",
					pjBookingItemModel::factory()->getTable(),
					pjBookingModel::factory()->getTable(),
					pjPackageItemModel::factory()->getTable(),
					pjPackageModel::factory()->getTable(),
					date('Y-m-d'), date('Y-m-d')
			);
			
			$items = $pjItemModel
			    ->select(sprintf("t1.*, t2.content AS `title`,
					(SELECT MIN(cnt)
						FROM `%1\$s` AS `t2`
						WHERE `t1`.`id`=`t2`.`item_id`
						AND CURDATE() BETWEEN `t2`.`date_from` AND `t2`.`date_to`
					) AS `min_cnt`, %2\$s, %3\$s",
			    pjAvailabilityModel::factory()->getTable(), $price_period, $booked_qty))
			    ->join('pjMultiLang', "t2.model='pjItem' AND t2.foreign_id=t1.id AND t2.locale='".$this->getLocaleId()."' AND t2.field='title'", 'left outer')
			    ->where('t1.is_active', 1)
			    ->findAll()
			    ->getData();
			
			$ongoing_arr = array();
			foreach($items as $item)
			{
				$max_cnt = pjUtil::getMaxCount($item['cnt'], $item['cnt'], $item['min_cnt']);
				if($max_cnt > 0 && (int) $max_cnt >= (int) $item['booked_qty'] + 1)
				{
					$cnt_items_avail_today = $cnt_items_avail_today + $max_cnt;
					if(isset($ongoing_arr[$item['category_id']]['products']))
					{
						$ongoing_arr[$item['category_id']]['products'] = $ongoing_arr[$item['category_id']]['products'] + 1;
					}else{
						$ongoing_arr[$item['category_id']]['products'] = 1;
					}
					if(isset($ongoing_arr[$item['category_id']]['items']))
					{
						$ongoing_arr[$item['category_id']]['items'] = $ongoing_arr[$item['category_id']]['items'] + $max_cnt;
					}else{
						$ongoing_arr[$item['category_id']]['items'] = $max_cnt;
					}
				}
			}
			
			$latest_booking_arr = $pjBookingModel
				->reset()
				->select('t1.id, t1.uuid, t1.c_name, t1.dt_from, t1.dt_to, t1.created, t1.total')
				->index('FORCE INDEX (`status`)')
				->where("(t1.status = 'confirmed' OR t1.status = 'pending')")
				->orderBy('t1.created DESC')
				->limit(5)
				->findAll()
				->getData();
			
			$cnt_ongoing = $pjBookingModel
				->reset()
				->where('t1.status', 'confirmed')
				->where("CURDATE() BETWEEN DATE(t1.dt_from) AND DATE(t1.dt_to)")
				->findCount()
				->getData();
			
			$category_arr = pjCategoryModel::factory()
				->select('t1.*, t2.content AS title')
				->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.is_active', '1')
				->orderBy("title ASC")
				->findAll()
				->getData();
			$avail_arr = array();
			foreach($category_arr as $k => $category)
			{
				if(isset($ongoing_arr[$category['id']]) && $ongoing_arr[$category['id']]['products'] > 0)
				{
					$category['ongoing'] = $ongoing_arr[$category['id']];
				}
				$avail_arr[] = $category;
			}
			
			$tbl = pjBookingItemModel::factory()->getTable();
			$ongoing_arr = $pjBookingModel
				->reset()
				->select("t1.*, (SELECT COUNT(TBI.foreign_id) FROM `".$tbl."` AS `TBI` WHERE TBI.booking_id=t1.id) AS products, (SELECT SUM(TBI.qty) FROM `".$tbl."` AS `TBI` WHERE TBI.booking_id=t1.id) AS items")
				->where('t1.status', 'confirmed')
				->where("CURDATE() BETWEEN DATE(t1.dt_from) AND DATE(t1.dt_to)")
				->orderBy("t1.dt_from ASC")
				->findAll()
				->getData();
			
			$date_from = $dt_from = date('Y-m-d');
			$date_to = $dt_to = date('Y-m-d');
			
			$_package_arr = pjPackageModel::factory()
				->select(sprintf("t1.*, t2.content AS `title`, 'package' AS `type`,
							(SELECT MIN(cnt) FROM `%1\$s` AS `t2` WHERE `t2`.`item_id` IN (SELECT `item_id` FROM `%9\$s` WHERE `package_id` = `t1`.`id`) AND CURDATE() BETWEEN `t2`.`date_from` AND `t2`.`date_to`) AS `min_from`,
							(SELECT MIN(cnt) FROM `%1\$s` AS `t2` WHERE `t2`.`item_id` IN (SELECT `item_id` FROM `%9\$s` WHERE `package_id` = `t1`.`id`) AND CURDATE() BETWEEN `t2`.`date_from` AND `t2`.`date_to`) AS `min_to`,
							(SELECT MIN(`cnt`) FROM `%8\$s` WHERE `id` IN (SELECT `item_id` FROM `%9\$s` WHERE `package_id` = t1.id) LIMIT 1) AS `cnt`,
							(SELECT COALESCE(SUM(bi.qty), 0)
								FROM `%4\$s` AS `bi`
								INNER JOIN `%5\$s` AS `b` ON b.id = bi.booking_id
								AND b.status = 'confirmed'
								AND b.dt_from <= '%7\$s'
								AND b.dt_to > '%6\$s'
								WHERE (bi.foreign_id = t1.id AND bi.type = 'package')
								OR (bi.foreign_id IN (SELECT `item_id` FROM `%9\$s` WHERE `package_id` = t1.id) AND bi.type = 'item')
								LIMIT 1
							) AS `booked_qty`,
							(SELECT COUNT(TPI.item_id) FROM `%9\$s` AS `TPI` WHERE TPI.package_id=t1.id) AS `cnt_items`
					",
					pjAvailabilityModel::factory()->getTable(), $date_from, $date_to,
					pjBookingItemModel::factory()->getTable(), pjBookingModel::factory()->getTable(),
					$dt_from, $dt_to, pjItemModel::factory()->getTable(), pjPackageItemModel::factory()->getTable()
					))
				->join('pjMultiLang', "t2.model='pjPackage' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'")
				->where('t1.is_active', 1)
				->orderBy("`title` ASC")
				->findAll()
				->getData();
			
			$package_arr = array();
			
			foreach($_package_arr as $package)
			{
				$max_cnt = pjUtil::getMaxCount($package['cnt'], $package['min_from'], $package['min_to']);
				if($max_cnt > 0 && (int) $max_cnt >= (int) $item['booked_qty'] + 1)
				{
					$package['cnt'] = $max_cnt;
					$package_arr[] = $package;
				}
			}
			
			$this->set('cnt_today_bookings', $cnt_today_bookings);
			$this->set('cnt_items_avail_today', $cnt_items_avail_today);
			$this->set('latest_booking_arr', $latest_booking_arr);
			
			$this->set('cnt_ongoing', $cnt_ongoing);
			$this->set('avail_today_arr', $avail_arr);
			$this->set('ongoing_arr', $ongoing_arr);
			$this->set('package_arr', $package_arr);
			
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionForgot()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['forgot_user']))
		{
			if (!isset($_POST['forgot_email']) || !pjValidation::pjActionNotEmpty($_POST['forgot_email']) || !pjValidation::pjActionEmail($_POST['forgot_email']))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			}
			$pjUserModel = pjUserModel::factory();
			$user = $pjUserModel
				->where('t1.email', $_POST['forgot_email'])
				->limit(1)
				->findAll()
				->getData();
				
			if (count($user) != 1)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			} else {
				$user = $user[0];
				
				$Email = new pjEmail();
				$Email
					->setTo($user['email'])
					->setFrom($user['email'])
					->setSubject(__('emailForgotSubject', true));
				
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$Email
						->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'])
					;
				}
				
				$body = str_replace(
					array('{Name}', '{Password}'),
					array($user['name'], $user['password']),
					__('emailForgotBody', true)
				);

				if ($Email->send($body))
				{
					$err = "AA11";
				} else {
					$err = "AA12";
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=$err");
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionMessages()
	{
		$this->setAjax(true);
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionLogin()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['login_user']))
		{
			if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
				!pjValidation::pjActionEmail($_POST['login_email']))
			{
				// Data not validate
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
			}
			$pjUserModel = pjUserModel::factory();

			$user = $pjUserModel
				->where('t1.email', $_POST['login_email'])
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeString($_POST['login_password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();

			if (count($user) != 1)
			{
				# Login failed
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=1");
			} else {
				$user = $user[0];
				unset($user['password']);
															
				if (!in_array($user['role_id'], array(1)))
				{
					# Login denied
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
				}
				
				if ($user['status'] != 'T')
				{
					# Login forbidden
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=3");
				}
				
				# Login succeed
				$last_login = date("Y-m-d H:i:s");
				$user['last_login'] = $last_login;
    			$_SESSION[$this->defaultUser] = $user;
    			
    			# Update
    			$data = array();
    			$data['last_login'] = $last_login;
    			$pjUserModel->reset()->set('id', $user['id'])->modify($data);

    			if ($this->isAdmin())
    			{
	    			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
    			}
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionLogout()
	{
		if ($this->isLoged())
        {
        	unset($_SESSION[$this->defaultUser]);
        }
       	pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
	}
	
	public function pjActionProfile()
	{
		$this->checkLogin();
		
		if (!$this->isAdmin())
		{
			if (isset($_POST['profile_update']))
			{
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->find($this->getUserId())->getData();
				$data = array();
				$data['role_id'] = $arr['role_id'];
				$data['status'] = $arr['status'];
				$post = array_merge($_POST, $data);
				if (!$pjUserModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA14");
				}
				$pjUserModel->set('id', $this->getUserId())->modify($post);
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA13");
			} else {
				$this->set('arr', pjUserModel::factory()->find($this->getUserId())->getData());
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdmin.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>