<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminProductFeatures extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$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=pjAdminProductFeatures&action=pjActionIndex&err=APF05");
			}
			if (isset($_POST['product_feature_create']))
			{
				$pjProductFeatureModel = pjProductFeatureModel::factory();
				
				$data = array();
				$data['order'] = $pjProductFeatureModel->getLastOrder($_POST['category_id']);
				
				$id = $pjProductFeatureModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjProductFeature', 'data');
					}
					
					if (isset($_FILES['image']))
					{
						if($_FILES['image']['error'] == 0)
						{
							$size = getimagesize($_FILES['image']['tmp_name']);
							if($size == true)
							{
								$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 . 'product_features/source/' . $id . '_' . $hash . '.' . $Image->getExtension();
											$thumb_path = PJ_UPLOAD_PATH . 'product_features/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'];
												$pjProductFeatureModel->reset()->where('id', $id)->limit(1)->modifyAll($data);
											}
										}
									}
								}
							}else{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProductFeatures&action=pjActionUpdate&id=$id&err=APF12");
							}
						}else if($_FILES['image']['error'] != 4){
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProductFeatures&action=pjActionUpdate&id=$id&err=APF09");
						}
					}
					$err = 'APF03';
				} else {
					$err = 'APF04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProductFeatures&action=pjActionIndex&err=$err");
			} else {
				$this->set('category_arr', pjCategoryModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.status', 'T')
					->orderBy('name ASC')->findAll()->getData());
				
				$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->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('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('pjAdminProductFeatures.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteProductFeature()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			$pjProductFeatureModel = pjProductFeatureModel::factory();
			$pjMultiLangModel = pjMultiLangModel::factory();
			$arr = $pjProductFeatureModel->find($_GET['id'])->getData();
			
			if (pjProductFeatureModel::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->where('model', 'pjProductFeature')->where('foreign_id', $_GET['id'])->eraseAll();
				
				$pjMultiLangModel
					->reset()
					->where('model', 'pjFeatureMod')
					->where("(foreign_id IN(SELECT TFM.id 
											FROM `".pjFeatureModModel::factory()->getTable()."` AS TFM 
											WHERE TFM.feature_id='".$_GET['id']."'
							               )
							  )")
					->eraseAll();
				pjFeatureModModel::factory()
					->where('feature_id', $_GET['id'])
					->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteProductFeatureBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjProductFeatureModel = pjProductFeatureModel::factory();
				$pjMultiLangModel = pjMultiLangModel::factory();
				
				$arr = $pjProductFeatureModel->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']);
					}
				}
				
				pjProductFeatureModel::factory()
					->whereIn('id', $_POST['record'])
					->eraseAll();
				$pjMultiLangModel
					->where('model', 'pjProductFeature')
					->whereIn('foreign_id', $_POST['record'])
					->eraseAll();
				
				$pjMultiLangModel
					->reset()
					->where('model', 'pjFeatureMod')
					->where("(foreign_id IN(SELECT TFM.id 
											FROM `".pjFeatureModModel::factory()->getTable()."` AS TFM 
											WHERE TFM.feature_id IN(".join(",", $_POST['record']).")
							               )
							  )")
					->eraseAll();
				pjFeatureModModel::factory()
					->whereIn('feature_id', $_POST['record'])
					->eraseAll();
			}
		}
		exit;
	}

	public function pjActionExportProductFeature()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjProductFeatureModel::factory()
						->select("t1.*, t2.content as title, t3.content as description")
						->join('pjMultiLang', "t2.model='pjProductFeature' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->join('pjMultiLang', "t3.model='pjProductFeature' 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("ProductFeatures-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	
	public function pjActionGetProductFeature()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjProductFeatureModel = pjProductFeatureModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjProductFeature' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
				->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjProductFeature' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
				->join('pjMultiLang', "t4.foreign_id = t1.category_id AND t4.model = 'pjCategory' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'name'", 'left');;
			
			if (isset($_GET['status']) && !empty($_GET['status']))
			{
				$pjProductFeatureModel->where('t1.status', $_GET['status']);
			}
			if (isset($_GET['category_id']) && !empty($_GET['category_id']))
			{
				$pjProductFeatureModel->where('t1.category_id', $_GET['category_id']);
			}
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjProductFeatureModel->where("(t2.content LIKE '%$q%' OR t3.content LIKE '%$q%')");
			}

			$column = 'order';
			$direction = 'ASC';
			$allowed_columns = array('title', 'category', 'status');
			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 = $pjProductFeatureModel->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 = $pjProductFeatureModel->select('t1.id, t1.order, t1.status, t2.content AS title, t4.content AS category')
				->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->isEditor())
		{
			$category_arr = pjCategoryModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjCategory' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
				->select('t1.*, t2.content as name')
				->orderBy("`order` ASC")
				->findAll()
				->getData();
			
			$this->set('category_arr', $category_arr);	
				
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminProductFeatures.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSortFeature()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{			
			$pjProductFeatureModel = pjProductFeatureModel::factory();
			
			foreach($_POST['sort'] as $k => $v)
			{
				$pjProductFeatureModel->reset()->set('id', $v)->modify(array('order' => $k+1));
			}
		}
		exit;
	}
	
	public function pjActionSaveProductFeature()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjProductFeatureModel = pjProductFeatureModel::factory();
			if (!in_array($_POST['column'], $pjProductFeatureModel->i18n))
			{
				$pjProductFeatureModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				$pjMultiLangModel = pjMultiLangModel::factory();
				$cnt = $pjMultiLangModel	
							->where('t1.foreign_id !=', $_GET['id'])
							->where('t1.model', 'pjProductFeature')
							->where('t1.locale', $this->getLocaleId())
							->where('t1.field', 'title')
							->where('t1.content', $_POST['value'])
							->findCount()->getData();
							
				if($cnt == 0)
				{
					$pjMultiLangModel->reset()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjProductFeature', 'data');
				}
			}
		}
		exit;
	}
	public function pjActionStatusProductFeature()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjProductFeatureModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			$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=pjAdminProductFeatures&action=pjActionIndex&err=APF06");
			}
			if (isset($_POST['product_feature_update']))
			{
				$pjProductFeatureModel = pjProductFeatureModel::factory();
				
				$arr = $pjProductFeatureModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminFleets&action=pjActionIndex&err=APF08");
				}
				
				$data = array();
				if (isset($_FILES['image']))
				{
					if($_FILES['image']['error'] == 0)
					{
						$size = getimagesize($_FILES['image']['tmp_name']);
						if($size == true)
						{
							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 . 'product_features/source/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
										$thumb_path = PJ_UPLOAD_PATH . 'product_features/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=pjAdminProductFeatures&action=pjActionUpdate&id=".$_POST['id']."&err=APF11");
						}
					}else if($_FILES['image']['error'] != 4){
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProductFeatures&action=pjActionUpdate&id=".$_POST['id']."&err=APF10");
					}
				}
				
				$pjProductFeatureModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjProductFeature', 'data');
				}

				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminProductFeatures&action=pjActionIndex&err=APF01");
			} else {
				$arr = pjProductFeatureModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminProductFeatures&action=pjActionIndex&err=APF08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjProductFeature');
				$this->set('arr', $arr);
				
				$this->set('category_arr', pjCategoryModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.status', 'T')
					->orderBy('name ASC')->findAll()->getData());
					
				$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->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('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('pjAdminProductFeatures.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			$pjProductFeatureModel = pjProductFeatureModel::factory();
			$arr = $pjProductFeatureModel->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';
				$pjProductFeatureModel->reset()->where(array('id' => $_GET['id']))->limit(1)->modifyAll($data);
				
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionGetLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_GET['locale']) && (int) $_GET['locale'] > 0)
			{
				pjAppController::setFields($_GET['locale']);
				
				$category_arr = pjCategoryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".pjObject::escapeString($_GET['locale'])."'", 'inner')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
					
				$this->set('category_arr', $category_arr);
			}
		}
	}
}
?>