<?php
/**
 * Simpla CMS
 *
 * @copyright	2011 Denis Pikusov
 * @link		http://simplacms.ru
 * @author		Denis Pikusov
 *
 */
require_once ('Simpla.php');
class Pages extends Simpla {
    /*
    *
    * Функция возвращает страницу по ее id или url (в зависимости от типа)
    * @param $id id или url страницы
    *
    */
    public function get_page($id, $menu_to_omit = []) {
        $menu_condition = '';
        if (!empty($menu_to_omit)) {
            $menu_condition .= 'menu_id NOT IN ('. implode(',', $menu_to_omit) . ') AND';
        }

        if (gettype($id) == 'string')
            $where = $this->db->placehold(' WHERE '. $menu_condition . 'url=? ', $id);
        else
            $where = $this->db->placehold(' WHERE '. $menu_condition . 'id=? ', intval($id));

        $query = "SELECT * FROM __pages $where LIMIT 1";
        $this->db->query($query);
        $page = $this->db->result();

        if ($page->name) {

            $parentUrl = $this->get_parent_url($page->parent);

            if ($parentUrl != '/')
                $page->parentUrl = '/' . $parentUrl;
            else
                $page->parentUrl = $parentUrl;
        }

        if(strpos($_SERVER['REQUEST_URI'], '/uslugi/') !== false) $page->parentUrl = '/uslugi/';
        if(strpos($_SERVER['REQUEST_URI'], '/tuning-centr/') !== false) $page->parentUrl = '/tuning-centr/';


        return $page;
    }

    /*
    *
    * Функция возвращает id страницы
    *
    */    
    public function get_page_id($alias) {
        $where = $this->db->placehold(' WHERE url=? ', $alias);
        $query = "SELECT id FROM __pages $where LIMIT 1";
        $this->db->query($query);
        $page = $this->db->result();
        return $page->id;
    }
    
    function getStartPage($id, $topParentId = 0){
    	$id = (int)$id;
    	$page = $this->get_page($id);
    	return ($page->parent == $topParentId || !$page->parent) ? $page : $this->getStartPage($page->parent, $topParentId);
    }
    
    /*
    *
    * Функция возвращает массив страниц, удовлетворяющих фильтру
    * @param $filter
    *
    */
    public function get_pages($filter = array()) {
        $menu_filter = '';
        $visible_filter = $keyword_filter = '';
        $pages = array();
        if (isset($filter['id']))
            $menu_filter = $this->db->placehold('AND id in (?@)', (array )$filter['id']);      
        if (isset($filter['parent']))
            $menu_filter = $this->db->placehold('AND parent in (?@)', (array )$filter['parent']);
        if (isset($filter['menu_id']))
            $menu_filter = $this->db->placehold('AND menu_id in (?@)', (array )$filter['menu_id']);
        if (isset($filter['visible']))
            $visible_filter = $this->db->placehold('AND visible = ?', intval($filter['visible']));
        if (isset($filter['show_home']))
            $visible_filter = $this->db->placehold('AND show_home = ?', intval($filter['show_home']));  

        if (isset($filter['show_service']))
            $visible_filter = $this->db->placehold('AND show_service = ?', intval($filter['show_service'])); 
		
		if(isset($filter['keyword']))
		{
			$keywords = explode(' ', $filter['keyword']);
			foreach($keywords as $keyword)
				$keyword_filter .= $this->db->placehold('AND (name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR meta_keywords LIKE "%'.mysql_real_escape_string(trim($keyword)).'%") ');
		}
			          
        $query = "SELECT id, parent, url, header, name, meta_title, meta_description, meta_keywords, image, introtext, toptext, body, bottext, menu_id, position, visible, show_home 
		          FROM __pages WHERE 1 $menu_filter $visible_filter $keyword_filter ORDER BY position";                                                       
          //echo($query) . '<hr>';        
        $this->db->query($query);
        foreach ($this->db->results() as $page) {  
            
            if ($page->name) {
            
                $parentUrl = $this->get_parent_url($page->parent);
                      
                if ($parentUrl != '/')
                    $page->parentUrl = '/' . $parentUrl;
                else 
                    $page->parentUrl = $parentUrl;
                
            }
                 
			if(strpos($_SERVER['REQUEST_URI'], '/uslugi/') !== false) $page->parentUrl = '/uslugi/';
			if(strpos($_SERVER['REQUEST_URI'], '/tuning-centr/') !== false) $page->parentUrl = '/tuning-centr/';	 
			//$page->parentUrl = '';                 
            $pages[$page->id] = $page;                                                           
        }            
        return $pages;
    }
    
