<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminPrices extends pjAdmin
{
	public $sessionPrice = 'pjPrice_session';
	
	public function pjActionIndex()
	{
	    $this->checkLogin();
		if ($this->getForeignIdPrice()) {
			$pjPriceModel = pjPriceModel::factory();
			$_arr = $pjPriceModel
				->where('t1.foreign_id', $this->getForeignIdPrice())
				->orderBy('t1.tab_id ASC, t1.id ASC, t1.date_from DESC, t1.date_to DESC')
				->findAll()
				->getData();
			
			$arr = array();
			foreach ($_arr as $k => $v)
			{
				if (!isset($arr[$v['season']]))
				{
					$arr[$v['season']] = array();
				}
				$arr[$v['season']][] = $v;
			}
			
			$query = sprintf("SELECT p1.foreign_id, p1.tab_id, p2.foreign_id, p2.tab_id
				FROM (
					SELECT p1.id AS `pid1`, p2.id AS `pid2`
					FROM `%1\$s` `p1`, `%1\$s` `p2`
					WHERE p2.date_from BETWEEN p1.date_from AND p1.date_to
	                AND p2.id != p1.id
						UNION
					SELECT p1.id, p2.id
					FROM `%1\$s` `p1`, `%1\$s` `p2`
					WHERE p2.date_to BETWEEN p1.date_from AND p1.date_to
					AND p2.id != p1.id
				) `p`, `%1\$s` `p1`, `%1\$s` `p2`
				WHERE p1.id = `pid1` AND p2.id = `pid2`
				AND p2.id > p1.id
				AND p1.tab_id != p2.tab_id
				GROUP BY p1.foreign_id, p1.tab_id, p2.foreign_id, p2.tab_id", $pjPriceModel->getTable());
			$overlap_arr = $pjPriceModel->reset()->prepare($query)->exec()->getData();
			
			$this
				->set('arr', $arr)
				->set('overlap_arr', $overlap_arr)
				->set('date_format', pjUtil::toBootstrapDate($this->option_arr['o_date_format']));
		}		
		
		$this->appendCss('datepicker3.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
		$this->appendJs('bootstrap-datepicker.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
		$this->appendCss('pjPrices.css');
		$this->appendJs('pjAdminPrices.js');
	}
	
	public function pjActionDeleteAll()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Prices has been deleted.'));
	}
	
	public function pjActionBeforeSave()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!isset($_SESSION[$this->sessionPrice]) || !is_array($_SESSION[$this->sessionPrice]))
		{
			$_SESSION[$this->sessionPrice] = array();
		}
		
		if ($this->_post->check('tabs'))
		{
			$post = $this->_post->raw();
			if (isset($_SESSION[$this->sessionPrice]['tabs']))
			{
				// If you want to append array elements from the second array to the first array
				// while not overwriting the elements from the first array and not re-indexing,
				// use the + array union operator:
				$_SESSION[$this->sessionPrice]['tabs'] = $_SESSION[$this->sessionPrice]['tabs'] + $post['tabs'];
				$this->_post->remove('tabs');
			}
			
			$_SESSION[$this->sessionPrice] = array_merge($_SESSION[$this->sessionPrice], $this->_post->raw());
			self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
		}
		self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
	}
	
	public function pjActionSave()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!isset($_SESSION[$this->sessionPrice]) || empty($_SESSION[$this->sessionPrice]))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
		}
		if (!pjAuth::factory('pjAdminPrices', 'pjActionIndex')->hasAccess())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Access denied.'));
		}
		$STORE = $_SESSION[$this->sessionPrice];
		
		$tmp = array();
		$tab_ids = array();
		foreach ($STORE['tabs'] as $tab_id => $tab_name)
		{
			$tab_ids[] = $tab_id;
			$i = $tab_id;
			if (!is_int($i) || (is_int($i) && $i > 1))
			{
				$tmp_arr = $STORE[$i . '_date_from'];
				reset($tmp_arr);
				$first_key = key($tmp_arr);
				if (is_array($STORE[$i . '_date_from'][$first_key])) {
					$date_from = pjDateTime::formatDate($STORE[$i . '_date_from'][$first_key][0], $this->option_arr['o_date_format']);
					$date_to = pjDateTime::formatDate($STORE[$i . '_date_to'][$first_key[0]], $this->option_arr['o_date_format']);
				} else {
					$date_from = pjDateTime::formatDate($STORE[$i . '_date_from'][$first_key], $this->option_arr['o_date_format']);
					$date_to = pjDateTime::formatDate($STORE[$i . '_date_to'][$first_key], $this->option_arr['o_date_format']);
				}
			}
			foreach ($STORE[$i . '_adults'] as $k => $adults)
			{
				$arr = array($tab_id, $adults, $STORE[$i . '_children'][$k]);
				if ($i > 1)
				{
					$arr[] = $date_from;
					$arr[] = $date_to;
				} else {
					$arr[] = $tab_name;
				}
				$string = join("|", $arr);
				if (in_array($string, $tmp))
				{
					self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				}
				$tmp[] = $string;
				if(isset($STORE[$i . '_set_different_prices_' . $k]))
				{
				    foreach(range(0, 6) as $wday)
				    {
				        if((float) $STORE[$i . '_day_' . $wday][$k] > 9999999.99)
				        {
				            self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => ''));
				        }
				    }
				}else{
				    if((int) @$STORE[$i . '_adults'][$k] == 0 && (int) @$STORE[$i . '_children'][$k] == 0)
				    {
				        if((float) $STORE['single_price_' . $i] > 9999999.99)
				        {
				            self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => ''));
				        }
				    }else{
				        foreach(range(0, 6) as $wday)
				        {
				            if((float) $STORE[$i . '_day_' . $wday][$k] > 9999999.99)
				            {
				                self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => ''));
				            }
				        }
				    }
				}
			}
		}
		$j = 1;
		$insert_ids = array();
		$pjPriceModel = pjPriceModel::factory();
		$pjPriceModel->where('foreign_id', $this->getForeignIdPrice())->eraseAll();
		
		foreach ($STORE['tabs'] as $tab_id => $tab_name)
		{
			$i = $tab_id;
			
			$data = array();
			
			$data['season'] = $tab_name;
			$data['foreign_id'] = $this->getForeignIdPrice();
			if (!is_int($i) || (is_int($i) && $i > 1))
			{
				$tmp_arr = $STORE[$i . '_date_from'];
				reset($tmp_arr);
				$first_key = key($tmp_arr);
				
				if (is_array($STORE[$i . '_date_from'][$first_key])) {
					$data['date_from'] = pjDateTime::formatDate($STORE[$i . '_date_from'][$first_key][0], $this->option_arr['o_date_format']);
					$data['date_to'] = pjDateTime::formatDate($STORE[$i . '_date_to'][$first_key][0], $this->option_arr['o_date_format']);
				} else {
					$data['date_from'] = pjDateTime::formatDate($STORE[$i . '_date_from'][$first_key], $this->option_arr['o_date_format']);
					$data['date_to'] = pjDateTime::formatDate($STORE[$i . '_date_to'][$first_key], $this->option_arr['o_date_format']);
				}
				$j++;
			}
			$data['tab_id'] = $j;
			
			$rand = null;
			foreach ($STORE[$i . '_adults'] as $k => $adults)
			{
				if (isset($STORE[$i . '_set_different_prices_based_on_' . $k])) {
			    	 $data['set_different_prices_based_on_guests'] = 'T';
			    } else {
			    	$data['set_different_prices_based_on_guests'] = 'F';
			    }
				$data['adults'] = $STORE[$i . '_adults'][$k];
				$data['children'] = $STORE[$i . '_children'][$k];
				if(isset($STORE[$i . '_set_different_prices_' . $k]))
				{
				    $data['mon'] = $STORE[$i . '_day_1'][$k];
				    $data['tue'] = $STORE[$i . '_day_2'][$k];
				    $data['wed'] = $STORE[$i . '_day_3'][$k];
				    $data['thu'] = $STORE[$i . '_day_4'][$k];
				    $data['fri'] = $STORE[$i . '_day_5'][$k];
				    $data['sat'] = $STORE[$i . '_day_6'][$k];
				    $data['sun'] = $STORE[$i . '_day_0'][$k];
				    $data['set_different_prices'] = 'T';
				}else{
				    if((int) $data['adults'] == 0 && (int) $data['children'] == 0)
				    {
    				    $data['mon'] = $STORE['single_price_' . $i];
    				    $data['tue'] = $STORE['single_price_' . $i];
    				    $data['wed'] = $STORE['single_price_' . $i];
    				    $data['thu'] = $STORE['single_price_' . $i];
    				    $data['fri'] = $STORE['single_price_' . $i];
    				    $data['sat'] = $STORE['single_price_' . $i];
    				    $data['sun'] = $STORE['single_price_' . $i];
    				    $data['set_different_prices'] = 'F';
				    }else{
				        $data['mon'] = $STORE[$i . '_day_1'][$k];
				        $data['tue'] = $STORE[$i . '_day_2'][$k];
				        $data['wed'] = $STORE[$i . '_day_3'][$k];
				        $data['thu'] = $STORE[$i . '_day_4'][$k];
				        $data['fri'] = $STORE[$i . '_day_5'][$k];
				        $data['sat'] = $STORE[$i . '_day_6'][$k];
				        $data['sun'] = $STORE[$i . '_day_0'][$k];
				        $data['set_different_prices'] = 'T';
				    }
				}
				if(strpos($k, "~:~") != false)
				{
				    list($idx1, $idx2) = explode("~:~", $k);
				    if(isset($STORE[$i . '_set_different_prices_based_on_' . $idx2]))
				    {
				        $insert_ids[] = $pjPriceModel->reset()->setAttributes($data)->insert()->getInsertId();
				    }
				}else{
				    if((int) $data['adults'] == 0 && (int) $data['children'] == 0)
				    {
				        $insert_ids[] = $pjPriceModel->reset()->setAttributes($data)->insert()->getInsertId();
				    }
				}
			}
		}
		$_SESSION[$this->sessionPrice] = NULL;
		unset($_SESSION[$this->sessionPrice]);
		
		if (in_array(false, $insert_ids) || in_array(0, $insert_ids))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
		}
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
	}
	
	public function pjActionDeleteSeason()
	{
	    $this->setAjax(true);
	    
	    if (!$this->isXHR())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
	    }
	    if (!($this->_get->toInt('foreign_id')))
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
	    }
	    if (!($this->_get->toInt('tab_id')))
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
	    }
	    pjPriceModel::factory()->where('foreign_id', $this->_get->toInt('foreign_id'))->where('tab_id', $this->_get->toInt('tab_id'))->eraseAll();
	    self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Season prices has been deleted.'));
	}
}
?>