<?PHP

require_once('api/Simpla.php');

class ArticleAdmin extends Simpla
{
	private $allowed_image_extentions = array('png', 'gif', 'jpg', 'jpeg', 'ico');
	public function fetch()
	{
		$product_categories = array();
		$article = new StdClass;
		if($this->request->method('post'))
		{
			
			
			
			$article->id = $this->request->post('id', 'integer');
			$article->name = $this->request->post('name');
			$article->date = date('Y-m-d', strtotime($this->request->post('date')));

			$article->visible = $this->request->post('visible', 'boolean');

            $article->category_id = $this->request->post('category_id', 'integer');

			$article->url = $this->request->post('url', 'string');
			$article->meta_title = $this->request->post('meta_title');
			$article->meta_keywords = $this->request->post('meta_keywords');
			$article->meta_description = $this->request->post('meta_description');
			$article->annotation = $this->request->post('annotation');

			$article->text = $this->request->post('body');

			// Категории товара
			$article_categories = $this->request->post('categories');
			if(is_array($article_categories))
			{
				foreach($article_categories as $c)
					$pc[]->id = $c;
				$article_categories = $pc;
			}


            // Связанные товары
            if(is_array($this->request->post('related_products')))
            {
                foreach($this->request->post('related_products') as $p)
                {
                    $rp[$p]->related_id = $p;
                    $rp[$p]->type = 'product';
                }
                $related_objects = $rp;
            }

            // Связанные статьи
            if(is_array($this->request->post('related_articles')))
            {
                foreach($this->request->post('related_articles') as $p)
                {
                    $rp[$p]->related_id = $p;
                    $rp[$p]->type = 'article';
                }
                $related_objects = $rp;
            }

 			// Не допустить одинаковые URL разделов.
			if(($a = $this->articles->get_article($article->url)) && $a->id!=$article->id)
			{
				$this->design->assign('message_error', 'url_exists');
			}
			else
			{
				if(empty($article->id))
				{
	  				$article->id = $this->articles->add_article($article);
	  				$article = $this->articles->get_article($article->id);
					$this->design->assign('message_success', 'added');
	  			}
  	    		else
  	    		{
  	    			$this->articles->update_article($article->id, $article);
  	    			$article = $this->articles->get_article($article->id);
					$this->design->assign('message_success', 'updated');
  	    		}


				// Удаление изображения
				if($this->request->post('delete_image'))
				{
					$this->articles->delete_image($article->id);
				}
				// Загрузка изображения
				$image = $this->request->files('image');
				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_image($article->id);
							$this->articles->update_article($article->id, array('image'=>$image_name));
							$article->image =$image_name;
					}
					else
					{
						$this->design->assign('error', 'error uploading image');
					}	
				}	


			}

            // Связанные объекты
            $query = $this->db->placehold('DELETE FROM __article_objects WHERE article_id=?', $article->id);
            $this->db->query($query);
            if(is_array($related_objects))
            {
              $pos = 0;
              foreach($related_objects  as $i=>$related_object)
                   $this->articles->add_related_object($article->id, $related_object->related_id, $related_object->type);
            }

			// Категории товара
			$query = $this->db->placehold('DELETE FROM __articles_categories WHERE article_id=?', $article->id);
			$this->db->query($query);
			if(is_array($article_categories))
			{
				foreach($article_categories as $i=>$category)
					$this->articles->add_article_category($article->id, $category->id, $i);
			}
			
			$this->db->query('DELETE FROM __article_models WHERE article_id=' . (int)$article->id);
			$this->db->query('DELETE FROM __article_pages WHERE article_id=' . (int)$article->id);
			$related_markas = $this->request->post('related_markas');
			$related_models = $this->request->post('related_models');
			$related_pages = $this->request->post('related_pages');
			
			if($related_markas){
				foreach($related_markas as $id) $this->db->query('INSERT INTO __article_models SET article_id=' . (int)$article->id . ", marka_id=".(int)$id.", model_id=0");
			}
			if($related_models){
				
				foreach($related_models as $id){
					$model = $this->model->get_model( (int)$id );
					$this->db->query('INSERT INTO __article_models SET article_id=' . (int)$article->id . ", marka_id=".$model->marka->id.", model_id=" . $id);
				} 
			}
			if($related_pages){
				foreach($related_pages as $id) $this->db->query('INSERT INTO __article_pages SET article_id=' . (int)$article->id . ", page_id=".(int)$id);
			}
			
			
		}
		else
		{
			$article->id = $this->request->get('id', 'integer');
			$article = $this->articles->get_article(intval($article->id));
		}
		
		
		
		if(!$article->id) $article->visible = 1;

		if(empty($article->date)) $article->date = date($this->settings->date_format, time());
		

		$this->design->assign('related_markas', $this->articles->get_related_markas($article->id) );
		$this->design->assign('related_pages', $this->articles->get_related_pages($article->id) );
		
		$related_models = $this->articles->get_related_models($article->id);
		foreach($related_models as $row){
			$marka = $this->marka->get_brand((int)$row->marka_id);
			if($marka) $row->name = $marka->name . ' - ' . $row->name;
		}
		$this->design->assign('related_models', $related_models );
		

        // Связанные объекты
        $related_objects = $this->articles->get_related_objects(array('id'=>$article->id));
        if(!empty($related_objects))
        {
            $r_products = array();
            $r_articles = array();

            foreach($related_objects as &$r_p)
                if($r_p->type == 'product') $r_products[$r_p->object_id] = &$r_p;
                elseif($r_p->type == 'article') $r_articles[$r_p->object_id] = &$r_p;

            if(!empty($r_products)) {
                $temp_products = $this->products->get_products(array('id'=>array_keys($r_products)));
                foreach($temp_products as $temp_product)
                    $r_products[$temp_product->id] = $temp_product;
            }

            if(!empty($r_articles)) {
                $temp_articles = $this->articles->get_articles(array('id'=>array_keys($r_articles)));
                foreach($temp_articles as $temp_article)
                    $r_articles[$temp_article->id] = $temp_article;
            }

            $this->design->assign('related_products', $r_products);
            $this->design->assign('related_articles', $r_articles);
        }
		// Категории товара
		$article_categories = $this->articles->get_articles_categories_filter(array('article_id'=>/*mt1sk*//*$article->id*/(isset($article->id)) ? $article->id : -1/*/mt1sk*/));

		$article->firstCategory = $article_categories ? reset($article_categories) : 0;
		if(empty($article_categories))
		{
			if($category_id = $this->request->get('category_id'))
				$article_categories[0]->id = $category_id;		
			else
				$article_categories = array(1);
		}

        $this->design->assign('article_categories', $article_categories);
		
		
        $categories = $this->articles->get_categories_tree();
        $this->design->assign('categories', $categories);
        $this->design->assign('article', $article);
        
        
        $this->db->query("SELECT * FROM __article_photo WHERE article_id='" . $article->id . "' ORDER BY position, id DESC");
        $photos = $this->db->results();
        foreach($photos as $ph) $ph->img = Img::get('/files/article_photo/' . $ph->img,  array('width'=>120, 'height'=>120));
        $this->design->assign('article_photos', $photos);
        
        
        //print_r($photos);die;
        

 	  	return $this->design->fetch('article.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);
	}
}