<?PHP
//die;
/**
 * Simpla CMS
 *
 * @copyright    2011 Denis Pikusov
 * @link        http://simplacms.ru
 * @author        Denis Pikusov
 *
 * Этот класс использует шаблон page.tpl
 *    header("HTTP/1.0 404 Not Found");
 * header("Status: 404 Not Found");
 * Header( "Location: /404.php" );
 * exit;
 */
require_once('View.php');

class PageView extends View
{
    function fetch()
    {
        $url = $this->request->get('page_url', 'string');
        $page = $this->pages->get_page($url);

        // Отображать скрытые страницы только админу
        if (empty($page) || (!$page->visible && empty($_SESSION['admin'])))
            return false;

        $urlNow = $page->parentUrl . $url . '/';
        if (isset($_GET['page']) && $_GET['page']) $urlNow .= 'page-' . $_GET['page'] . '/';
        $requestUri = explode('?', $_SERVER['REQUEST_URI']);

        if ($urlNow != $requestUri[0] && $urlNow != '/tuning-centr/tuning-centr/') {
            if ($urlNow != '/404/')
                header('HTTP/1.1 301 Moved Permanently');
            else {
                header("HTTP/1.0 404 Not Found");
                header("Status: 404 Not Found");
            }
            header('Location: ' . $urlNow);
        }

        if (!empty($_COOKIE['stat_hash'])) {
            $u = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
            $this->pages->db->query("SELECT * FROM __visited WHERE stat_hash = '" . $_COOKIE['stat_hash'] . "' AND url_hash = '" . md5($u) . "' LIMIT 1");
            if (!$this->pages->db->num_rows()) {
                $this->pages->db->query("INSERT INTO __visited SET 
					url = '$u',
					url_hash = '" . md5($u) . "',
					stat_hash = '" . $_COOKIE['stat_hash'] . "',
					date = NOW()
				");

                $page->visited++;
                $update_visited->visited = $page->visited;
                $this->pages->update_page($page->id, $update_visited);

            }
        }


        $filter['show_home'] = 1;
        $items = $this->pages->get_pages($filter);

        foreach ($items as $item) {
            $startPage = $this->pages->getStartPage($item->parent, 28);
            $item->startId = $startPage->id;
        }

        $this->design->assign('service_items_start', (object)$service_items_start);
        $this->design->assign('service_items', $items);


        $sfilter['show_service'] = 1;
        $services = $this->pages->get_pages($sfilter);
        foreach ($services as $item) {
            $startPage = $this->pages->getStartPage($item->parent, 28);
            $item->startId = $startPage->id;
        }
        $this->design->assign('just_service_items', $services);

        ob_start();
        $this->getSubServices(28, $page->id);
        $service_menu = ob_get_clean();
        $this->design->assign('service_menu', $service_menu);    //echo $service_menu;die;

        // Отображать скрытые страницы только админу
        if (empty($page) || (!$page->visible && empty($_SESSION['admin'])))
            return false;


        // Вложеные страницы
        $sub_pages = $this->pages->get_pages(array('parent' => $page->id));
        $this->design->assign('sub_pages', $sub_pages);

        // хлебные крошки
        $breadcrumb = $this->pages->get_breadcrumb($page->id);
        $this->design->assign('breadcrumb', $breadcrumb);

        $page->body = preg_replace_callback('~<img.*class=.*zooming2[^>]*>~Uis', array($this, 'resizeBodyImages'), $page->body);
        $page->body = $this->setPageGalleries($page->body);

        $this->design->assign('page', $page);


        $this->design->assign('meta_title', $page->meta_title ?: $page->name);
        $this->design->assign('meta_keywords', $page->meta_keywords);
        $this->design->assign('meta_description', $page->meta_description);

        /////////////////////////////////// sitemap //
        if ($url == 'sitemap') {
            ob_start();
            //$this->pages->db->query("SELECT url,name FROM __pages WHERE menu_id=1 AND visible=1 ORDER BY position");
            $this->pages->db->query("SELECT id,url,name FROM __pages WHERE parent=0 AND visible=1 ORDER BY name");
            echo '<ul>';
            foreach ($this->pages->db->results() as $row) {
                if ($row->id == 5 || $row->id == 182) continue;
                if ($row->url == 'aktsii') $row->url = 'actions';
                $url = $row->url ? '/' . $row->url . '/' : '/';
                echo '<li><a href="' . $url . '">' . $row->name . '</a>';
                echo '</li>';
            }
            echo '</ul>';

            echo '<div class="row"><div class="col-md-6">';
            echo '<div class="title" data-page="5">Каталог продукции</div>';
            $this->getCats();
            echo '</div>';

            echo '<div class="col-md-6"><div class="title">Услуги тюнинг центра</div>';
            $this->getServices();
            echo '</div></div>';


            $page->body .= ob_get_clean();

        }
        /////////////////////////////////// end sitemap //
        /////////////////////////////////// otzyvy //

        if ($url == 'otzyvy') {


            if (strpos($_SERVER['REQUEST_URI'], '?page=') !== false) {
                Header("HTTP/1.1 301 Moved Permanently");
                $url = $_GET['page'] != 1 ? 'page-' . $_GET['page'] . '/' : '';
                $u = explode('?', $_SERVER['REQUEST_URI']);
                Header("Location: " . $u[0] . $url);
                die;
            }

            //require_once ($_SERVER['DOCUMENT_ROOT'] . '/feedback/Img.php');

            $limit = 0;
            if (isset($_GET['page'])) $limit = ($_GET['page'] - 1) * 10;

            $sql = (!empty($_SESSION['admin'])) ? "SELECT * FROM `__feedback` WHERE `parent_id`=0 ORDER BY `id` DESC LIMIT " . $limit . ',10' : "SELECT * FROM `__feedback` WHERE `active`=1 AND `parent_id`=0 ORDER BY `id` DESC LIMIT " . $limit . ',10';

            $this->pages->db->query($sql);
            $feedback = $ids = array();
            foreach ($this->pages->db->results() as $row) {
                $row->style = (!empty($_SESSION['admin']) && !$row->active) ? 'feedback_not' : '';
                $feedback[] = $row;
                $ids[] = $row->id;
            }

            $this->pages->db->query("SELECT * FROM `__feedback` WHERE `parent_id` IN(" . implode(',', $ids) . ") ORDER BY `id` ");
            $feedback_replies = array();
            foreach ($this->pages->db->results() as $row) {
                $ids[] = $row->id;
                $feedback_replies[$row->parent_id] = $row;
            }

            $this->pages->db->query("SELECT * FROM `__feedback_images` WHERE `feedback_id` IN(" . implode(',', $ids) . ") ORDER BY `id` ");
            $feedback_imgs = array();
            foreach ($this->pages->db->results() as $row) {
                if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/feedback/images/' . $row->name))
                    continue;
                $row->img = Img::get('/feedback/images/' . $row->name, array('width' => 112, 'height' => 112));
                if (!isset($feedback_imgs[$row->feedback_id]))
                    $feedback_imgs[$row->feedback_id] = array();
                $feedback_imgs[$row->feedback_id][] = $row;
            }

            $this->design->assign('feedback', $feedback);
            $this->design->assign('feedback_replies', $feedback_replies);
            $this->design->assign('feedback_imgs', $feedback_imgs);

            if (isset($_GET['edit']) || isset($_GET['reply'])) {
                $fid = isset($_GET['edit']) ? $_GET['edit'] : $_GET['reply'];
                $this->pages->db->query("SELECT * FROM `__feedback` WHERE `id` = '" . (int)$fid . "' ");
                $this->design->assign('feed_row', $this->pages->db->result());
            }

            /// paginator
            $sql = (!empty($_SESSION['admin'])) ? "SELECT * FROM `__feedback` WHERE `parent_id`=0" : "SELECT * FROM `__feedback` WHERE `active`=1 AND `parent_id`=0";
            $this->pages->db->query($sql);
            $tpn = ceil($this->pages->db->num_rows() / 10);
            $this->design->assign('total_pages_num', $tpn);
            $p = isset($_GET['page']) ? $_GET['page'] : 1;
            $this->design->assign('current_page_num', $p);
            if (isset($_GET['page'])) {
                $page->header .= ' - страница ' . $p;
                $page->body = '';
                $this->design->assign('page', $page);
            }
        }
        /////////////////////////////////// end otzyvy //


        // Связанные объекты
        $related_objects = $this->pages->get_related_objects(array('id' => $page->id));
        if (!empty($related_objects)) {
            $r_products = array();
            $r_pages = 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 == 'page')
                    $r_pages[$r_p->object_id] = &$r_p;
                elseif ($r_p->type == 'article')
                    $r_articles[$r_p->object_id] = &$r_p;

            if (!empty($r_products)) {

                //echo '<!-- @@@1'; print_r($r_products); echo '-->';

                // foreach($this->products->get_products(array('id'=>array_keys($r_products), 'in_stock'=>1, 'visible'=>1)) as $p)
                foreach ($this->products->get_products(array('id' => array_keys($r_products), 'visible' => 1)) as $p)
                    $r_products[$p->id] = $p;

                //echo '<!-- @@@2'; print_r($r_products); echo '-->';

                $r_products_images = $this->products->get_images(array('product_id' => array_keys($r_products)));
                foreach ($r_products_images as $related_product_image)
                    if (isset($r_products[$related_product_image->product_id]))
                        $r_products[$related_product_image->product_id]->images[] = $related_product_image;

                $r_products_variants = $this->variants->get_variants(array('product_id' => array_keys($r_products), 'instock' => true));
                foreach ($r_products_variants as $related_product_variant) {
                    if (isset($r_products[$related_product_variant->product_id])) {
                        $r_products[$related_product_variant->product_id]->variants[] = $related_product_variant;
                    }
                }

                foreach ($r_products as $id => $r) {
                    if (is_object($r)) {
                        $r->image = &$r->images[0];
                        $r->variant = &$r->variants[0];
                    } else {
                        unset($r_products[$id]);
                    }
                }

            }

            if (!empty($r_pages)) {
                $temp_pages = $this->pages->get_pages(array('id' => array_keys($r_pages)));
                foreach ($temp_pages as $temp_page)
                    $r_pages[$temp_page->id] = $temp_page;
            }

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

            $this->design->assign('related_products', $r_products);
            $this->design->assign('related_pages', $r_pages);
            $this->design->assign('related_articles', $r_articles);
        }

        if ($url == 'catalog') {
            $catalog_categories = array();
            $this->pages->db->query("SELECT * FROM __categories WHERE visible=1 AND parent_id=0 ORDER BY position,name");
            foreach ($this->pages->db->results() as $row) {
                if (!$row->image) $row->image = 'empty2.jpg';
                $catalog_categories[] = $row;
            }
            $this->design->assign('catalog_categories', $catalog_categories);
        }

        $show_catalog_link = 0;

        if (strpos($_SERVER['REQUEST_URI'], '/uslugi/') === 0) $show_catalog_link = 1;
        $this->design->assign('show_catalog_link', $show_catalog_link);

        return $this->design->fetch('page.tpl');
    }

