<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminListings extends pjAdmin
{
	private $imageFiles = array('small_path', 'medium_path', 'large_path', 'source_path');
	
	public function pjActionCheckRefId()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() && isset($_GET['listing_refid']))
		{
			$pjListingModel = pjListingModel::factory();
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjListingModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjListingModel->where('t1.listing_refid', $_GET['listing_refid'])->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$type_arr = pjTypeModel::factory()->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->where('status', 'T')
				->orderBy('name ASC')
				->findAll()
				->getData();
			
			$_feature_arr = pjFeatureModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjFeature' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->where('status', 'T')
				->orderBy('name ASC')
				->findAll()
				->getData();
			$feature_arr = array();
			foreach($_feature_arr as $k => $v)
			{
				$feature_arr[$v['type']][] = $v;
			}
			
			$this->set('type_arr', $type_arr);		
			$this->set('feature_arr', $feature_arr);
			
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
					
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminListings.js');
			
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjListingModel = pjListingModel::factory()
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t4.model='pjType' AND t4.foreign_id=t1.type_id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t5.model='pjBreed' AND t5.foreign_id=t1.breed_id AND t5.field='name' AND t5.locale='".$this->getLocaleId()."'", 'left outer');
			
			if (isset($_GET['status']) && !empty($_GET['status']))
			{
				$pjListingModel->where("t1.status", $_GET['status']);
			}
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$pjListingModel->where(sprintf("(t1.listing_refid LIKE '%%%1\$s%%' OR t2.content LIKE '%%%1\$s%%' OR t3.content LIKE '%%%1\$s%%')", pjObject::escapeString($_GET['q'])));
			}
			
			if (isset($_GET['listing_refid']) && !empty($_GET['listing_refid']))
			{
				$q = pjObject::escapeString($_GET['listing_refid']);
				$pjListingModel->where('t1.listing_refid LIKE', "%$q%");
			}
			
			if (isset($_GET['type_id']) && !empty($_GET['type_id']))
			{
				$pjListingModel->where('t1.type_id', $_GET['type_id']);
			}
			if (isset($_GET['breed_id']) && !empty($_GET['breed_id']))
			{
				$pjListingModel->where('t1.breed_id', $_GET['breed_id']);
			}
			if (isset($_GET['feature_age_id']) && !empty($_GET['feature_age_id']))
			{
				$pjListingModel->where('t1.feature_age_id', $_GET['feature_age_id']);
			}
			if (isset($_GET['feature_color_id']) && !empty($_GET['feature_color_id']))
			{
				$pjListingModel->where('t1.feature_color_id', $_GET['feature_color_id']);
			}
			if (isset($_GET['feature_sex_id']) && !empty($_GET['feature_sex_id']))
			{
				$pjListingModel->where('t1.feature_sex_id', $_GET['feature_sex_id']);
			}
			if (isset($_GET['feature_size_id']) && !empty($_GET['feature_size_id']))
			{
				$pjListingModel->where('t1.feature_size_id', $_GET['feature_size_id']);
			}
			
			if (isset($_GET['year_from']) && (int) $_GET['year_from'] > 0 && isset($_GET['year_to']) && (int) $_GET['year_to'] > 0)
			{
				$pjListingModel->where("(t1.listing_year BETWEEN '".$_GET['year_from']."' AND '".$_GET['year_to']."')");
			} else if(isset($_GET['year_from']) && (int) $_GET['year_from'] > 0 && !isset($_GET['year_to']) && (int) $_GET['year_to'] <= 0){
				$pjListingModel->where("(t1.listing_year >= '".$_GET['year_from']."')");
			}else if(!isset($_GET['year_from']) && (int) $_GET['year_from'] <= 0 && isset($_GET['year_to']) && (int) $_GET['year_to'] > 0){
				$pjListingModel->where("(t1.listing_year <= '".$_GET['year_to']."')");
			}
			
			$column = 'id';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
			
			$total = $pjListingModel->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 = $pjListingModel
				->select(sprintf('t1.*, t4.content as `type`, t5.content as breed, 
								(SELECT `small_path` FROM `%s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `image`', pjGalleryModel::factory()->getTable()))
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
				
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['listing_create']))
			{
				$data = array();
				$data['created'] = date('Y-m-d H:i:s');
				$data = array_merge($_POST, $data);
				$pjListingModel = pjListingModel::factory();
				if (!$pjListingModel->validates($data))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionCreate&err=AL09");
				}
				
				if ($pjListingModel->where('t1.listing_refid', $data['listing_refid'])->findCount()->getData() > 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionCreate&err=AL10");
				}
				
				$id = $pjListingModel->reset()->setAttributes($data)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AL03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjListing', 'data');
					}
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $id . "&err=$err");
				} else {
					$err = 'AL04';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionCreate&err=$err");
				}
			}else{
				$type_arr = pjTypeModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')
					->orderBy('name ASC')
					->findAll()
					->getData();
				
				$this->set('type_arr', $type_arr);
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminListings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
			
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['listing_update']))
			{
				$arr = pjListingModel::factory()->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL08");
				}
				
				$err = NULL;
				$data = array();
				$data['modified'] = date("Y-m-d H:i:s");
			
				$pjListingModel = pjListingModel::factory();
				$post = array_merge($_POST, $data);

				if (!$pjListingModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $_POST['id'] . "&locale=" . $_POST['locale'] . "&tab_id=" . $_POST['tab_id'] . "&err=AL09");
				}
				
				if ($pjListingModel->where('t1.id !=', $_POST['id'])->where('t1.listing_refid', $post['listing_refid'])->findCount()->getData() > 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $_POST['id'] . "&locale=" . $_POST['locale'] . "&tab_id=" . $_POST['tab_id'] . "&err=AL10");
				}
				
				$pjListingModel->set('id', $_POST['id'])->modify($post);

				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjListing', 'data');
				}
				
				pjListingExtraModel::factory()->where('listing_id', $_POST['id'])->eraseAll();
				
				if (isset($_POST['extra']) && is_array($_POST['extra']) && count($_POST['extra']) > 0)
				{
					$pjListingExtraModel = pjListingExtraModel::factory();
					$pjListingExtraModel->begin();
					foreach ($_POST['extra'] as $extra_id)
					{
						$pjListingExtraModel->setAttributes(array(
							'listing_id' => $_POST['id'],
							'extra_id' => $extra_id
						))->insert();
					}
					$pjListingExtraModel->commit();
				}
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $_POST['id'] . "&locale=" . $_POST['locale'] . "&tab_id=" . $_POST['tab_id'] . "&err=AL01");
				
			} else {
				$arr = pjListingModel::factory()->find($_GET['id'])->getData();
				
				if (count($arr) === 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjListing');
				
				$type_arr = pjTypeModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')
					->orderBy('name ASC')
					->findAll()
					->getData();
						
				$breed_arr = pjBreedModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjBreed' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('t1.type_id', $arr['type_id'])
					->where('status', 'T')
					->orderBy('name ASC')
					->findAll()
					->getData();
			
				$extra_arr = pjExtraModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjExtra' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')
					->orderBy('name ASC')
					->findAll()
					->getData();
				
				$listing_extra_arr = pjListingExtraModel::factory()
					->where('t1.listing_id', $arr['id'])
					->findAll()
					->getDataPair(null, 'extra_id');
				
				$_feature_arr = pjFeatureModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjFeature' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')
					->orderBy('name ASC')
					->findAll()
					->getData();
				$feature_arr = array();
				foreach($_feature_arr as $k => $v)
				{
					$feature_arr[$v['type']][] = $v;
				}
				
				$this->set('type_arr', $type_arr);		
				$this->set('breed_arr', $breed_arr);
				$this->set('extra_arr', $extra_arr);
				$this->set('feature_arr', $feature_arr);
				$this->set('listing_extra_arr', $listing_extra_arr);
				
				$country_arr = pjCountryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('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('arr', $arr);
				$this->set('gallery_arr', pjGalleryModel::factory()->where('foreign_id', $arr['id'])->findAll()->getData());
				$this->set('category_arr', pjSanitize::clean($category_arr));
				$this->set('listing_extra_arr', pjListingExtraModel::factory()->where('t1.listing_id', $arr['id'])->findAll()->getDataPair(NULL, 'extra_id'));
				$this->set('country_arr', pjSanitize::clean($country_arr));
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
											
				# TinyMCE
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tiny_mce/');
				
				# Gallery plugin
				$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
				$this->appendJs('ajaxupload.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				
				$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('pjAdminListings.js');				
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionStatusListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0 && isset($_GET['status']) && in_array($_GET['status'], array('T', 'F', 'E')))
			{
				pjListingModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('status' => $_GET['status']));
			}
		}
		exit;
	}
	
	public function pjActionSaveListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjListingModel = pjListingModel::factory();
			if (!in_array($_POST['column'], $pjListingModel->i18n))
			{
				if (in_array($_POST['column'], array('expire')))
				{
					$_POST['value'] = pjUtil::formatDate($_POST['value'], $this->option_arr['o_date_format']);
				}
				$value = $_POST['value'];
				
				$pjListingModel->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'], 'pjListing', 'data');
			}
		}
		exit;
	}
	
	public function pjActionDeleteListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjListingModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjListing')->where('foreign_id', $_GET['id'])->eraseAll();
				
				pjListingExtraModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				
				$pjGalleryModel = pjGalleryModel::factory();
				$arr = $pjGalleryModel->where('foreign_id', $_GET['id'])->findAll()->getData();
				if (count($arr) > 0)
				{
					foreach ($arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
					$pjGalleryModel->eraseAll();
				}
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteListingBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjListingModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjListing')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				pjListingExtraModel::factory()->whereIn('listing_id', $_POST['record'])->eraseAll();
				
				$arr = pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->findAll()->getData();
				if (count($arr) > 0)
				{
					pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->eraseAll();
					foreach ($arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionGetBreeds()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$breed_arr = pjBreedModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjBreed' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->where('t1.type_id', $_GET['type_id'])
				->where('status', 'T')
				->orderBy('name ASC')
				->findAll()
				->getData();
			
			$this->set('breed_arr', $breed_arr);
				
		}
	}
}