<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminReasons extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['reason_create']))
			{
				$id = pjReasonModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AE03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjReason', 'data');
					}
					
					$fleet_arr = pjFleetModel::factory()->where('t1.status', 'T')->findAll()->getData();
					$pjReasonServiceModel = pjReasonServiceModel::factory();
					foreach($fleet_arr as $fleet)
					{
						if (isset($_POST['service_id_' . $fleet['id']]) && is_array($_POST['service_id_' . $fleet['id']]) && count($_POST['service_id_' . $fleet['id']]) > 0)
						{
							$pjReasonServiceModel->begin();
							foreach ($_POST['service_id_' . $fleet['id']] as $service_id)
							{
								$pjReasonServiceModel
								->reset()
								->set('reason_id', $id)
								->set('service_id', $service_id)
								->insert();
							}
							$pjReasonServiceModel->commit();
						}
					}
					
				} else {
					$err = 'AE04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminReasons&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));
		
				$fleet_arr = pjFleetModel::factory()
					->join('pjMultiLang', "t2.model='pjFleet' AND t2.foreign_id=t1.id AND t2.field='fleet' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as fleet")
					->where('t1.status', 'T')
					->orderBy("fleet ASC")
					->findAll()->getData();
				
				$temp_service_arr = pjServiceModel::factory()
					->join('pjMultiLang', "t2.model='pjService' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as name")
					->orderBy("name ASC")
					->findAll()->getData();
				
				$service_arr = array();
				foreach($temp_service_arr as $k => $v)
				{
					$service_arr[$v['fleet_id']][] = $v;
				}
				
				$this->set('fleet_arr', $fleet_arr);
				$this->set('service_arr', $service_arr);
				
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('jquery.validate.min.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('pjAdminReasons.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteReason()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjReasonModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjReason')->where('foreign_id', $_GET['id'])->eraseAll();
				pjReasonServiceModel::factory()->where('reason_id', $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteReasonBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjReasonModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjReason')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				pjReasonServiceModel::factory()->whereIn('reason_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetReason()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjReasonModel = pjReasonModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjReason' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjReasonModel->where('t2.content LIKE', "%$q%");
			}

			$column = 'name';
			$direction = 'ASC';
			$allowed_columns = array('name', 'limo_service');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjReasonModel->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 = $pjReasonModel
				->select('t1.*, t2.content AS name')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			
			$reason_id_arr = $pjReasonModel->findAll()->getDataPair(null, 'id');
			$service_arr = array();
			if(!empty($reason_id_arr))
			{
				$temp_service_arr = pjServiceModel::factory()
					->join('pjMultiLang', "t2.model='pjService' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t3.model='pjFleet' AND t3.foreign_id=t1.fleet_id AND t3.field='fleet' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjReasonService', "t4.service_id=t1.id", 'left outer')
					->select("t1.*, t2.content as name, t3.content as fleet, t4.reason_id")
					->where("(t1.id IN (SELECT TRS.service_id FROM `".pjReasonServiceModel::factory()->getTable()."` AS `TRS` WHERE `TRS`.reason_id IN(".join(',', $reason_id_arr).") ) )")
					->findAll()
					->getData();
				foreach($temp_service_arr as $service)
				{
					$service_arr[$service['reason_id']][$service['fleet_id']][] = $service;
				}
			}
			
			foreach($data as $k => $v)
			{
				$v['limo_service'] = '';
				$limo_service_arr = array();
				if(isset($service_arr[$v['id']]) && is_array($service_arr[$v['id']]))
				{
					foreach($service_arr[$v['id']] as $fleet_id => $service)
					{
						$service_name_arr = array();
						foreach($service as $s)
						{
							$service_name_arr[] = $s['name'];
						}
						$limo_service_arr[] = '<b>' . $service_arr[$v['id']][$fleet_id][0]['fleet'] . '</b> - ' . join(", ", $service_name_arr);
					}
				}
				$v['limo_service'] = join('<br/>', $limo_service_arr);
				$data[$k] = $v;
			}
			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
		
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminReasons.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveReason()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjReasonModel = pjReasonModel::factory();
			if (!in_array($_POST['column'], $pjReasonModel->getI18n()))
			{
				$pjReasonModel->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'], 'pjReason', 'data');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['reason_update']))
			{
				pjReasonModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjReason', 'data');
				}
				
				$fleet_arr = pjFleetModel::factory()->where('t1.status', 'T')->findAll()->getData();
				$pjReasonServiceModel = pjReasonServiceModel::factory();
				$pjReasonServiceModel->where('reason_id', $_POST['id'])->eraseAll();
				foreach($fleet_arr as $fleet)
				{
					if (isset($_POST['service_id_' . $fleet['id']]) && is_array($_POST['service_id_' . $fleet['id']]) && count($_POST['service_id_' . $fleet['id']]) > 0)
					{
						$pjReasonServiceModel->begin();
						foreach ($_POST['service_id_' . $fleet['id']] as $service_id)
						{
							$pjReasonServiceModel
								->reset()
								->set('reason_id', $_POST['id'])
								->set('service_id', $service_id)
								->insert();
						}
						$pjReasonServiceModel->commit();
					}
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminReasons&action=pjActionIndex&err=AE01");
				
			} else {
				$arr = pjReasonModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminReasons&action=pjActionIndex&err=AE08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjReason');
				$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));
				
				$fleet_arr = pjFleetModel::factory()
					->join('pjMultiLang', "t2.model='pjFleet' AND t2.foreign_id=t1.id AND t2.field='fleet' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as fleet")
					->where('t1.status', 'T')
					->orderBy("fleet ASC")
					->findAll()->getData();
				
				$temp_service_arr = pjServiceModel::factory()
					->join('pjMultiLang', "t2.model='pjService' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as name")
					->orderBy("name ASC")
					->findAll()->getData();
				
				$service_arr = array();
				foreach($temp_service_arr as $k => $v)
				{
					$service_arr[$v['fleet_id']][] = $v;
				}
				
				$this->set('fleet_arr', $fleet_arr);
				$this->set('service_arr', $service_arr);
				
				$service_id_arr = pjReasonServiceModel::factory()->where('reason_id', $_GET['id'])->findAll()->getDataPair(null, 'service_id');
				$this->set('service_id_arr', $service_id_arr);
				
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('jquery.validate.min.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('pjAdminReasons.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>