<?php

require_once('api/Simpla.php');


############################################
# Class Category - Edit the good gategory
############################################
class ModelAdmin extends Simpla
{
  private $allowed_image_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico');

  function fetch()
  {

		if($this->request->method('post'))
		{
			$brand->id = $this->request->post('id', 'integer');
			$brand->name = $this->request->post('name');
			$brand->description = $this->request->post('description');

			$brand->url = $this->request->post('url', 'string');
			$brand->meta_title = $this->request->post('meta_title');
			$brand->meta_keywords = $this->request->post('meta_keywords');
			$brand->meta_description = $this->request->post('meta_description');
			$brand->marka_id = $this->request->post('marka_id');
			
			// Не допустить одинаковые URL разделов.
			if(($c = $this->model->get_model($brand->url)) && $c->id!=$brand->id)
			{			
				$this->design->assign('message_error', 'url_exists');
			}
			else
			{
				if(empty($brand->id))
				{
	  				$brand->id = $this->model->add_model($brand);
					$this->design->assign('message_success', 'added');
	  			}
  	    		else
  	    		{
  	    			$this->model->update_model($brand->id, $brand);
					$this->design->assign('message_success', 'updated');
  	    		}	
  	    		// Удаление изображения
  	    		if($this->request->post('delete_image'))
  	    		{
  	    			$this->model->delete_image($brand->id);
  	    		}
  	    		// Загрузка изображения
  	    		$image = $this->request->files('image');
  	    		if(!empty($image['name']) && in_array(strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)), $this->allowed_image_extentions))
  	    		{
  	    			$this->model->delete_image($brand->id);
					  $image['name'] = $this->rus_lat($image['name']);  	 
					  $image['name'] = $this->getUniqueFileName($this->root_dir.$this->config->model_images_dir, $image['name']);   			
  	    			move_uploaded_file($image['tmp_name'], $this->root_dir.$this->config->model_images_dir.$image['name']);
  	    			$this->model->update_model($brand->id, array('image'=>$image['name']));
  	    		}
	  			$brand = $this->model->get_model($brand->id);
			}
		}
		else
		{
			$brand->id = $this->request->get('id', 'integer');
			$brand = $this->model->get_model($brand->id);
		}
		
		if(!$brand) $brand = new stdClass;
		if($this->request->get('marka_id', 'integer') && empty($brand->id)) $brand->marka_id = $this->request->get('marka_id', 'integer');
		
		//print_r($brand);die;
		
		$markas = $this->marka->get_brands();
		$this->design->assign('markas', $markas);
		
 		$this->design->assign('brand', $brand);
		return  $this->design->fetch('model.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);
	}
}