<?php

require_once('api/Simpla.php');

//include $_SERVER['DOCUMENT_ROOT'].'/api/SimpleImage.php';

############################################
# Class Category - Edit the good gategory
############################################
class ArticleCategoryAdmin extends Simpla
{
	private $allowed_image_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico');
  function fetch()
  { 
  	
		if($this->request->method('post'))
		{
			$category->id = $this->request->post('id', 'integer');
			$category->parent_id = $this->request->post('parent_id', 'integer');
			$category->name = $this->request->post('name');
			$category->visible = $this->request->post('visible', 'boolean');

			$category->url = $this->request->post('url', 'string');
			$category->meta_title = $this->request->post('meta_title');
			$category->meta_keywords = $this->request->post('meta_keywords');
			$category->meta_description = $this->request->post('meta_description');
			
			$category->description = $this->request->post('description');
			
			$image = $this->request->files('image');
	
			// Не допустить одинаковые URL разделов.
			if(($c = $this->articles->get_category($category->url)) && $c->id!=$category->id)
			{			
				$this->design->assign('message_error', 'url_exists');
			}
			else
			{
			
            // Загрузка изображения
				
				if(!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions))
				{
					$image['name'] = $this->rus_lat($image['name']);
					if ($image_name = $this->image->upload_image($image['tmp_name'], $image['name']))
					{
							$this->articles->delete_category_image($category->id);
							$this->articles->update_articles_category($article->id, array('image'=>$image_name));
							$category->image = $image_name;
					}
					else
					{
						$this->design->assign('error', 'error uploading image');
					}	
				}
				
				if(empty($category->id))
				{
	  				$category->id = $this->articles->add_category($category);
					$this->design->assign('message_success', 'added');
	  			}
  	    		else
  	    		{
  	    			$this->articles->update_category($category->id, $category);
					$this->design->assign('message_success', 'updated');
  	    		}
  	    		// Удаление изображения
  	    		if($this->request->post('delete_image'))
  	    		{
  	    			$this->articles->delete_category_image($category->id);
  	    		}
  	    		$category = $this->articles->get_category(intval($category->id));
			}
		}
		else
		{
			$category->id = $this->request->get('id', 'integer');
			$category = $this->articles->get_category($category->id);
			if(!$category->id) $category->visible = 1;
		}
		 
		$categories = $this->articles->get_categories_tree();

		$this->design->assign('category', $category);
		$this->design->assign('categories', $categories);
		return  $this->design->fetch('article_category.tpl');
	}
	
	function rus_lat($name){
		$rus = array('','а','б','в','г','д','е','ё','Ё','ж','з','и','й','к',
		'л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я');
		$eng = array('','a','b','v','g','d','e','e','e','zh','z','i','j','k',
		'l','m','n','o','p','r','s','t','u','f','h','c','ch','sh','shch','','y','','e','yu','ya');
		$name = mb_strtolower($name,"UTF-8");
		$name = str_replace(array('"',"'"),'',$name);
		$name = str_replace(array(',',':',';','/','{','}','[',']'),'',$name);
		$name = str_replace(array(' '),'_',$name);
		$res = '';
		$arr = $this->str_split_unicode($name);
		foreach($arr as $key){
			if($key == '_'){
				$res .= '_';
				continue;
			}
			if (!preg_match("/[а-я]/i", $key)){
				$res .= $key;
				continue;
			}
			$k = array_search($key,$rus);
			if($k){
				$res .= $eng[$k];
			}
		}
		return $res;
	}

	function str_split_unicode($str, $l = 0) {
	    if ($l > 0) {
	        $ret = array();
	        $len = mb_strlen($str, "UTF-8");
	        for ($i = 0; $i < $len; $i += $l) {
	            $ret[] = mb_substr($str, $i, $l, "UTF-8");
	        }
	        return $ret;
	    }
	    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
	}
}