    function getServices($parent_id = 28)
    {
        $this->pages->db->query("SELECT url,name,id FROM __pages WHERE visible=1 AND parent=" . $parent_id . " ORDER BY position");
        if (!$this->pages->db->num_rows()) return;
        echo '<ul>';
        foreach ($this->pages->db->results() as $row) {
            echo '<li><a href="/tuning-centr/' . $row->url . '/">' . $row->name . '</a>' . "\n";
            $this->getServices($row->id);
            echo '</li>';
        }
        echo '</ul>' . "\n";
    }

    function getSubServices($parent_id, $page_id, $level = 0)
    {

        $this->pages->db->query("SELECT url,name,id FROM __pages WHERE visible=1 AND parent=" . $parent_id . " ORDER BY position");
        if (!$this->pages->db->num_rows()) return;
        echo '<ul data-t="y">';
        foreach ($this->pages->db->results() as $row) {

            if ($row->id == $page_id) {
                $active = ' class="active" ';
            } else {
                $active = '';
            }

            echo '<li ' . $active . ' ><a href="/tuning-centr/' . $row->url . '/">' . $row->name . '</a>';
            if ($parent_id == $page_id or $level == 0) {
                $this->getSubServices($row->id, $page_id, $level);
            }
            echo '</li>';
        }
        $level++;
        echo '</ul>';
    }

