<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminLines extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminLines&action=pjActionIndex&err=ALN05");
			}
			if (isset($_POST['line_create']))
			{
				$pjLineModel = pjLineModel::factory();
				$_POST['seats'] = empty($_POST['seats']) ? 0 : $_POST['seats'];
				$id = $pjLineModel->setAttributes($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjLine', 'data');
					}
					if(isset($_POST['pd_id']) && is_array($_POST['pd_id']))
					{
						$pjLineDetailModel = pjLineDetailModel::factory();
						$pjLineDetailModel->begin();
						foreach($_POST['pd_id'] as $k => $location_id)
						{
							$pjLineDetailModel
								->reset()
								->set('line_id', $id)
								->set('location_id', $location_id)
								->set('duration_pickup', $_POST['duration_pickup'][$k])
								->set('duration_dropoff', $_POST['duration_dropoff'][$k])
								->set('price_pickup', pjUtil::convertToMySQLNumber($_POST['price_pickup'][$k], $this->option_arr))
								->set('price_dropoff', pjUtil::convertToMySQLNumber($_POST['price_dropoff'][$k], $this->option_arr))
								->insert();
						}
						$pjLineDetailModel->commit();
					}
					if (isset($_FILES['image']))
					{
						if($_FILES['image']['error'] == 0)
						{
							$image_size = getimagesize($_FILES['image']['tmp_name']);
							if(!empty($image_size))
							{
								$Image = new pjImage();
								if ($Image->getErrorCode() !== 200)
								{
									$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
									if ($Image->load($_FILES['image']))
									{
										$resp = $Image->isConvertPossible();
										if ($resp['status'] === true)
										{
											$hash = md5(uniqid(rand(), true));
											$source_path = PJ_UPLOAD_PATH . 'lines/source/' . $id . '_' . $hash . '.' . $Image->getExtension();
											$thumb_path = PJ_UPLOAD_PATH . 'lines/thumb/' . $id . '_' . $hash . '.' . $Image->getExtension();
											if ($Image->save($source_path))
											{
												$Image->loadImage($source_path);
												$Image->resizeSmart(150, 100);
												$Image->saveImage($thumb_path);
												
												$data['source_path'] = $source_path;
												$data['thumb_path'] = $thumb_path;
												$data['image_name'] = $_FILES['image']['name'];
												$pjLineModel->reset()->where('id', $id)->limit(1)->modifyAll($data);
											}
										}
									}
								}
							}else{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminLines&action=pjActionUpdate&id=$id&err=ALN11");
							}
						}else if($_FILES['image']['error'] != 4){
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminLines&action=pjActionUpdate&id=$id&err=ALN09");
						}
					}
					
					$err = 'ALN03';
				} else {
					$err = 'ALN04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminLines&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));
				
				$pjLocationModel = pjLocationModel::factory();
				$da_arr = $pjLocationModel
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as title")
					->where('t1.type', 'DA')
					->where('t1.status', 'T')
					->orderBy("title ASC")
					->findAll()->getData();
				$this->set('da_arr', $da_arr);
				
				$pd_arr = $pjLocationModel
					->reset()
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as title")
					->where('t1.type', 'PD')
					->where('t1.status', 'T')
					->orderBy("title ASC")
					->findAll()->getData();
				$this->set('pd_arr', $pd_arr);
				
				$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('pjAdminLines.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteLine()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			$pjLineModel = pjLineModel::factory();
			$arr = $pjLineModel->find($_GET['id'])->getData();
			
			if (pjLineModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				if(file_exists(PJ_INSTALL_PATH . $arr['source_path']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['source_path']);
				}
				if(file_exists(PJ_INSTALL_PATH . $arr['thumb_path']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['thumb_path']);
				}
					
				pjMultiLangModel::factory()->where('model', 'pjLine')->where('foreign_id', $_GET['id'])->eraseAll();
				pjLineDetailModel::factory()->where('line_id', $_GET['id'])->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteLineBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjLineModel = pjLineModel::factory();
				$arr = $pjLineModel
					->reset()
					->whereIn('id', $_POST['record'])
					->findAll()
					->getData();
			
				foreach($arr as $v)
				{
					if(file_exists(PJ_INSTALL_PATH . $v['source_path']))
					{
						@unlink(PJ_INSTALL_PATH . $v['source_path']);
					}
					if(file_exists(PJ_INSTALL_PATH . $v['thumb_path']))
					{
						@unlink(PJ_INSTALL_PATH . $v['thumb_path']);
					}
				}
				$pjLineModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
				pjLineDetailModel::factory()->whereIn('line_id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjLine')->whereIn('foreign_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportLine()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjLineModel::factory()
						->select("t1.*, t2.content as line, t3.content as description")
						->join('pjMultiLang', "t2.model='pjLine' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->join('pjMultiLang', "t3.model='pjLine' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
						->whereIn('t1.id', $_POST['record'])
						->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Lines-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetLine()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjLineModel = pjLineModel::factory();
			
			$pjLineModel
				->join('pjMultiLang', "t2.model='pjLine' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t3.model='pjLine' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t4.model='pjLocation' AND t4.foreign_id=t1.location_id AND t4.field='title' AND t4.locale='".$this->getLocaleId()."'", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjLineModel->where("(t2.content LIKE '%$q%' OR t3.content LIKE '%$q%')");
			}
	
			$column = 'title';
			$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 = $pjLineModel->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 = $pjLineModel
				->select('t1.*, t2.content as title, t4.content as location')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()->getData();
				
			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('pjAdminLines.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveLine()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjLineModel = pjLineModel::factory();
			
			if (!in_array($_POST['column'], $pjLineModel->i18n))
			{
				$value = $_POST['value'];
				
				$pjLineModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $value));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjLine', 'data');
			}
		}
		exit;
	}
	
	public function pjActionStatusLine()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjLineModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminLines&action=pjActionIndex&err=ALN06");
			}	
			if (isset($_POST['line_update']))
			{
				$pjLineModel = pjLineModel::factory();
				
				$arr = $pjLineModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminLines&action=pjActionIndex&err=ALN08");
				}
				
				$data = array();
				if (isset($_FILES['image']))
				{
					if($_FILES['image']['error'] == 0)
					{
						$image_size = getimagesize($_FILES['image']['tmp_name']);
						if(!empty($image_size))
						{
							if(!empty($arr['source_path']))
							{
								$source_path = PJ_INSTALL_PATH . $arr['source_path'];
								$thumb_path = PJ_INSTALL_PATH . $arr['thumb_path'];
								@unlink($source_path);
								@unlink($thumb_path);
							}
								
							$Image = new pjImage();
							if ($Image->getErrorCode() !== 200)
							{
								$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
								if ($Image->load($_FILES['image']))
								{
									$resp = $Image->isConvertPossible();
									if ($resp['status'] === true)
									{
										$hash = md5(uniqid(rand(), true));
										$source_path = PJ_UPLOAD_PATH . 'lines/source/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
										$thumb_path = PJ_UPLOAD_PATH . 'lines/thumb/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
										if ($Image->save($source_path))
										{
											$Image->loadImage($source_path);
											$Image->resizeSmart(150, 100);
											$Image->saveImage($thumb_path);
											
											$data['source_path'] = $source_path;
											$data['thumb_path'] = $thumb_path;
											$data['image_name'] = $_FILES['image']['name'];
										}
									}
								}
							}
						}else{
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminLines&action=pjActionUpdate&id=".$_POST['id']."&err=ALN11");
						}
					}else if($_FILES['image']['error'] != 4){
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminLines&action=pjActionUpdate&id=".$_POST['id']."&err=ALN10");
					}	
				}
				$_POST['seats'] = empty($_POST['seats']) ? 0 : $_POST['seats'];
				$pjLineModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjLine', 'data');
				}
				
				$pjLineDetailModel = pjLineDetailModel::factory();
				$line_detail_id_arr = $pjLineDetailModel->where('t1.line_id', $_POST['id'])->findAll()->getDataPair(null, 'id');
				if(isset($_POST['pd_id']) && is_array($_POST['pd_id']))
				{
					$update_id_arr = array();
					$pjLineDetailModel->reset();
					$pjLineDetailModel->begin();
					foreach($_POST['pd_id'] as $k => $location_id)
					{
						if(strpos($k, 'new') !== FALSE)
						{
							$pjLineDetailModel
								->reset()
								->set('line_id', $_POST['id'])
								->set('location_id', $location_id)
								->set('duration_pickup', $_POST['duration_pickup'][$k])
								->set('duration_dropoff', $_POST['duration_dropoff'][$k])
								->set('price_pickup', pjUtil::convertToMySQLNumber($_POST['price_pickup'][$k], $this->option_arr))
								->set('price_dropoff', pjUtil::convertToMySQLNumber($_POST['price_dropoff'][$k], $this->option_arr))
								->insert();
						}else{
							if(in_array($k, $line_detail_id_arr))
							{
								$update_id_arr[] = $k;
							}
						}
					}
					$pjLineDetailModel->commit();
					
					$remove_id_arr = array();
					if(!empty($update_id_arr))
					{
						foreach($update_id_arr as $line_detail_id)
						{
							$update_data = array();
							$update_data['line_id'] = $_POST['id'];
							$update_data['location_id'] = $_POST['pd_id'][$line_detail_id];
							$update_data['duration_pickup'] = $_POST['duration_pickup'][$line_detail_id];
							$update_data['duration_dropoff'] = $_POST['duration_dropoff'][$line_detail_id];
							$update_data['price_pickup'] = pjUtil::convertToMySQLNumber($_POST['price_pickup'][$line_detail_id], $this->option_arr);
							$update_data['price_dropoff'] = pjUtil::convertToMySQLNumber($_POST['price_dropoff'][$line_detail_id], $this->option_arr);
							$pjLineDetailModel->reset()->where('id', $line_detail_id)->limit(1)->modifyAll($update_data);
						}
						$remove_id_arr=array_diff($line_detail_id_arr,$update_id_arr);
					}else{
						$remove_id_arr = $line_detail_id_arr;
					}
					if(!empty($remove_id_arr))
					{
						$pjLineDetailModel->reset()->whereIn('id', $remove_id_arr)->eraseAll();
					}
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminLines&action=pjActionIndex&err=ALN01");
				
			} else {
				$pjMultiLangModel = pjMultiLangModel::factory();
				
				$arr = pjLineModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminLines&action=pjActionIndex&err=ALN08");
				}
				$arr['i18n'] = $pjMultiLangModel->getMultiLang($arr['id'], 'pjLine');
				
				$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('arr', $arr);
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$pjLocationModel = pjLocationModel::factory();
				$da_arr = $pjLocationModel
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as title")
					->where('t1.type', 'DA')
					->where('t1.status', 'T')
					->orderBy("title ASC")
					->findAll()->getData();
				$this->set('da_arr', $da_arr);
				
				$pd_arr = $pjLocationModel
					->reset()
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as title")
					->where('t1.type', 'PD')
					->where('t1.status', 'T')
					->orderBy("title ASC")
					->findAll()->getData();
				$this->set('pd_arr', $pd_arr);
				
				$line_detail_arr = pjLineDetailModel::factory()->where('t1.line_id', $_GET['id'])->findAll()->getData();
				$this->set('line_detail_arr', $line_detail_arr);
				
				$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('pjAdminLines.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			$pjLineModel = pjLineModel::factory();
			$arr = $pjLineModel->find($_GET['id'])->getData(); 
			
			if(!empty($arr))
			{
				if(!empty($arr['source_path']))
				{
					$source_path = PJ_INSTALL_PATH . $arr['source_path'];
					$thumb_path = PJ_INSTALL_PATH . $arr['thumb_path'];
					@unlink($source_path);
					@unlink($thumb_path);
				}
				
				$data = array();
				$data['source_path'] = ':NULL';
				$data['thumb_path'] = ':NULL';
				$data['image_name'] = ':NULL';
				$pjLineModel->reset()->where(array('id' => $_GET['id']))->limit(1)->modifyAll($data);
				
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
	}
}
?>