<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdmin extends pjAppController
{
	public $defaultUser = 'admin_user';
	
	public $requireLogin = true;
	
	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(@$_REQUEST['action'], array('pjActionLogin', 'pjActionForgot', 'pjActionPreview', 'pjActionContact', 'pjActionExportFeed')))
			{
				if (!$this->isXHR())
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjBase&action=pjActionLogin");
				} else {
					header('HTTP/1.1 401 Unauthorized');
					exit;
				}
			}
		}

		$ref_inherits_arr = array();
		if ($this->isXHR() && isset($_SERVER['HTTP_REFERER'])) {
			$http_refer_arr = parse_url($_SERVER['HTTP_REFERER']);
			parse_str($http_refer_arr['query'], $arr);
			if (isset($arr['controller']) && isset($arr['action'])) {
				parse_str($_SERVER['QUERY_STRING'], $query_string_arr);
				$key = $query_string_arr['controller'].'_'.$query_string_arr['action'];
				$cnt = pjAuthPermissionModel::factory()->where('`key`', $key)->findCount()->getData();
				if ($cnt <= 0) {
					$ref_inherits_arr[$query_string_arr['controller'].'::'.$query_string_arr['action']] = $arr['controller'].'::'.$arr['action'];
				}
			}
		}
		$inherits_arr = array(
			'pjAdminOptions::pjActionUpdateTheme' => 'pjAdminOptions::pjActionPreview',
			'pjAdminReports::pjActionPrintReport' => 'pjAdminReports::pjActionIndex',
		    'pjAdminReports::pjActionCheckDates' => 'pjAdminReports::pjActionIndex',
			'pjBasePermissions::pjActionResetPermission' => 'pjBasePermissions::pjActionUserPermission',
			'pjAdminExtras::pjActionAddExtra' => 'pjAdminExtras::pjActionCreate',
			'pjAdminExtras::pjActionSaveExtra' => 'pjAdminExtras::pjActionUpdate',
			'pjAdminSpaces::pjActionSaveSpace' => 'pjAdminSpaces::pjActionUpdate',
			'pjVouchers::pjActionSaveVoucher' => 'pjVouchers::pjActionUpdate',
		    'pjAdminPrices::pjActionCheckDates' => 'pjAdminPrices::pjActionIndex',
            'pjAdminSpaces::pjActionCheckPeriods' => 'pjAdminSpaces::pjActionCreate',
		    'pjAdminSpaces::pjActionCheckPeriods' => 'pjAdminSpaces::pjActionUpdate'
		);
		if ($_REQUEST['controller'] == 'pjAdminOptions' && isset($_REQUEST['next_action'])) {
			$inherits_arr['pjAdminOptions::pjActionUpdate'] = 'pjAdminOptions::'.$_REQUEST['next_action'];
		}
		$inherits_arr = array_merge($inherits_arr, $ref_inherits_arr);
		pjRegistry::getInstance()->set('inherits', $inherits_arr);
	}
	
	public function beforeFilter()
	{
		parent::beforeFilter();

		if (!pjAuth::factory()->hasAccess() && @$_REQUEST['action'] != 'pjActionExportFeed')
		{
			$this->sendForbidden();
			return false;
		}
		
		if (self::isPost() && @$_REQUEST['action'] != 'pjActionExportFeed')
		{
			pjAppController::validateCsrfToken();
		}
		
		return true;
	}
	
	public function afterFilter()
	{
		parent::afterFilter();
		$this->appendJs('index.php?controller=pjBase&action=pjActionMessages', PJ_INSTALL_URL, true);
	}
	
	public function beforeRender()
	{
		
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
		
		$pjBookingModel = pjBookingModel::factory();
			
		$spaces_occupied_today = $pjBookingModel
			->where('t1.status', 'confirmed')
			->where("CURDATE() BETWEEN DATE(`from`) AND DATE(`to`)")
			->findCount()
			->getData();
		$car_coming_today = $pjBookingModel
			->reset()
			->where('t1.status', 'confirmed')
			->where("CURDATE() = DATE(`from`)")
			->findCount()
			->getData();
		$car_leaving_today = $pjBookingModel
			->reset()
			->where('t1.status', 'confirmed')
			->where("CURDATE() = DATE(`to`)")
			->findCount()
			->getData();
		
		$latest_bookings = $pjBookingModel
			->reset()
			->where('t1.status', 'confirmed')
			->orWhere('t1.status', 'pending')
			->orderBy("created DESC")
			->limit(5)
			->findAll()
			->getData();
		$coming_bookings = $pjBookingModel
			->reset()
			->where('t1.status', 'confirmed')
			->where("CURDATE() = DATE(`from`)")
			->orderBy("`from` ASC")
			->limit(5)
			->findAll()
			->getData();
		$leaving_bookings = $pjBookingModel
			->reset()
			->where('t1.status', 'confirmed')
			->where("CURDATE() = DATE(`to`)")
			->orderBy("`to` ASC")
			->limit(5)
			->findAll()
			->getData();
		
		foreach($latest_bookings as $k => $v)
		{
		    $v['days'] = pjAppController::getRentalDays($this->option_arr, date('Y-m-d', strtotime($v['from'])), date('Y-m-d', strtotime($v['to'])), date('H', strtotime($v['from'])), date('H', strtotime($v['to'])), date('i', strtotime($v['from'])), date('i', strtotime($v['to'])));
			$latest_bookings[$k] = $v;
		}	
		foreach($coming_bookings as $k => $v)
		{
		    $v['days'] = pjAppController::getRentalDays($this->option_arr, date('Y-m-d', strtotime($v['from'])), date('Y-m-d', strtotime($v['to'])), date('H', strtotime($v['from'])), date('H', strtotime($v['to'])), date('i', strtotime($v['from'])), date('i', strtotime($v['to'])));
			$coming_bookings[$k] = $v;
		}
		foreach($leaving_bookings as $k => $v)
		{
		    $v['days'] = pjAppController::getRentalDays($this->option_arr, date('Y-m-d', strtotime($v['from'])), date('Y-m-d', strtotime($v['to'])), date('H', strtotime($v['from'])), date('H', strtotime($v['to'])), date('i', strtotime($v['from'])), date('i', strtotime($v['to'])));
			$leaving_bookings[$k] = $v;
		}
		
		$this
			->set('spaces_occupied_today', $spaces_occupied_today)
			->set('car_coming_today', $car_coming_today)
			->set('car_leaving_today', $car_leaving_today)
			->set('latest_bookings', $latest_bookings)
			->set('coming_bookings', $coming_bookings)
			->set('leaving_bookings', $leaving_bookings);
	}
}
?>