<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminProducts 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=pjAdminProducts&action=pjActionIndex&err=AP05");
			}
			if (isset($_POST['product_create']))
			{
				$id = pjProductModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$pjMultiLangModel = pjMultiLangModel::factory();
					$model_id_arr = array();
					if (isset($_POST['i18n']))
					{
						if(isset($_POST['index_arr']) && $_POST['index_arr'] != '')
						{
							$index_arr = explode("|", $_POST['index_arr']);
							
							$pjProductModModel = pjProductModModel::factory();
							foreach($index_arr as $k => $v)
							{
								$m_data = array();
								$m_data['product_id'] = $id;
								$model_id = $pjProductModModel->reset()->setAttributes($m_data)->insert()->getInsertId();
								if (isset($_FILES['model_image_' . $v]))
								{
									$model_file = $_FILES['model_image_' . $v];
									if($model_file['error'] == 0)
									{
										$size = getimagesize($model_file['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($model_file))
												{
													$resp = $Image->isConvertPossible();
													if ($resp['status'] === true)
													{
														$hash = md5(uniqid(rand(), true));
														$source_path = PJ_UPLOAD_PATH . 'models/source/' . $model_id . '_' . $hash . '.' . $Image->getExtension();
														$thumb_path = PJ_UPLOAD_PATH . 'models/thumb/' . $model_id . '_' . $hash . '.' . $Image->getExtension();
														if ($Image->save($source_path))
														{
															$Image->loadImage($source_path);
															$Image->resizeSmart(150, 100);
															$Image->saveImage($thumb_path);
															$temp_model_data = array();
															$temp_model_data['source_path'] = $source_path;
															$temp_model_data['thumb_path'] = $thumb_path;
															$pjProductModModel->reset()->where('id', $model_id)->limit(1)->modifyAll($temp_model_data);
														}
													}
												}
											}
										}
									}
								}
								if ($model_id !== false && (int) $model_id > 0)
								{
									$model_id_arr[] = $model_id;
									foreach ($_POST['i18n'] as $locale => $locale_arr)
									{
										foreach ($locale_arr as $field => $content)
										{
											if(is_array($content))
											{
												$insert_id = $pjMultiLangModel->reset()->setAttributes(array(
													'foreign_id' => $model_id,
													'model' => 'pjProductMod',
													'locale' => $locale,
													'field' => $field,
													'content' => $content[$v],
													'source' => 'data'
												))->insert()->getInsertId();
												
												if ($insert_id === FALSE || (int) $insert_id <= 0)
												{
													$pjMultiLangModel->reset()
														->where('foreign_id', $model_id)
														->where('model', 'pjProductMod')
														->where('locale', $locale)
														->where('field', $field)
														->limit(1)
														->modifyAll(array('content' => $content[$v]));
												}
											}
										}
									}
								}
							}
						}
						foreach ($_POST['i18n'] as $locale => $locale_arr)
						{
							foreach ($locale_arr as $field => $content)
							{
								if(!is_array($content))
								{
									$insert_id = $pjMultiLangModel->reset()->setAttributes(array(
										'foreign_id' => $id,
										'model' => 'pjProduct',
										'locale' => $locale,
										'field' => $field,
										'content' => $content,
										'source' => 'data'
									))->insert()->getInsertId();
									
									if ($insert_id === FALSE || (int) $insert_id <= 0)
									{
										$pjMultiLangModel->reset()
											->where('foreign_id', $id)
											->where('model', 'pjProduct')
											->where('locale', $locale)
											->where('field', $field)
											->limit(1)
											->modifyAll(array('content' => $content));
									}
								}
							}
						}
					}
					
					$pjProductCategoryModel = pjProductCategoryModel::factory();
					if (isset($_POST['category_id']) && is_array($_POST['category_id']) && count($_POST['category_id']) > 0)
					{
						$pjProductCategoryModel->begin();
						foreach ($_POST['category_id'] as $category_id)
						{
							$pjProductCategoryModel
								->reset()
								->set('product_id', $id)
								->set('category_id', $category_id)
								->insert();
						}
						$pjProductCategoryModel->commit();
					}

					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 . 'products/source/' . $id . '_' . $hash . '.' . $Image->getExtension();
											$thumb_path = PJ_UPLOAD_PATH . 'products/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;
												pjProductModel::factory()->where('id', $id)->limit(1)->modifyAll($data);
											}
										}
									}
								}
							}else{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&action=pjActionUpdate&id=$id&err=AP12");
							}
						}else if($_FILES['image']['error'] != 4){
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&action=pjActionUpdate&id=$id&err=AP09");
						}
					}
					
					$err = 'AP03';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&action=pjActionFeature&id=".$id."&err=$err");
				} else {
					$err = 'AP04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&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('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());
				
				$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('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('pjAdminProducts.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteProduct()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjProductModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$pjProductModModel = pjProductModModel::factory();
				
				$pjMultiLangModel->where('model', 'pjProduct')->where('foreign_id', $_GET['id'])->eraseAll();
				$pjMultiLangModel
					->reset()
					->where('model', 'pjProductMod')
					->where("(foreign_id IN(SELECT TM.id 
											FROM `".$pjProductModModel->getTable()."` AS TM 
											WHERE TM.product_id = '".$_GET['id']."')
							  )")
					->eraseAll();
				$model_arr = $pjProductModModel->where('product_id', $_GET['id'])->findAll()->getData();
				foreach($model_arr as $k => $v)
				{
					if(!empty($v['source_path']))
					{
						$source_path = PJ_INSTALL_PATH . $v['source_path'];
						$thumb_path = PJ_INSTALL_PATH . $v['thumb_path'];
						@unlink($source_path);
						@unlink($thumb_path);
					}
				}
				$pjProductModModel->reset()->where('product_id', $_GET['id'])->eraseAll();

				pjProductCategoryModel::factory()->where('product_id', $_GET['id'])->eraseAll();
				
				$pjMultiLangModel
					->reset()
					
					->where('model', 'pjFeatureMod')
					->where("(foreign_id IN(SELECT TFM.id 
											FROM `".pjFeatureModModel::factory()->getTable()."` AS TFM 
											WHERE TFM.model_id IN (SELECT TM.id 
																   FROM `".$pjProductModModel->getTable()."` AS TM 
																   WHERE TM.product_id = '".$_GET['id']."')
							               )
							  )")
					->eraseAll();
				pjFeatureModModel::factory()
					->where("model_id IN (SELECT TM.id 
										  FROM `".$pjProductModModel->getTable()."` AS TM 
										  WHERE TM.product_id = '".$_GET['id']."')")
					->eraseAll();
					
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteProductBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$pjProductModModel = pjProductModModel::factory();
				
				pjProductModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				$pjMultiLangModel->where('model', 'pjProduct')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				$pjMultiLangModel
					->reset()
					->where('model', 'pjProductMod')
					->where("(foreign_id IN(SELECT TM.id 
											FROM `".$pjProductModModel->getTable()."` AS TM 
											WHERE TM.product_id IN(".join(",", $_POST['record'])."))
							  )")
					->eraseAll();
				$model_arr = $pjProductModModel->whereIn('product_id', $_POST['record'])->findAll()->getData();
				foreach($model_arr as $k => $v)
				{
					if(!empty($v['source_path']))
					{
						$source_path = PJ_INSTALL_PATH . $v['source_path'];
						$thumb_path = PJ_INSTALL_PATH . $v['thumb_path'];
						@unlink($source_path);
						@unlink($thumb_path);
					}
				}
				$pjProductModModel->reset()->whereIn('product_id', $_POST['record'])->eraseAll();
				pjProductCategoryModel::factory()->whereIn('product_id', $_POST['record'])->eraseAll();
				
				$pjMultiLangModel
					->reset()
					->where('model', 'pjFeatureMod')
					->where("(foreign_id IN(SELECT TFM.id 
											FROM `".pjFeatureModModel::factory()->getTable()."` AS TFM 
											WHERE TFM.model_id IN (SELECT TM.id 
																   FROM `".$pjProductModModel->getTable()."` AS TM 
																   WHERE TM.product_id IN(".join(",", $_POST['record'])."))
							               )
							  )")
					->eraseAll();
				pjFeatureModModel::factory()
					->where("model_id IN (SELECT TM.id 
										  FROM `".$pjProductModModel->getTable()."` AS TM 
										  WHERE TM.product_id IN(".join(",", $_POST['record']).")")
					->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetProduct()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjProductModel = pjProductModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjProduct' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'product_name'", 'left');
			
			if (isset($_GET['status']) && !empty($_GET['status']))
			{
				$pjProductModel->where('t1.status', $_GET['status']);
			}
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjProductModel->where("(t2.content LIKE '%$q%')");
			}

			$column = 'name';
			$direction = 'ASC';
			$allowed_columns = array('thumb_path', 'name', 'models', 'categories', '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 = $pjProductModel->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 = $pjProductModel
				->select("t1.id, t1.thumb_path, t1.status, t2.content AS name,
						  (SELECT COUNT(TM.product_id) FROM `".pjProductModModel::factory()->getTable()."` AS `TM` WHERE `TM`.product_id=t1.id) AS models,
						  (SELECT COUNT(TPC.product_id) FROM `".pjProductCategoryModel::factory()->getTable()."` AS `TPC` WHERE `TPC`.product_id=t1.id) AS categories")
				->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())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminProducts.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveProduct()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjProductModel = pjProductModel::factory();
			if (!in_array($_POST['column'], $pjProductModel->i18n))
			{
				$value = $_POST['value'];
				
				$pjProductModel->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'], 'pjProduct', 'data');
			}
		}
		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=pjAdminProducts&action=pjActionIndex&err=AP06");
			}
			if (isset($_POST['product_update']))
			{
				$arr = pjProductModel::factory()->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&action=pjActionIndex&err=AP08");
				}
				
				$pjMultiLangModel = pjMultiLangModel::factory();
				$pjProductModModel = pjProductModModel::factory();
				$pjFeatureModModel = pjFeatureModModel::factory();
				
				$feature_id_arr = array();
				$model_id_arr = array();
				if (isset($_POST['category_id']) && is_array($_POST['category_id']) && count($_POST['category_id']) > 0)
				{
					$feature_id_arr = pjProductFeatureModel::factory()->whereIn('category_id', $_POST['category_id'])->findAll()->getDataPair("id", "id");
					
				}
				if (isset($_POST['i18n']))
				{
					if(isset($_POST['index_arr']) && $_POST['index_arr'] != '')
					{
						$index_arr = explode("|", $_POST['index_arr']);

						foreach($index_arr as $k => $v)
						{
							if(strpos($v, 'pc') !== false)
							{
								$m_data = array();
								$m_data['product_id'] = $_POST['id'];
								
								$model_id = $pjProductModModel->reset()->setAttributes($m_data)->insert()->getInsertId();
								if (isset($_FILES['model_image_' . $v]))
								{
									$model_file = $_FILES['model_image_' . $v];
									if($model_file['error'] == 0)
									{
										$size = getimagesize($model_file['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($model_file))
												{
													$resp = $Image->isConvertPossible();
													if ($resp['status'] === true)
													{
														$hash = md5(uniqid(rand(), true));
														$source_path = PJ_UPLOAD_PATH . 'models/source/' . $model_id . '_' . $hash . '.' . $Image->getExtension();
														$thumb_path = PJ_UPLOAD_PATH . 'models/thumb/' . $model_id . '_' . $hash . '.' . $Image->getExtension();
														if ($Image->save($source_path))
														{
															$Image->loadImage($source_path);
															$Image->resizeSmart(150, 100);
															$Image->saveImage($thumb_path);
															$temp_model_data = array();
															$temp_model_data['source_path'] = $source_path;
															$temp_model_data['thumb_path'] = $thumb_path;
															$pjProductModModel->reset()->where('id', $model_id)->limit(1)->modifyAll($temp_model_data);
														}
													}
												}
											}
										}
									}
								}
								if ($model_id !== false && (int) $model_id > 0)
								{
									$model_id_arr[] = $model_id;
									foreach ($_POST['i18n'] as $locale => $locale_arr)
									{
										foreach ($locale_arr as $field => $content)
										{
											if(is_array($content))
											{
												$insert_id = $pjMultiLangModel->reset()->setAttributes(array(
													'foreign_id' => $model_id,
													'model' => 'pjProductMod',
													'locale' => $locale,
													'field' => $field,
													'content' => $content[$v],
													'source' => 'data'
												))->insert()->getInsertId();
											}
										}
									}
								}
							}else{
								$m_data = array();
								$m_data['product_id'] = $_POST['id'];
								
								$_model_arr = $pjProductModModel->reset()->find($v)->getData();
								if (isset($_FILES['model_image_' . $v]))
								{
									$model_file = $_FILES['model_image_' . $v];
									
									if($model_file['error'] == 0)
									{
										$size = getimagesize($model_file['tmp_name']);
										if($size == true)
										{
											if(!empty($_model_arr['source_path']))
											{
												$source_path = PJ_INSTALL_PATH . $_model_arr['source_path'];
												$thumb_path = PJ_INSTALL_PATH . $_model_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($model_file))
												{
													$resp = $Image->isConvertPossible();
													if ($resp['status'] === true)
													{
														$hash = md5(uniqid(rand(), true));
														$source_path = PJ_UPLOAD_PATH . 'models/source/' . $v . '_' . $hash . '.' . $Image->getExtension();
														$thumb_path = PJ_UPLOAD_PATH . 'models/thumb/' . $v . '_' . $hash . '.' . $Image->getExtension();
														if ($Image->save($source_path))
														{
															$Image->loadImage($source_path);
															$Image->resizeSmart(150, 100);
															$Image->saveImage($thumb_path);
															$m_data['source_path'] = $source_path;
															$m_data['thumb_path'] = $thumb_path;
														}
													}
												}
											}
										}
									}
								}
								
								$pjProductModModel->reset()->where('id', $v)->limit(1)->modifyAll($m_data);
								$model_id_arr[] = $v;
								
								foreach ($_POST['i18n'] as $locale => $locale_arr)
								{
									foreach ($locale_arr as $field => $content)
									{
										if(is_array($content))
										{
											$sql = sprintf("INSERT INTO `%1\$s` (`id`, `foreign_id`, `model`, `locale`, `field`, `content`, `source`)
												VALUES (NULL, :foreign_id, :model, :locale, :field, :update_content, :source)
												ON DUPLICATE KEY UPDATE `content` = :update_content, `source` = :source;",
												$pjMultiLangModel->getTable()
											);
											$foreign_id = $v;
											$model = 'pjProductMod';
											$source = 'data';
											$update_content = $content[$v];
											$modelObj = $pjMultiLangModel->reset()->prepare($sql)->exec(compact('foreign_id', 'model', 'locale', 'field', 'update_content', 'source'));
											if ($modelObj->getAffectedRows() > 0 || $modelObj->getInsertId() > 0)
											{
												
											}
										}
									}
								}
							}
						}
					}					
					foreach ($_POST['i18n'] as $locale => $locale_arr)
					{
						foreach ($locale_arr as $field => $content)
						{
							if(!is_array($content))
							{
								$sql = sprintf("INSERT INTO `%1\$s` (`id`, `foreign_id`, `model`, `locale`, `field`, `content`, `source`)
									VALUES (NULL, :foreign_id, :model, :locale, :field, :content, :source)
									ON DUPLICATE KEY UPDATE `content` = :content, `source` = :source;",
									$pjMultiLangModel->getTable()
								);
								$foreign_id = $_POST['id'];
								$model = 'pjProduct';
								$source = 'data';
								$modelObj = $pjMultiLangModel->reset()->prepare($sql)->exec(compact('foreign_id', 'model', 'locale', 'field', 'content', 'source'));
								if ($modelObj->getAffectedRows() > 0 || $modelObj->getInsertId() > 0)
								{
									
								}
							}
						}
					}
				}
				
				if(isset($_POST['remove_arr']) && $_POST['remove_arr'] != '')
				{
					$remove_arr = explode("|", $_POST['remove_arr']);
					
					$pjMultiLangModel->reset()->where('model', 'pjProductMod')->whereIn('foreign_id', $remove_arr)->eraseAll();
					$remove_model_arr = $pjProductModModel->reset()->whereIn('id', $remove_arr)->findAll()->getData();
					foreach ($remove_model_arr as $k => $v)
					{
						if(!empty($v['source_path']))
						{
							$source_path = PJ_INSTALL_PATH . $v['source_path'];
							$thumb_path = PJ_INSTALL_PATH . $v['thumb_path'];
							@unlink($source_path);
							@unlink($thumb_path);
						}
					}
					$pjProductModModel->reset()->whereIn('id', $remove_arr)->eraseAll();
					
					$pjMultiLangModel
						->reset()
						->where('model', 'pjFeatureMod')
						->where("(foreign_id IN(SELECT TFM.id 
												FROM `".pjFeatureModModel::factory()->getTable()."` AS TFM 
												WHERE TFM.model_id IN(".join(",", $remove_arr).")
								               )
								  )")
						->eraseAll();
					pjFeatureModModel::factory()
						->whereIn('model_id', $remove_arr)
						->eraseAll();
				}
				
				$pjProductCategoryModel = pjProductCategoryModel::factory();
				$category_id_arr = $pjProductCategoryModel->where('product_id', $_POST['id'])->findAll()->getDataPair("category_id", "category_id");
				$pjProductCategoryModel->where('product_id', $_POST['id'])->eraseAll();
				
				if (isset($_POST['category_id']) && is_array($_POST['category_id']) && count($_POST['category_id']) > 0)
				{
					$pjProductCategoryModel->reset()->begin();
					foreach ($_POST['category_id'] as $category_id)
					{
						$pjProductCategoryModel
							->reset()
							->set('product_id', $_POST['id'])
							->set('category_id', $category_id)
							->insert();
					}
					$pjProductCategoryModel->commit();
					
					$category_removed_id_arr = array();
					foreach($category_id_arr as $cid)
					{
						if(!in_array($cid, $_POST['category_id']))
						{
							$category_removed_id_arr[] = $cid;
						}
					}
					if(!empty($category_removed_id_arr))
					{
						$feature_removed_id_arr = pjProductFeatureModel::factory()->whereIn('category_id', $category_removed_id_arr)->findAll()->getDataPair("id", "id");
						
						if(!empty($feature_removed_id_arr))
						{
							$pjMultiLangModel
								->reset()
								->where('model', 'pjFeatureMod')
								->where("(foreign_id IN(SELECT TFM.id 
														FROM `".pjFeatureModModel::factory()->getTable()."` AS TFM 
														WHERE TFM.feature_id IN(".join(",", $feature_removed_id_arr).") AND TFM.model_id IN(".join(",", $model_id_arr).")
										               )
										  )")
								->eraseAll();
							pjFeatureModModel::factory()
								->whereIn('feature_id', $feature_removed_id_arr)
								->whereIn('model_id', $model_id_arr)
								->eraseAll();
								
						}
					}
					
				}
				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 . 'products/source/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
										$thumb_path = PJ_UPLOAD_PATH . 'products/thumb/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
										if ($Image->save($source_path))
										{
											$Image->loadImage($source_path);
											$Image->resizeSmart(150, 100);
											$Image->saveImage($thumb_path);
											$data = array();
											$data['source_path'] = $source_path;
											$data['thumb_path'] = $thumb_path;
											pjProductModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
										}
									}
								}
							}
						}else{
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&action=pjActionUpdate&id=".$_POST['id']."&err=AP11");
						}
					}else if($_FILES['image']['error'] != 4){
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&action=pjActionUpdate&id=".$_POST['id']."&err=AP10");
					}
				}
								
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminProducts&action=pjActionUpdate&id=".$_POST['id']."&err=AP01");
				
			} else {
				$pjMultiLangModel = pjMultiLangModel::factory();
				
				$arr = pjProductModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminProducts&action=pjActionIndex&err=AP08");
				}
				$arr['i18n'] = $pjMultiLangModel->getMultiLang($arr['id'], 'pjProduct');
				$this->set('arr', $arr);
				
				$model_arr = pjProductModModel::factory()->where('product_id', $_GET['id'])->findAll()->getData();
				foreach($model_arr as $k => $v)
				{
					$model_arr[$k]['i18n'] = $pjMultiLangModel->reset()->getMultiLang($v['id'], 'pjProductMod');
				}
				
				$this->set('model_arr', $model_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('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());
				$this->set('category_id_arr', pjProductCategoryModel::factory()
					->where('product_id', $_GET['id'])
					->findAll()
					->getDataPair("category_id", "category_id"));
				
				$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('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('pjAdminProducts.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionFeature()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['feature_update']))
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$pjFeatureModModel = pjFeatureModModel::factory();
				
				if (isset($_POST['i18n']))
				{
					$j = 1;
					$feature_mod_id_arr = array();
					
					$feature_mod_arr = pjFeatureModModel::factory()
						->where("t1.model_id IN(SELECT TPM.id FROM `".pjProductModModel::factory()->getTable()."` AS TPM WHERE TPM.product_id = '".$_POST['id']."')")
						->findAll()
						->getData();
						
					$grid_arr = array();
					foreach($feature_mod_arr as $k => $v)
					{
						$grid_arr[$v['feature_id'] . '_' . $v['model_id']] = $v['id'];
					}
					
					foreach ($_POST['i18n'] as $locale => $locale_arr)
					{
						foreach ($locale_arr as $field => $content)
						{
							if(is_array($content))
							{
								foreach($content as $k => $v)
								{
									$id = null;
									if($j == 1)
									{
										list($feature_id, $model_id) = explode("_", $k);
										if(array_key_exists($k, $grid_arr))
										{
											$id = $grid_arr[$k];
										}else{
											$id = $pjFeatureModModel
												->reset()
												->setAttributes(array('feature_id' => $feature_id, 'model_id' => $model_id))
												->insert()
												->getInsertId();
										}
										$feature_mod_id_arr[$k] = $id;
									}else{
										$id = $feature_mod_id_arr[$k];
									}
									if($id != null)
									{
										$insert_id = $pjMultiLangModel->reset()->setAttributes(array(
											'foreign_id' => $id,
											'model' => 'pjFeatureMod',
											'locale' => $locale,
											'field' => $field,
											'content' => $v,
											'source' => 'data'
										))->insert()->getInsertId();
										
										if ($insert_id === FALSE || (int) $insert_id <= 0)
										{
											$pjMultiLangModel->reset()
												->where('foreign_id', $id)
												->where('model', 'pjFeatureMod')
												->where('locale', $locale)
												->where('field', $field)
												->limit(1)
												->modifyAll(array('content' => $v));
										}
									}
								}
							}
						}
						$j++;
					}
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminProducts&action=pjActionFeature&id=".$_POST['id']."&err=AP02");
			}else{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$pjProductFeatureModel = pjProductFeatureModel::factory();
				
				$arr = pjProductModel::factory()
					->select('t1.*, t2.content AS product_name')
					->join('pjMultiLang', "t2.model='pjProduct' AND t2.foreign_id=t1.id AND t2.field='product_name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminProducts&action=pjActionIndex&err=AP08");
				}
				$arr['i18n'] = $pjMultiLangModel->getMultiLang($arr['id'], 'pjProduct');
				$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('model_arr', pjProductModModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjProductMod' AND t2.foreign_id=t1.id AND t2.field='model_name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('product_id', $_GET['id'])
					->findAll()
					->getData());
				$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.id IN(SELECT TPC.category_id FROM `".pjProductCategoryModel::factory()->getTable()."` AS TPC WHERE TPC.product_id = '".$_GET['id']."')")
					->where('t1.status', 'T')
					->findAll()
					->getData();
				foreach($category_arr as $k => $v)
				{
					$v['features'] = $pjProductFeatureModel
						->reset()
						->select('t1.*, t2.content AS title')
						->join('pjMultiLang', "t2.model='pjProductFeature' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->where('t1.category_id', $v['id'])
						->where('t1.status', 'T')
						->findAll()
						->getData();
					$category_arr[$k] = $v;
				}
				$this->set('category_arr',$category_arr);
				
				$feature_mod_arr = pjFeatureModModel::factory()
					->where("t1.model_id IN(SELECT TPM.id FROM `".pjProductModModel::factory()->getTable()."` AS TPM WHERE TPM.product_id = '".$_GET['id']."')")
					->findAll()
					->getData();
					
				$grid_arr = array();
				foreach($feature_mod_arr as $k => $v)
				{
					$v['i18n'] = $pjMultiLangModel->reset()->getMultiLang($v['id'], 'pjFeatureMod');
					$grid_arr[$v['feature_id'] . '_' . $v['model_id']] = $v;
				}
				$this->set('grid_arr',$grid_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('pjAdminProducts.js');
			}
			
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
				
			$pjProductModel = pjProductModel::factory();
			$arr = $pjProductModel->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';
				$pjProductModel->reset()->where(array('id' => $_GET['id']))->limit(1)->modifyAll($data);
	
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
				
			pjAppController::jsonResponse($response);
		}
	}
	public function pjActionDeleteModelImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
	
			$pjProductModModel = pjProductModModel::factory();
			$arr = $pjProductModModel->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';
				$pjProductModModel->reset()->where(array('id' => $_GET['id']))->limit(1)->modifyAll($data);
	
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
	
			pjAppController::jsonResponse($response);
		}
	}
}
?>