<?php

require_once('api/Simpla.php');

if(!class_exists('SimpleImage')) include $_SERVER['DOCUMENT_ROOT'].'/api/SimpleImage.php';

############################################
# Class Category - Edit the good gategory
############################################
class CategoryAdmin 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->ym = $this->request->post('ym', 'boolean');
			$category->menu = $this->request->post('menu', 'boolean');
			$category->from_subs = $this->request->post('from_subs', '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');
			
			$category->category_h1 = $this->request->post('category_h1'); //var_dump($category);
			$category->text_bottom = $this->request->post('text_bottom');
			$category->anons = $this->request->post('anons');
			$category->menu_name = $this->request->post('menu_name');
			
			$category->how2show = $this->request->post('how2show');
	
			// Не допустить одинаковые URL разделов.
			if(($c = $this->categories->get_category($category->url)) && $c->id!=$category->id)
			{			
				$this->design->assign('message_error', 'url_exists');
			}
			else
			{
				if(empty($category->id))
				{
	  				$category->id = $this->categories->add_category($category);
					$this->design->assign('message_success', 'added');
	  			}
  	    		else
  	    		{ 
  	    			$this->categories->update_category($category->id, $category);
					$this->design->assign('message_success', 'updated');
  	    		}
  	    		// Удаление изображения
  	    		if($this->request->post('delete_image'))
  	    		{
  	    			$this->categories->delete_image($category->id);
  	    		}
  	    		// Загрузка изображения
  	    		$image = $this->request->files('image');
  	    		if(!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions))
  	    		{
  	    			$this->categories->delete_image($category->id);
  	    			$image['name'] = $this->rus_lat($image['name']);
  	    			$image['name'] = $this->getUniqueFileName($this->root_dir.$this->config->categories_images_dir, $image['name']);
  	    			move_uploaded_file($image['tmp_name'], $this->root_dir.$this->config->categories_images_dir.$image['name']);
  	    			
  	    			
  	    			
  	    			$img = new SimpleImage($this->root_dir.$this->config->categories_images_dir.$image['name']);
				$img->best_fit(1200, 1200)->save($this->root_dir.$this->config->categories_images_dir.$image['name']);
  	    			$this->categories->update_category($category->id, array('image'=>$image['name'])); 
  	    		}
  	    		$category = $this->categories->get_category(intval($category->id));
			}
		}
		else
		{
			$category->id = $this->request->get('id', 'integer');
			$category = $this->categories->get_category($category->id);
			if(!$category->id) $category->visible = 1;
		}
		

		$categories = $this->categories->get_categories_tree();

		$this->design->assign('category', $category); //var_dump($categories);
		$this->design->assign('categories', $categories);
		return  $this->design->fetch('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);
	}
}