<?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')))
			{
				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::pjActionPaymentOptions' => 'pjAdminOptions::pjActionPayments',
			'pjAdminPrices::pjActionDeleteSeason' => 'pjAdminPrices::pjActionSave',
			'pjAdminPrices::pjActionDeleteAll' => 'pjAdminPrices::pjActionSave',
			'pjAdminPrices::pjActionBeforeSave' => 'pjAdminPrices::pjActionSave',
			'pjAdminExtras::pjActionAddExtra' => 'pjAdminExtras::pjActionCreate',
			'pjAdminExtras::pjActionSaveExtra' => 'pjAdminExtras::pjActionUpdate',
			'pjAdminClients::pjActionSaveClient' => 'pjAdminClients::pjActionUpdate',
			'pjAdminLimits::pjActionAddLimit' => 'pjAdminLimits::pjActionCreate',
			'pjAdminRestrictions::pjActionAddRestriction' => 'pjAdminRestrictions::pjActionCreate',
			'pjAdminRestrictions::pjActionSaveRestriction' => 'pjAdminRestrictions::pjActionUpdate',
			'pjAdminDiscounts::pjActionSavePackage' => 'pjAdminDiscounts::pjActionUpdatePackage',
			'pjAdminDiscounts::pjActionSaveCode' => 'pjAdminDiscounts::pjActionUpdateCode',
			'pjAdminDiscounts::pjActionSaveFree' => 'pjAdminDiscounts::pjActionUpdateFree',
			'pjAdminOptions::pjActionUpdateTheme' => 'pjAdminOptions::pjActionPreview',
			'pjAdminReports::pjActionPrintReport' => 'pjAdminReports::pjActionIndex',
			'pjBasePermissions::pjActionResetPermission' => 'pjBasePermissions::pjActionUserPermission'
		);
		if ($_REQUEST['controller'] == 'pjAdminOptions' && isset($_REQUEST['next_action'])) {
			$inherits_arr['pjAdminOptions::pjActionUpdate'] = 'pjAdminOptions::'.$_REQUEST['next_action'];
		}
		$inherits_arr = array_merge($ref_inherits_arr, $inherits_arr);
		pjRegistry::getInstance()->set('inherits', $inherits_arr);
	}
	public function beforeFilter()
	{
		parent::beforeFilter();

		if (!pjAuth::factory()->hasAccess())
		{
			$this->sendForbidden();
			return false;
		}
		
		return true;
	}
	
	public function afterFilter()
	{
		parent::afterFilter();
		$this->appendJs('index.php?controller=pjBase&action=pjActionMessages', PJ_INSTALL_URL, true);
	}
	
	public function beforeRender()
	{

	}
	
	public function setLocalesData()
    {
        $locale_arr = pjLocaleModel::factory()
            ->select('t1.*, t2.file')
            ->join('pjBaseLocaleLanguage', 't2.iso=t1.language_iso', 'left')
            ->where('t2.file IS NOT NULL')
            ->orderBy('t1.sort ASC')->findAll()->getData();

        $lp_arr = array();
        foreach ($locale_arr as $item)
        {
            $lp_arr[$item['id']."_"] = $item['file'];
        }
        $this->set('lp_arr', $locale_arr);
        $this->set('locale_str', pjAppController::jsonEncode($lp_arr));
        $this->set('is_flag_ready', $this->requestAction(array('controller' => 'pjBaseLocale', 'action' => 'pjActionIsFlagReady'), array('return')));
    }
	
    public function pjActionVerifyAPIKey()
    {
        $this->setAjax(true);

        if ($this->isXHR())
        {
            if (!self::isPost())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'HTTP method is not allowed.'));
            }

            $option_key = $this->_post->toString('key');
            if (!array_key_exists($option_key, $this->option_arr))
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Option cannot be found.'));
            }

            $option_value = $this->_post->toString('value');
            if(empty($option_value))
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'API key is empty.'));
            }

            $html = '';
            $isValid = false;
            switch ($option_key)
            {
                case 'o_google_maps_api_key':
                    $address = preg_replace('/\s+/', '+', $this->option_arr['o_timezone']);
                    $api_key_str = $option_value;
                    $gfile = "https://maps.googleapis.com/maps/api/geocode/json?key=".$api_key_str."&address=".$address;
                    $Http = new pjHttp();
                    $response = $Http->request($gfile)->getResponse();
                    $geoObj = pjAppController::jsonDecode($response);
                    $geoArr = (array) $geoObj;
                    if ($geoArr['status'] == 'OK')
                    {
                        $isValid = true;
                    }
                    break;
                default:
                    // API key for an unknown service. We can't verify it so we assume it's correct.
                    $isValid = true;
            }

            if ($isValid)
            {
                self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Key is correct!', 'html' => $html));
            }
            else
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Key is not correct!', 'html' => $html));
            }
        }
        exit;
    }
    private function writeSql($sql)
    {
        $file = 'database.sql';
        file_put_contents($file, $sql, FILE_APPEND | LOCK_EX);
    }
    public function pjActionGenerateTitles()
    {
        $pjBaseFieldModel = pjBaseFieldModel::factory();
        $pjBaseMultiLangModel = pjBaseMultiLangModel::factory();
        
        $sql = array();
        $locale_id = $this->getLocaleId();
        $f_arr = $pjBaseFieldModel->where('source', 'script')->orderBy("`key` ASC")->findAll()->getData();
        foreach ($f_arr as $result)
        {
            $arr = $pjBaseMultiLangModel
            ->reset()
            ->select('t1.*')
            ->where('t1.foreign_id', $result['id'])
            ->where('t1.model','pjBaseField')
            ->where('t1.locale', $locale_id)
            ->where('t1.field', 'title')
            ->limit(0, 1)
            ->findAll()
            ->getDataIndex(0);
            
            $key = $result['key'];
            $type = $result['type'];
            $label = $content = str_replace("'", "''", $result['label']);
            
            $content = $arr['content'];
            $content = str_replace("'", "''", $content);
                        
            $sql[] = "INSERT INTO `plugin_base_fields` VALUES (NULL, '{$key}', '{$type}', '{$label}', 'script', NULL);";
            $sql[] = "\n";
            $sql[] = "SET @id := (SELECT LAST_INSERT_ID());";
            $sql[] = "\n";
            $sql[] = "INSERT INTO `plugin_base_multi_lang` VALUES (NULL, @id, 'pjBaseField', '::LOCALE::', 'title', '{$content}', 'script');";
            $sql[] = "\n";
            $sql[] = "\n";
        }
        $this->writeSql(join("", $sql));
        echo 'done';
        exit;
    }
	public function pjActionIndex()
	{
	    $this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	    						
		$pjBookingModel = pjBookingModel::factory();
		$pjRoomModel = pjRoomModel::factory();
		$pjRoomNumberModel = pjRoomNumberModel::factory();
		$pjBookingRoomModel = pjBookingRoomModel::factory();
		$pjMultiLangModel = pjMultiLangModel::factory();
		
		
		$today = date('Y-m-d');
		$nightMode = $this->option_arr['o_price_based_on'] == 'nights';
		
		$latest_booking_arr = array();
		$latest_count = $pjBookingModel->findCount()->getData();
		if ($latest_count > 0)
		{
			$statement = sprintf("SELECT TB.*, `TAU`.phone AS c_phone, `TAU`.name AS c_name, DATEDIFF(`date_to`, `date_from`) AS nights,
				(SELECT GROUP_CONCAT(CONCAT_WS(:ws, `m`.`content`, `TRN`.`number`) SEPARATOR :sep) 
					FROM `%3\$s` AS `TBR` 
					INNER JOIN `%1\$s` AS `TR` ON `TR`.id = `TBR`.`room_id` 
					INNER JOIN `%4\$s` AS `TRN` ON `TRN`.id = `TBR`.`room_number_id`
					LEFT OUTER JOIN `%5\$s` AS `m` ON m.model=:model AND m.foreign_id=TR.id AND m.field=:field AND m.locale=:locale
					WHERE `TBR`.`booking_id`=`TB`.`id`) AS `rooms`
				FROM `%2\$s` AS TB INNER JOIN `%6\$s` AS `TC` ON `TB`.client_id = `TC`.`id` INNER JOIN `%7\$s` AS `TAU` ON `TC`.foreign_id = `TAU`.`id` 
				WHERE 1 
				ORDER BY created DESC 
				LIMIT 0,2",
				$pjRoomModel->getTable(),
				$pjBookingModel->getTable(),
				$pjBookingRoomModel->getTable(),
				$pjRoomNumberModel->getTable(),
				$pjMultiLangModel->getTable(),
			    pjClientModel::factory()->getTable(),
			    pjAuthUserModel::factory()->getTable()
			);
			
			$latest_booking_arr = $pjBookingModel->reset()->prepare($statement)->exec(array(
				'model' => 'pjRoom',
				'field' => 'name',
				'locale' => $this->getLocaleId(),
				'sep' => ', ',
				'ws' => ' '
			))->getData();
		}
		$this->set('latest_booking_arr', $latest_booking_arr);
		
		$arrivals_arr = array();
		$arrival_count = $pjBookingModel
			->reset()
			->where('t1.status', 'confirmed')
			->where('t1.date_from', $today)
			->findCount()
			->getData();
		if ($arrival_count > 0)
		{
			$statement = sprintf("SELECT TB.*, DATEDIFF(`date_to`, `date_from`) AS `nights`,
				(SELECT GROUP_CONCAT(CONCAT_WS(:ws, `m`.`content`, `TRN`.`number`) SEPARATOR :sep) 
					FROM `%3\$s` AS `TBR` 
					INNER JOIN `%1\$s` AS `TR` ON `TR`.id = `TBR`.`room_id` 
					INNER JOIN `%4\$s` AS `TRN` ON `TRN`.id = `TBR`.`room_number_id` 
					LEFT OUTER JOIN `%5\$s` AS `m` ON m.model=:model AND m.foreign_id=TR.id AND m.field=:field AND m.locale=:locale
					WHERE `TBR`.`booking_id`=`TB`.`id`
				) AS `rooms`
				FROM `%2\$s` AS TB 
				WHERE `date_from` = :today 
				AND `status` = :confirmed
				ORDER BY created DESC",
				$pjRoomModel->getTable(),
				$pjBookingModel->getTable(),
				$pjBookingRoomModel->getTable(),
				$pjRoomNumberModel->getTable(),
				$pjMultiLangModel->getTable()
			);
			$arrivals_arr = $pjBookingModel->reset()->prepare($statement)->exec(array(
				'today' => $today,
				'confirmed' => 'confirmed',
				'ws' => ' ',
				'sep' => ', ',
				'model' => 'pjRoom',
				'field' => 'name',
				'locale' => $this->getLocaleId()
			))->getData();
		}
		$this->set('arrival_count', $arrival_count);
		$this->set('arrivals_arr', $arrivals_arr);
		
		$departure_arr = array();
		$departure_count = $pjBookingModel->reset()->where('t1.status', 'confirmed')->where('t1.date_to', $today)->findCount()->getData();
		if ($departure_count > 0)
		{
			$statement = sprintf("SELECT TB.*, DATEDIFF(`date_to`, `date_from`) AS `nights`,
					(SELECT GROUP_CONCAT(CONCAT_WS(:ws, `m`.`content`, `TRN`.`number`) SEPARATOR :sep) 
						FROM `%3\$s` AS `TBR` 
						INNER JOIN `%1\$s` AS `TR` ON `TR`.id = `TBR`.`room_id` 
						INNER JOIN `%4\$s` AS `TRN` ON `TRN`.id = `TBR`.`room_number_id`
						LEFT OUTER JOIN `%5\$s` AS `m` ON m.model=:model AND m.foreign_id=TR.id AND m.field=:field AND m.locale=:locale 
						WHERE `TBR`.`booking_id`=`TB`.`id`) AS `rooms`
					FROM `%2\$s` AS `TB`
					WHERE `date_to` = :today 
					AND `status` = :status
					ORDER BY `created` DESC",
				$pjRoomModel->getTable(),
				$pjBookingModel->getTable(),
				$pjBookingRoomModel->getTable(),
				$pjRoomNumberModel->getTable(),
				$pjMultiLangModel->getTable()
			);
			$departure_arr = $pjBookingModel->reset()->prepare($statement)->exec(array(
				'status' => 'confirmed',
				'today' => $today,
				'ws' => ' ',
				'sep' => ', ',
				'model' => 'pjRoom',
				'field' => 'name',
				'locale' => $this->getLocaleId()
			))->getData();
		}
		$this->set('departure_count', $departure_count);
		$this->set('departure_arr', $departure_arr);
		
		$statement = sprintf("SELECT 1,
			(SELECT COUNT(room_id) FROM `%3\$s` AS `t1` INNER JOIN `%1\$s` AS `t2` ON t2.id = t1.room_id WHERE 1 AND t1.booking_id IN (
				SELECT `TB`.`id` 
				FROM `%2\$s` AS TB 
				WHERE TB.status = :confirmed 
				AND TB.`date_from` <= :today 
				AND :today <= TB.`date_to`) LIMIT 1) AS `booked_today`,
			(SELECT COUNT(room_id) FROM `%3\$s` AS `t1` INNER JOIN `%1\$s` AS `t2` ON t2.id = t1.room_id WHERE 1 AND t1.booking_id IN (
				SELECT `TB`.`id` 
				FROM `%2\$s` AS TB 
				WHERE TB.status = :pending 
				AND TB.`date_from` <= :today 
				AND :today <= TB.`date_to`) LIMIT 1) AS `pending_today`,
			(SELECT SUM(`cnt`) FROM `%1\$s` AS `TR` WHERE 1) AS `total_rooms`",
			$pjRoomModel->getTable(),
			$pjBookingModel->getTable(),
			$pjBookingRoomModel->getTable()
		);
		$this->set('arr', $pjBookingModel->reset()->prepare($statement)->exec(array(
			'today' => $today,
			'confirmed' => 'confirmed',
			'pending' => 'pending'
		))->getDataIndex(0));
		
		$room_count = $pjRoomModel->findCount()->getData();
		if ($room_count > 0)
		{
			$statement = sprintf("SELECT TR.*, m.content AS `name`,
						(SELECT COUNT(room_id) FROM `%3\$s` AS TBR WHERE TBR.room_id=TR.id AND TBR.booking_id IN (SELECT TB.id FROM `%2\$s` AS TB WHERE TB.`date_from` %5\$s :today AND :today %6\$s TB.`date_to` AND TB.status=:confirmed)) AS `booked_rooms`,
						(SELECT COUNT(room_id) FROM `%3\$s` AS TBR WHERE TBR.room_id=TR.id AND TBR.booking_id IN (SELECT TB.id FROM `%2\$s` AS TB WHERE TB.`date_from` %5\$s :today AND :today %6\$s TB.`date_to` AND TB.status=:pending)) AS `pending_rooms` 
					FROM `%1\$s` AS TR
					LEFT OUTER JOIN `%4\$s` AS `m` ON m.model=:model AND m.foreign_id=TR.id AND m.field=:field AND m.locale=:locale
					WHERE 1 
					ORDER BY `name` ASC",
				$pjRoomModel->getTable(),
				$pjBookingModel->getTable(),
				$pjBookingRoomModel->getTable(),
				$pjMultiLangModel->getTable(),
				$nightMode ? '<=' : '<',
				$nightMode ? '<' : '<'
			);
			$this->set('avail_room_arr', $pjRoomModel->prepare($statement)->exec(array(
				'pending' => 'pending',
				'confirmed' => 'confirmed',
				'today' => $today,
				'model' => 'pjRoom',
				'field' => 'name',
				'locale' => $this->getLocaleId(),
			))->getData());
		}
		
		# Restrictions
		$restrictions = pjRestrictionRoomModel::factory()
			->select('t3.room_id, COUNT(t3.room_id) AS `cnt`')
			->join('pjRestriction', "t2.id=t1.restriction_id", 'inner')
			->join('pjRoomNumber', "t3.id=t1.room_number_id", 'inner')
			->join('pjRoom', "t4.id=t3.room_id", 'inner')
			->where(sprintf('t2.date_from %s', $nightMode ? "<" : "<="), $today)
			->where(sprintf('t2.date_to %s', $nightMode ? ">" : ">="), $today)
			->groupBy('t3.room_id')
			->findAll()
			->getDataPair('room_id', 'cnt');
		$this->set('restrictions', $restrictions);
		# Restrictions
		
		$conditions = NULL;
		# breakfast today
		#$conditions = " AND `TB`.`date_from` < :today AND :today <= `TB`.`date_to`";
		# sleeping today
		$conditions = " AND `TB`.`date_from` <= :today AND :today < `TB`.`date_to`";
		$conditions .= " AND `TB`.`status`= :confirmed";
		$statement = sprintf("SELECT 1,
				  (SELECT SUM(TBR.`adults` + TBR.`children`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `guests`,
				  (SELECT SUM(TBR.`adults`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `total_adults`,
				  (SELECT SUM(TBR.`children`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `total_children`",
			$pjRoomModel->getTable(),
			$pjBookingModel->getTable(),
			$pjBookingRoomModel->getTable(),
			$conditions
		);	
		$sleeping = $pjBookingModel->reset()->prepare($statement)->exec(array(
			'confirmed' => 'confirmed',
			'today' => $today
		))->getDataIndex(0);
		$this->set('sleeping', $sleeping);
		
		$conditions = NULL;
		$conditions = " AND `TB`.`date_from` = :today";
		$conditions .= " AND `TB`.`status` = :confirmed";
		$statement = sprintf("SELECT 1,
				(SELECT SUM(TBR.`adults` + TBR.`children`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `guests`,
				(SELECT SUM(TBR.`adults`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `total_adults`,
				(SELECT SUM(TBR.`children`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `total_children`",
			$pjRoomModel->getTable(),
			$pjBookingModel->getTable(),
			$pjBookingRoomModel->getTable(),
			$conditions
		);	
			
		$arrive_today = $pjBookingModel->reset()->prepare($statement)->exec(array(
			'today' => $today,
			'confirmed' => 'confirmed'
		))->getData();
		
		$this->set('arrive_today', $arrive_today);
			
		$conditions = NULL;
		$conditions = " AND `TB`.`date_to` = :today";
		$conditions .= " AND `TB`.`status` = :confirmed";
		$statement = sprintf("SELECT 1,
				(SELECT SUM(TBR.`adults` + TBR.`children`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `guests`,
				(SELECT SUM(TBR.`adults`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `total_adults`,
				(SELECT SUM(TBR.`children`) FROM `%3\$s` AS `TBR` WHERE `TBR`.`booking_id` IN(SELECT `TB`.`id` FROM `%2\$s` AS `TB` WHERE 1 %4\$s)) AS `total_children`",
			$pjRoomModel->getTable(),
			$pjBookingModel->getTable(),
			$pjBookingRoomModel->getTable(),
			$conditions
		);					
		$leave_today = $pjBookingModel->reset()->prepare($statement)->exec(array(
			'today' => $today,
			'confirmed' => 'confirmed'
		))->getData();
		$this->set('leave_today',  $leave_today);
		
		$this->appendJs('jsapi', 'https://www.google.com/', TRUE);
		$this->appendJs('pjAdmin.js');
		$this->appendJs('pjAdminDashboard.js');
	}
	
	public function pjActionChartGet()
	{
		$this->setAjax(true);
		
		
		$min = 1;
		$max = 7;
		if ($this->_get->check('type'))
		{
		    switch ($this->_get->toInt('type'))
			{
				case 2:
					$min = -7;
					$max = -1;
					break;
				case 1:
				default:
					$min = 1;
					$max = 7;
					break;
			}
		}
		
		$iso_date = date("Y-n-j");
		list($y, $m, $d) = explode("-", $iso_date);
			
		$bookings = array();
		
		$rooms = pjRoomModel::factory()
			->select('t1.id, t2.content AS `name`')
			->join('pjMultiLang', sprintf("t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='%u'", $this->getLocaleId()), 'left outer')
			->orderBy('`name` ASC')
			->findAll()
			->getData();
		
		$pjBookingRoomModel = pjBookingRoomModel::factory();
		foreach (range($min, $max) as $i)
		{
			$time = mktime(0, 0, 0, $m, $d+$i, $y);
			$date = date("Y-m-d", $time);
		
			$bookings[$date] = $pjBookingRoomModel
				->reset()
				->select("t1.room_id, COUNT(t1.room_id) AS `cnt`, t2.date_to")
				->join('pjBooking', "t2.id=t1.booking_id", 'inner')
				->join('pjRoom', 't3.id=t1.room_id', 'inner')
				->where('t2.status', 'confirmed')
				->where(sprintf("('%s' BETWEEN t2.date_from AND t2.date_to)", $pjBookingRoomModel->escapeStr($date)))
				->groupBy('t1.room_id, t2.date_to')
				->findAll()
				->getData();
		}
		
		$result = array('cols' => array(), 'rows' => array());
		$result['cols'][] = array(
			'id' => 0,
			'label' => 'Date',
			'type' => 'string'
		);
		foreach ($rooms as $room)
		{
			$result['cols'][] = array(
				'id' => $room['id'],
				'label' => $room['name'],
				'type' => 'number'
			);
		}
		$nightMode = $this->option_arr['o_price_based_on'] == 'nights';
		$i = 0;
		foreach ($bookings as $date => $group)
		{
			$result['rows'][$i] = array('c' => array());
			foreach ($result['cols'] as $c => $col)
			{
				if ($c == 0)
				{
					$result['rows'][$i]['c'][0] = array('v' => $date, 'f' => pjDateTime::formatDate($date, 'Y-m-d', 'd/m'));
				} else {
					$result['rows'][$i]['c'][$c] = array('v' => 0);
					foreach ($group as $item)
					{
						if ($item['room_id'] == $col['id'])
						{
							if ($nightMode && $date == $item['date_to']) {
								$result['rows'][$i]['c'][$c] = array('v' => 0);
							} else {
								$result['rows'][$i]['c'][$c] = array('v' => $item['cnt']);
							}
						}
					}
				}
			}
			$i += 1;
		}

		pjAppController::jsonResponse($result);
	}	
}
?>