<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminDiscounts extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['discount_create']))
			{
				$data = array();
			
				$data['discount'] = $_POST['type'] == 'amount' ? pjUtil::convertToMySQLNumber($_POST['discount'], $this->option_arr) : $_POST['discount'];
				$data['type'] = $_POST['type'];
				$data['condition'] = $_POST['condition'];
				$data['apply_on'] = $_POST['apply_on'];
				$data['date_from'] = pjUtil::formatDate($_POST['date_from'], $this->option_arr['o_date_format']);
				$data['date_to'] = pjUtil::formatDate($_POST['date_to'], $this->option_arr['o_date_format']);
				$data['options'] = $_POST['options'];
				
				$data['early_days'] = ':NULL';
				$data['min_persons'] = ':NULL';
				$data['max_persons'] = ':NULL';
				$data['min_duration'] = ':NULL';
				$data['max_duration'] = ':NULL';
				
				if($_POST['options'] == 'early')
				{
					$data['early_days'] = $_POST['early_days'];
				}
				if($_POST['options'] == 'persons')
				{
					$data['min_persons'] = $_POST['min_persons'];
					$data['max_persons'] = $_POST['max_persons'];
				}
				if($_POST['options'] == 'duration')
				{
					$data['min_duration'] = $_POST['min_duration'];
					$data['max_duration'] = $_POST['max_duration'];
				}
				
				$id = pjDiscountModel::factory($data)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjDiscount', 'data');
					}
						
					$pjCalendarDiscountModel = pjCalendarDiscountModel::factory();
					if (isset($_POST['calendar_id']) && is_array($_POST['calendar_id']) && count($_POST['calendar_id']) > 0)
					{
						$pjCalendarDiscountModel->begin();
						foreach ($_POST['calendar_id'] as $calendar_id)
						{
							$pjCalendarDiscountModel
								->reset()
								->set('discount_id', $id)
								->set('calendar_id', $calendar_id)
								->insert();
						}
						$pjCalendarDiscountModel->commit();
					}
					$err = 'AD03';
				} else {
					$err = 'AD04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminDiscounts&action=pjActionIndex&err=$err");
			} else {
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
				->join('pjLocaleLanguage', '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('calendar_arr', pjCalendarModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCalendar' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('name ASC')
					->findAll()
					->getData());
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('pjAdminDiscounts.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteDiscount()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			if (pjDiscountModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjCalendarDiscountModel::factory()->where('discount_id', $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteDiscountBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjDiscountModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjCalendarDiscountModel::factory()->whereIn('discount_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportDiscount()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjDiscountModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Discounts-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetDiscount()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjDiscountModel = pjDiscountModel::factory()->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjDiscount' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjDiscountModel->where('t2.content LIKE', "%$q%");
			}
	
			$column = 'name';
			$direction = 'ASC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjDiscountModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$pages = ceil($total / $rowCount);
			$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}

			$data = array();
			
			$data = $pjDiscountModel->select('t1.*, t2.content as name')->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k => $v)
			{
				if($v['type'] == 'percent')
				{
					$v['discount'] = $v['discount'] . '%';
				}else{
					$v['discount'] = pjUtil::formatCurrencySign(pjUtil::converToCurrencyFormat($v['discount'], $this->option_arr), $this->option_arr['o_currency']);
				}
				$v['valid'] = '';
				$v['valid'] = __('lblFrom', true) . ' ' . date($this->option_arr['o_date_format'], strtotime($v['date_from'])) . ' ' . __('lblTo', true) . ' ' . date($this->option_arr['o_date_format'], strtotime($v['date_to']));
				$data[$k] = $v;
			}	
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminDiscounts.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveDiscount()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjDiscountModel = pjDiscountModel::factory();
			if (!in_array($_POST['column'], $pjDiscountModel->getI18n()))
			{
				$pjDiscountModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjDiscount', 'data');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['discount_update']))
			{
				$data = array();
				
				$data['discount'] = $_POST['type'] == 'amount' ? pjUtil::convertToMySQLNumber($_POST['discount'], $this->option_arr) : $_POST['discount'];
				$data['type'] = $_POST['type'];
				$data['condition'] = $_POST['condition'];
				$data['apply_on'] = $_POST['apply_on'];
				$data['date_from'] = pjUtil::formatDate($_POST['date_from'], $this->option_arr['o_date_format']);
				$data['date_to'] = pjUtil::formatDate($_POST['date_to'], $this->option_arr['o_date_format']);
				$data['options'] = $_POST['options'];
				
				$data['early_days'] = ':NULL';
				$data['min_persons'] = ':NULL';
				$data['max_persons'] = ':NULL';
				$data['min_duration'] = ':NULL';
				$data['max_duration'] = ':NULL';
				
				if($_POST['options'] == 'early')
				{
					$data['early_days'] = $_POST['early_days'];
				}
				if($_POST['options'] == 'persons')
				{
					$data['min_persons'] = $_POST['min_persons'];
					$data['max_persons'] = $_POST['max_persons'];
				}
				if($_POST['options'] == 'duration')
				{
					$data['min_duration'] = $_POST['min_duration'];
					$data['max_duration'] = $_POST['max_duration'];
				}
				
				pjDiscountModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjDiscount', 'data');
				}
				
				$pjCalendarDiscountModel = pjCalendarDiscountModel::factory();
				$pjCalendarDiscountModel->where('discount_id', $_POST['id'])->eraseAll();
				if (isset($_POST['calendar_id']) && is_array($_POST['calendar_id']) && count($_POST['calendar_id']) > 0)
				{
					$pjCalendarDiscountModel->begin();
					foreach ($_POST['calendar_id'] as $calendar_id)
					{
						$pjCalendarDiscountModel
							->reset()
							->set('discount_id', $_POST['id'])
							->set('calendar_id', $calendar_id)
							->insert();
					}
					$pjCalendarDiscountModel->commit();
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminDiscounts&action=pjActionIndex&err=AD01");
				
			} else {
				$arr = pjDiscountModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminDiscounts&action=pjActionIndex&err=AD08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjDiscount');
				$this->set('arr', $arr);
				
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
				->join('pjLocaleLanguage', '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('calendar_arr', pjCalendarModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCalendar' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('name ASC')
					->findAll()
					->getData());
			
				$this->set('calendar_id_arr', pjCalendarDiscountModel::factory()
					->where("discount_id", $_GET['id'])
					->findAll()
					->getDataPair("calendar_id", "calendar_id"));
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('pjAdminDiscounts.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>