    function setPageGalleries($text)
    {
        $text = preg_replace_callback('~\{gallery([ ]+)id=([0-9]+)\}~Uis', array($this, '_setPageGalleries'), $text);
        if (strpos($text, 'flexslider-gallery')) {
            $text .= '<script> $(document).ready(function(){
			$(".flexslider-gallery").bxSlider({
					slideWidth: 210,
					//minSlides: 2,
					maxSlides: 6,
					slideMargin: 5,
					pager: false
				});
			}); </script>';
        }
        //echo $text; die;


        return $text;
    }

    function resizeBodyImages($m)
    {
        preg_match('~src=["\'](.*)["\']~Uis', $m[0], $img);
        if (empty($img[1])) return $m[0];
        preg_match('~title=["\'](.*)["\']~Uis', $m[0], $title);
        preg_match('~alt=["\'](.*)["\']~Uis', $m[0], $alt);

        $alt = isset($alt[1]) ? $alt[1] : '';
        $title = isset($title[1]) ? $title[1] : '';

        $src = Img::get(urldecode($img[1]), array('width' => 400, 'height' => 300, 'crop' => true));
        $tl = $title ? '<div class="zooming2-title">' . $title . '</div>' : '';
        return '<div class="col-sm-6 mb">' . $tl . '<img alt="' . $alt . '" class="zooming2 zooming-ready" src="' . $src . '" title="' . $title . '"></div>' . "\n";
    }

    function _setPageGalleries($m)
    { // return '';
        if (empty($m[2])) return '';
        $this->db->query("SELECT * FROM s_banners WHERE `visible`=1 AND `id_group` = ? ORDER BY `position`", (int)$m[2]);
        $banners = $this->db->results();
        if (!$banners) return '';
        $out = '<div class="flexslider-gallery">';
        foreach ($banners as $row) {
            $width = 210;
            $height = 150;
            $src = Img::get('files/banners/' . $row->image, array('width' => 210, 'height' => 150));
            /*$src = $this->image->add_resize_params('/files/banners/'.$row->image , $width, $height, false);
            if(!is_file($_SERVER['DOCUMENT_ROOT'].$src)){
                   $this->image->image_constrain_gd($_SERVER['DOCUMENT_ROOT'].'/files/banners/'.$row->image, $_SERVER['DOCUMENT_ROOT'].$src, $width, $height);
            }*/
            $out .= '<div class="slide"><a class="fancybox" href="/files/banners/' . $row->image . '" rel="page-gallery-' . $m[2] . '"><img src="' . $src . '"></a></div>';
        }
        return $out .= '</div>';
    }

    function getCats($parent_id = 0)
    {
        $this->pages->db->query("SELECT url, name, id FROM __categories WHERE visible=1 AND parent_id=" . $parent_id . " ORDER BY name");
        if (!$this->pages->db->num_rows())
            return;
        echo '<ul>';
        foreach ($this->pages->db->results() as $row) {
            echo '<li><a href="/catalog/' . $row->url . '/">' . $row->name . '</a>';
            $this->getCats($row->id);
            echo '</li>';
        }
        echo '</ul>';
    }


}


