<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminPrices extends pjAdmin
{
    public function pjActionCheckDates()
    {
        $this->setAjax(true);
        if ($this->isXHR())
        {
            $post = $this->_post->raw();
            if(!isset($post['space_id']))
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => __('lblPricesSavedDesc', true)));
            }
            if(count($post['space_id']) > 1)
            {
                foreach ($post['space_id'] as $index => $space_id)
                {
                    $date_from = pjDateTime::formatDate($post['date_from'][$index], $this->option_arr['o_date_format']);
                    $date_to = pjDateTime::formatDate($post['date_to'][$index], $this->option_arr['o_date_format']);
                    foreach ($post['space_id'] as $idx => $sid)
                    {
                        if($index != $idx)
                        {
                            $check_date_from = pjDateTime::formatDate($post['date_from'][$idx], $this->option_arr['o_date_format']);
                            $check_date_to = pjDateTime::formatDate($post['date_to'][$idx], $this->option_arr['o_date_format']);
                            if($space_id == $sid && (($check_date_from <= $date_from && $date_from <= $check_date_to) || ($check_date_to >= $date_to && $date_to >= $check_date_from)))
                            {
                                self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'index' => $index, 'idx' => $idx, 'text' => __('lblDuplicatedPeriodDesc', true)));
                            }
                        }
                    }
                }
            }
        }
        self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
    }
    
	public function pjActionIndex()
	{
		$this->checkLogin();
	    if (!pjAuth::factory('pjAdminPrices', 'pjActionIndex')->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	    
	    $pjPriceModel = pjPriceModel::factory();
			
		$price_arr = $pjPriceModel
			->orderBy("t1.space_id ASC, t1.date_from ASC, t1.date_to ASC, t1.price ASC")
			->findAll()
			->getData();
			
		if (self::isPost() && $this->_post->check('price_update'))
		{
			$post = $this->_post->raw();
			$remove_id_arr = array();
			foreach($price_arr as $price)
			{
				if(!isset($post['space_id'][$price['id']]))
				{
					$remove_id_arr[] = $price['id'];
				}
			}
			foreach ($post['space_id'] as $index => $space_id)
			{
				if ((int) $space_id > 0 && !empty($post['date_from'][$index]) && !empty($post['date_to'][$index]) && !empty($post['price'][$index]))
				{
					$data = array();
					$data['space_id'] = $space_id;
					$data['date_from'] = pjDateTime::formatDate($post['date_from'][$index], $this->option_arr['o_date_format']);
					$data['date_to'] = pjDateTime::formatDate($post['date_to'][$index], $this->option_arr['o_date_format']);
					$data['price'] = $post['price'][$index];
					
					if (isset($post['id'][$index]))
					{
						$pjPriceModel->reset()->where('id', $post['id'][$index])->limit(1)->modifyAll($data);
					}else{
						$pjPriceModel->reset()->setAttributes($data)->insert();
					}
				}
			}
			if(!empty($remove_id_arr))
			{
				$pjPriceModel->reset()->whereIn('id', $remove_id_arr)->eraseAll();
			}
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminPrices&action=pjActionIndex&err=AP01");
		} 
		
		if (self::isGet())
		{
    		$space_arr = pjSpaceModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSpace' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
				->select("t1.*, t2.content AS name")
				->where('t1.status', 'T')
				->orderBy("name ASC")
				->findAll()
				->getData();
			
			$this->set('space_arr', $space_arr);
			$this->set('price_arr', $price_arr);
			
			$this->appendCss('datepicker3.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
			$this->appendJs('bootstrap-datepicker.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
    		$this->appendJs('pjAdminPrices.js');
		}
	}
	
	public function pjActionDiscount()
	{
		$this->checkLogin();
	    if (!pjAuth::factory('pjAdminPrices', 'pjActionDiscount')->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	    $pjDiscountModel = pjDiscountModel::factory();
				
		$discount_arr = $pjDiscountModel
			->orderBy("t1.space_id ASC, t1.min_days ASC, t1.max_days ASC, t1.price ASc")
			->findAll()
			->getData();
			
		if (self::isPost() && $this->_post->check('discount_update'))
		{
			$post = $this->_post->raw();
			$remove_id_arr = array();
			foreach($discount_arr as $discount)
			{
				if(!isset($post['space_id'][$discount['id']]))
				{
					$remove_id_arr[] = $discount['id'];
				}
			}
			foreach ($post['space_id'] as $index => $space_id)
			{
				if ((int) $space_id > 0 && (int) $post['price_id'][$index] > 0 && (int) $post['min_days'][$index] > 0 && (int) $post['max_days'][$index] > 0 && !empty($post['price'][$index]))
				{
					$data = array();
					$data['space_id'] = $space_id;
					$data['price_id'] = $post['price_id'][$index];
					$data['min_days'] = $post['min_days'][$index];
					$data['max_days'] = $post['max_days'][$index];
					$data['price'] = $post['price'][$index];

					if (isset($post['id'][$index]))
					{
						$pjDiscountModel->reset()->where('id', $post['id'][$index])->limit(1)->modifyAll($data);
					}else{
						$pjDiscountModel->reset()->setAttributes($data)->insert();
					}
				}
			}
			if(!empty($remove_id_arr))
			{
				$pjDiscountModel->reset()->whereIn('id', $remove_id_arr)->eraseAll();
			}
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminPrices&action=pjActionDiscount&err=AD01");
		} 
		
		if (self::isGet())
		{
    		$space_arr = pjSpaceModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSpace' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
				->select("t1.*, t2.content AS name")
				->where('t1.status', 'T')
				->orderBy("name ASC")
				->findAll()
				->getData();
				
			$price_arr = pjPriceModel::factory()
					->orderBy("t1.date_from ASC, t1.date_to ASC")
					->findAll()
					->getData();
					
			$this->set('space_arr', $space_arr);
			$this->set('price_arr', $price_arr);
			$this->set('discount_arr', $discount_arr);
			
    		$this->appendJs('pjAdminPrices.js');
		}
	}	
	
	public function pjActionGetDateRange()
	{
		$this->checkLogin();
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = array();
			$get = $this->_get->raw();
			if((int) $get['space_id'] > 0)
			{
				$arr = pjPriceModel::factory()
					->where('t1.space_id', $get['space_id'])
					->orderBy("t1.date_from ASC, t1.date_to ASC")
					->findAll()
					->getData();
			}
			$this->set('arr', $arr);
			$this->set('get', $get);
		}
	}
}
?>