    public function get_parent_url($id, $url = '') {  
    	//if(strpos($_SERVER['REQUEST_URI'], '/tuning-centr/') !== false) return '/tuning-centr/';
        if (!$id) return;
        $id = intval($id);
        $page = $this->get_page($id);
        $url = $page->url . '/' . $url;
        
        if ($page->parent > 0)
            return $this->get_parent_url($page->parent, $url);
         else
            return $url;
    }
    
    public function get_breadcrumb($id, $breadcrumb = array()) {                  
        if (!$id) return;
        $id = intval($id);
        $page = $this->get_page($id);                                
        $breadcrumb[] = new ArrayObj(array('anchor' => $page->header, 'href' => $this->get_parent_url($page->id)));     
        if ($page->parent > 0)
            return $this->get_breadcrumb($page->parent, $breadcrumb);
         else {
            $result = array_reverse($breadcrumb);
            $lastResult = array_pop($result);
            return new ArrayObj($result);
         }
    }
	
	public function get_breadcrumb_service($id, $breadcrumb = array()) {                  
        if (!$id) return;
        $id = intval($id);
        $page = $this->get_page($id);    //echo '<!-- 999999'; print_r($page);    echo '-->';                        
        //$breadcrumb[] = new ArrayObj(array('anchor' => $page->name, 'href' => $this->get_parent_url($page->id)));   
        
        $href = $page->url != 'tuning-centr' ? 'tuning-centr/' . $page->url . '/' : 'tuning-centr/';
        
		$breadcrumb[] = new ArrayObj(array('anchor' => $page->name, 'href' => $href  ));   
        if ($page->parent > 0)
            return $this->get_breadcrumb_service($page->parent, $breadcrumb);
         else {
            $result = array_reverse($breadcrumb);
            $lastResult = array_pop($result);
            return new ArrayObj($result);
         }
    }
	   
    
    
