<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminCategories extends pjAdmin
{
	public function pjActionDeleteCategory()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		if (!self::isPost())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
		}
		if (!pjAuth::factory()->hasAccess())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
		}
		if (!($this->_get->toInt('id')))
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
		}
		$arr = pjCategoryModel::factory()->find($this->_get->toInt('id'))->getData();
		if (!pjCategoryModel::factory()->reset()->set('id', $this->_get->toInt('id'))->erase()->getAffectedRows())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 105, 'text' => 'Category has not been deleted.'));
		}
		pjMultiLangModel::factory()->where('model', 'pjCategory')->where('foreign_id', $this->_get->toInt('id'))->eraseAll();
		pjServiceCategoryModel::factory()->where('category_id', $this->_get->toInt('id'))->eraseAll();
		@clearstatcache();
		if (!empty($arr['image']) && is_file($arr['image']))
		{
			@unlink($arr['image']);
		}
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Category has been deleted'));
		exit;
	}
	
	public function pjActionDeleteCategoryBulk()
	{
	    $this->setAjax(true);
	    if (!$this->isXHR())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
	    }
	    if (!self::isPost())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
	    }
	    if (!pjAuth::factory()->hasAccess())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
	    }
	    if (!$this->_post->has('record'))
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
	    }
	    $record = $this->_post->toArray('record');
	    if (empty($record))
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 104, 'text' => 'Missing, empty or invalid parameters.'));
	    }
	    $arr = pjCategoryModel::factory()->where('id !=', 1)->whereIn('id', $record)->findAll()->getData();
	    pjMultiLangModel::factory()->where('model', 'pjCategory')->whereIn('foreign_id', $record)->eraseAll();
	    pjServiceCategoryModel::factory()->whereIn('category_id', $record)->eraseAll();
	    pjCategoryModel::factory()->whereIn('id', $record)->eraseAll();
		@clearstatcache();
		foreach ($arr as $val) {
			if (!empty($val['image']) && is_file($val['image']))
			{
				@unlink($val['image']);
			}
		}
	    self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Categories has been deleted.'));
	    exit;
	}
	
	public function pjActionGetCategory()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjCategoryModel = pjCategoryModel::factory()
				->join('pjMultiLang', sprintf("t2.foreign_id = t1.id AND t2.model = 'pjCategory' AND t2.locale = '%u' AND t2.field = 'name'", $this->getLocaleId()), 'left');
			if ($q = $this->_get->toString('q'))
			{
			    $pjCategoryModel->where("(t2.content LIKE '%$q%')");
			}
			if ($this->_get->toString('status'))
			{
			    $status = $this->_get->toString('status');
			    if(in_array($status, array('T', 'F')))
			    {
			        $pjCategoryModel->where('t1.status', $status);
			    }
			}
			$column = 'order';
			$direction = 'ASC';
			if ($this->_get->toString('column') && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC')))
			{
			    $column = $this->_get->toString('column');
			    $direction = strtoupper($this->_get->toString('direction'));
			}
			$total = $pjCategoryModel->findCount()->getData();
			$rowCount = $this->_get->toInt('rowCount') ?: 10;
			$pages = ceil($total / $rowCount);
			$page = $this->_get->toInt('page') ?: 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}
			$data = $pjCategoryModel
				->select("t1.*, t2.content AS name")
				->orderBy("`$column` $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			$service_gender = __('service_gender', true);
			foreach ($data as $k => $v) {
				$data[$k]['gender_formated'] = @$service_gender[$v['gender']];
			}
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
		
	public function pjActionIndex()
	{
	    $this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	    $this->setLocalesData();
	    
	    $this->set('has_update', pjAuth::factory('pjAdminCategories', 'pjActionUpdateForm')->hasAccess());
		$this->set('has_create', pjAuth::factory('pjAdminCategories', 'pjActionCreateForm')->hasAccess());
		$this->set('has_delete', pjAuth::factory('pjAdminCategories', 'pjActionDeleteCategory')->hasAccess());
		$this->set('has_delete_bulk', pjAuth::factory('pjAdminCategories', 'pjActionDeleteCategoryBulk')->hasAccess());
	    
	    $this->appendCss('jasny-bootstrap.min.css', PJ_THIRD_PARTY_PATH . 'jasny/');
		$this->appendJs('jasny-bootstrap.min.js', PJ_THIRD_PARTY_PATH . 'jasny/');
	    $this->appendJs('jquery-ui.min.js', PJ_THIRD_PARTY_PATH . 'jquery_ui/');
	    $this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
	    $this->appendJs('jquery.multilang.js', $this->getConstant('pjBase', 'PLUGIN_JS_PATH'), false, false);
	    $this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
	    $this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
	    $this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
	    $this->appendJs('pjAdminCategories.js');
	}
	
	public function pjActionCreate()
	{
	    $this->setAjax(true);
	    if (!pjAuth::factory()->hasAccess())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
	    }
	    if (!$this->isXHR())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
	    }
	    if (!self::isPost())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
	    }
	    if (!$this->_post->toInt('category_create'))
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
	    }
	    $post = $this->_post->raw();
	    $pjCategoryModel = pjCategoryModel::factory();
	    $data = array();
	    $data['status'] = $this->_post->check('status') ? 'T' : 'F';
	    $data['order'] = $pjCategoryModel->getLastOrder();
	    
	    $id = $pjCategoryModel->setAttributes(array_merge($post, $data))->insert()->getInsertId();
	    if ($id !== false && (int) $id > 0)
	    {
	        if (isset($post['i18n']))
	        {
	            pjMultiLangModel::factory()->saveMultiLang($post['i18n'], $id, 'pjCategory', 'data');
	        }
	        
	    	if (isset($_FILES['image']))
			{
				if($_FILES['image']['error'] == 0)
				{
					$size = getimagesize($_FILES['image']['tmp_name']);
					if($size == true)
					{
						$pjImage = new pjImage();
						$pjImage->setAllowedExt($this->extensions)->setAllowedTypes($this->mimeTypes);
						if ($pjImage->load($_FILES['image']))
						{
							$image_path = PJ_UPLOAD_PATH . 'categories/' . md5($id . PJ_SALT) . ".jpg";
							$pjImage
								->loadImage()
								->resizeSmart(100, 170)
								->saveImage($image_path);
			
							$pjCategoryModel->reset()->set('id', $id)->modify(array('image' => $image_path));
						}
					}else{
						
					}
				}else if($_FILES['image']['error'] != 4){
					
				}
			}
			
	        self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Category has been added!'));
	    } else {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 104, 'text' => 'Category could not be added!'));
	    }
	    exit;
	}
	
	public function pjActionUpdate()
	{
	    $this->setAjax(true);
	    if (!pjAuth::factory()->hasAccess())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
	    }
	    if (!$this->isXHR())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
	    }
	    if (!self::isPost())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
	    }
	    if (!$this->_post->toInt('category_update'))
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
	    }
	    if (!$this->_post->toInt('id'))
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 104, 'text' => 'Missing, empty or invalid parameters.'));
	    }
	    $post = $this->_post->raw();
	    $pjCategoryModel = pjCategoryModel::factory();
	    $data = array();
	    $data['status'] = $this->_post->check('status') ? 'T' : 'F';
	    $pjCategoryModel->reset()->where('id', $this->_post->toInt('id'))->limit(1)->modifyAll(array_merge($post, $data));
	    if (isset($post['i18n']))
	    {
	        pjMultiLangModel::factory()->updateMultiLang($post['i18n'], $post['id'], 'pjCategory', 'data');
	    }
	    
	    if (isset($_FILES['image']))
		{
			if($_FILES['image']['error'] == 0)
			{
				$size = getimagesize($_FILES['image']['tmp_name']);
				if($size == true)
				{
					$arr = $pjCategoryModel->reset()->find($this->_post->toInt('id'))->getData();
					$pjImage = new pjImage();
					$pjImage->setAllowedExt($this->extensions)->setAllowedTypes($this->mimeTypes);
					if ($pjImage->load($_FILES['image']))
					{
						if ($arr) {
							@clearstatcache();
							if (!empty($arr['image']) && is_file($arr['image']))
							{
								@unlink($arr['image']);
							}
						}
						mt_srand();
						$rand = mt_rand(1, 9999);
						$image_path = PJ_UPLOAD_PATH . 'categories/' . md5($arr['id'].$rand. PJ_SALT) . ".jpg";
						$pjImage
							->loadImage()
							->resizeSmart(100, 170)
							->saveImage($image_path);
						$pjCategoryModel->reset()->set('id', $arr['id'])->modify(array('image' => $image_path));
					} else {
						
					}
				}else{
					
				}
			}else if($_FILES['image']['error'] != 4){
				
			}
		}	
		
	    self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Category has been updated!'));
	    exit;
	}
	
	public function pjActionSortCategory()
	{
		$this->setAjax(true);
		if (!$this->isXHR())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		if (!self::isPost())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
		}
		$post = $this->_post->raw();
		$pjCategoryModel = pjCategoryModel::factory();
		foreach($post['sort'] as $k => $v)
		{
		    $pjCategoryModel->reset()->set('id', $v)->modify(array('order' => $k+1));
		}
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Categories has been sorted.'));
		exit;
	}
	
	public function pjActionSaveCategory()
	{
	    $this->setAjax(true);
	    
	    if (!$this->isXHR())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
	    }
	    
	    if (!self::isPost())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
	    }
	    
	    if (!pjAuth::factory($this->_get->toString('controller'), 'pjActionUpdate')->hasAccess())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
	    }
	    $pjCategoryModel = pjCategoryModel::factory();
	    $arr = $pjCategoryModel->find($this->_get->toInt('id'))->getData();
	    if (!$arr)
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Location not found.'));
	    }
	    if (!in_array($this->_post->toString('column'), $pjCategoryModel->getI18n()))
	    {
	        $pjCategoryModel->reset()->where('id', $this->_get->toInt('id'))->limit(1)->modifyAll(array($this->_post->toString('column') => $this->_post->toString('value')));
	    } else {
	        pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($this->_post->toString('column') => $this->_post->toString('value'))), $this->_get->toInt('id'), 'pjCategory', 'data');
	    }
	    
	    self::jsonResponse(array('status' => 'OK', 'code' => 201, 'text' => 'Category has been updated.'));
	    
	    exit;
	}
	
	public function pjActionCreateForm()
	{
	    $this->setAjax(true);
	    
	    if (!$this->isXHR())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
	    }
	    if (!self::isGet())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
	    }
	    $this->setLocalesData();
	}
	
	public function pjActionUpdateForm()
	{
	    $this->setAjax(true);
	    
	    if (!$this->isXHR())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
	    }
	    if (!self::isGet())
	    {
	        self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
	    }
	    if ($this->_get->toInt('id'))
	    {
	        $id = $this->_get->toInt('id');
	        $arr = pjCategoryModel::factory()->find($id)->getData();
	        if (count($arr) === 0)
	        {
	            self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Category is not found.'));
	        }
	        $arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjCategory');
	        $this->set('arr', $arr);
	        
	        $this->setLocalesData();
	    }else{
	        self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing parameters.'));
	    }
	}
	
	public function pjActionDeleteImage()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
	
		if (!self::isPost())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'HTTP method not allowed.'));
		}
	
		if ($this->_post->check('id') && $this->_post->toInt('id'))
		{
			$pjCategoryModel = pjCategoryModel::factory();
			$arr = $pjCategoryModel->find($this->_post->toInt('id'))->getData();
			if (!empty($arr))
			{
				$pjCategoryModel->reset()->set('id', $arr['id'])->modify(array('image' => ':NULL'));
	
				@clearstatcache();
				if (!empty($arr['image']) && is_file($arr['image']))
				{
					@unlink($arr['image']);
				}
				self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
			}
		}
		self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
	}
	
	public function pjActionUpdate13713() {
		$pjAuthPermissionModel = pjAuthPermissionModel::factory();
		$pjAuthRolePermissionModel = pjAuthRolePermissionModel::factory();
		$pjAuthUserModel = pjAuthUserModel::factory();
		$pjAuthUserPermissionModel = pjAuthUserPermissionModel::factory();
		
		$auth_permission = $pjAuthPermissionModel->reset()
			->whereIn('t1.key', array('pjAdminCategories','pjAdminCategories_pjActionIndex','pjAdminCategories_pjActionCreateForm','pjAdminCategories_pjActionUpdateForm','pjAdminCategories_pjActionDeleteCategory','pjAdminCategories_pjActionDeleteCategoryBulk'))
			->findAll()->getDataPair(null, 'id');
		
		$user_arr = $pjAuthUserModel->reset()->whereIn('t1.role_id', array(1))->findAll()->getDataPair(null, 'id');
		foreach ($auth_permission as $val) {
			$pjAuthRolePermissionModel->reset()->setAttributes(array('role_id' => 1, 'permission_id' => $val))->insert();
		}
		foreach ($user_arr as $val) {
			foreach ($auth_permission as $v) {
				$pjAuthUserPermissionModel->reset()->setAttributes(array('user_id' => $val, 'permission_id' => $v))->insert();
			}
		}	
		
		echo 'Data updated!';
		exit;
	}
}
?>