    /*
    *
    * Функция возвращает массив id => name для выбора родительского раздела в админке
    *
    */      
    public function get_select_pages($filter = array(), $pages = array(), $del = '') {
        $menu_filter = '';
        $visible_filter = '';
        //$pages = array();
        if (isset($filter['parent']))
            $menu_filter = $this->db->placehold('AND parent in (?@)', (array )$filter['parent']);
        if (isset($filter['menu_id']))
            $menu_filter = $this->db->placehold('AND menu_id in (?@)', (array )$filter['menu_id']);
        if (isset($filter['visible']))
            $visible_filter = $this->db->placehold('AND visible = ?', intval($filter['visible'])); 
        if (isset($filter['show_home']))
            $visible_filter = $this->db->placehold('AND show_home = ?', intval($filter['show_home']));                       
        $query = "SELECT id, name FROM __pages WHERE 1 $menu_filter $visible_filter ORDER BY id"; //echo $query;
        $this->db->query($query);

        foreach ($this->db->results() as $page){
        	$page->name = $del . $page->name;
        	$pages[$page->id] = $page;
        	$filter2 = $filter;
        	$filter2['parent'] = array($page->id);
        	$pages = $this->get_select_pages($filter2, $pages, $del . '--');
        }

            
        return $pages;
    }
    /*
    *
    * Создание страницы
    *
    */
    public function add_page($page) {
        $query = $this->db->placehold('INSERT INTO __pages SET ?%', $page);
        if (!$this->db->query($query))
            return false;
        $id = $this->db->insert_id();
        $this->db->query("UPDATE __pages SET position=id WHERE id=?", $id);
        return $id;
    }
    /*
    *
    * Обновить страницу
    *
    */
    public function update_page($id, $page) {
        $query = $this->db->placehold('UPDATE __pages SET ?% WHERE id in (?@)', $page, (array )$id);
        if (!$this->db->query($query))
            return false;
        return $id;
    }
    /*
    *
    * Удалить страницу
    *
    */
    public function delete_page($id) {
        if (!empty($id)) {
            $query = $this->db->placehold("DELETE FROM __pages WHERE id=? LIMIT 1", intval($id));
            if ($this->db->query($query))
                return true;
        }
        return false;
    }
    public function delete_image($id) {
        $query = $this->db->placehold("SELECT image FROM __pages WHERE id=?", intval($id));
        $this->db->query($query);
        $filename = $this->db->result('image');
        if (!empty($filename)) {
            $query = $this->db->placehold("UPDATE __pages SET image=NULL WHERE id=?", $id);
            $this->db->query($query);
            $query = $this->db->placehold("SELECT count(*) as count FROM __pages WHERE image=? LIMIT 1", $filename);
            $this->db->query($query);
            $count = $this->db->result('count');
            if ($count == 0) {
                @unlink($this->config->root_dir . $this->config->original_images_dir . $filename);
            }
        }
    }
    /*
    *
    * Функция возвращает массив меню
    *
    */
    public function get_menus() {
        $menus = array();
        $query = "SELECT * FROM __menu ORDER BY position";
        $this->db->query($query);
        foreach ($this->db->results() as $menu)
            $menus[$menu->id] = $menu;
        return $menus;
    }
    /*
    *
    * Функция возвращает меню по id
    * @param $id
    *
    */
    public function get_menu($menu_id) {
        $query = $this->db->placehold("SELECT * FROM __menu WHERE id=? LIMIT 1", intval($menu_id));
        $this->db->query($query);
        return $this->db->result();
    }
    
    ////////////////////////////////////////////////////
    
    function get_related_objects($page_id = array())
    {
        if(empty($page_id))
            return array();

        $query = $this->db->placehold("SELECT page_id, object_id, type
                    FROM __pages_objects
                    WHERE page_id in(?@)", (array)$page_id);
        $this->db->query($query);
        return $this->db->results();
    }
    


    public function add_related_object($page_id, $related_id, $type)
    {
        $query = $this->db->placehold("INSERT IGNORE INTO __pages_objects SET page_id=?, object_id=?, type=?", $page_id, $related_id, $type);
        $this->db->query($query);
        return $related_id;
    }

    public function delete_related_object($page_id, $related_id)
    {
        $query = $this->db->placehold("DELETE FROM __pages_objects WHERE page_id=? AND object_id=? LIMIT 1", intval($page_id), intval($related_id));
        $this->db->query($query);
    }   
	
	
	
	
	function get_related_articles($page_id = array())
    {
        if(empty($page_id))
            return array();

        $query = $this->db->placehold("SELECT *
                    FROM __related_articles
                    WHERE page_id in(?@)", (array)$page_id);
        $this->db->query($query);
        return $this->db->results();
    }
    
    public function add_related_article($page_id, $article_id)
    {
        $query = $this->db->placehold("INSERT IGNORE INTO __related_articles SET page_id=?, article_id=?", $page_id, $article_id);
        $this->db->query($query);
        return $article_id;
    }

    public function delete_related_article($page_id, $article_id)
    {
        $query = $this->db->placehold("DELETE FROM __related_articles WHERE page_id=? AND article_id=? LIMIT 1", intval($page_id), intval($article_id));
        $this->db->query($query);
    }  
    
    
    
}

class ArrayObj extends stdClass {
    function __construct($array = array()) {
        if (is_array($array))
            foreach ($array as $k => $v) $this->$k = $v;
    }
}