<?php

require_once('View.php');

class ServiceView extends View
{
    function fetch()
    {
        // обрабатываем url
        $url = $this->request->get('page_url');
        if (strpos($url, '?') > 0)
            $url = substr($url, 0, strpos($url, '?'));
        $url = trim($url, '/');

        // получаем страницу
        $page = $this->services->get($url);
        if (empty($page))
            return false;

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

        // обновляем счётчик посещения страницы
        $this->update_visited($page->id, $page->visited);

        // zoom изображений
        $page->body = preg_replace_callback('~<img.*class=.*zooming2[^>]*>~Uis', array($this, 'resizeBodyImages'), $page->body);
        // Обрабатываем галереи на странице
        $page->body = $this->setPageGalleries($page->body);

        // Главная ли это страница услуг
        $is_main_page = $this->services->root_id === intval($page->id);
        $this->design->assign('is_main_page', $is_main_page);

        if ($is_main_page) {
            //услуги главной страница
            $this->design->assign('home_services', $this->services->get_home_services(true, true));
        } elseif ($this->services->has_children($page->id)) {
            // Вложенные страницы услуги, кроме брендовых
            $this->design->assign('sub_pages', $this->services->all(array(
                'parent' => $page->id, 'brand_id' => 0, 'visible' => 1
            )));
        }

        // для небрендовых услуг получаем привязанные брендовые страницы
        if (!$is_main_page && !$page->brand_id) {
            $brands = array();
            $brands_pages = $this->services->get_brands_pages($page->id, ['visible' => 1]);
            //брендовые страницы существуют, нужно выводить блок услуги по брендам, готовим данные
            if (!empty($brands_pages)) {
                $active_ids = array();
                foreach ($brands_pages as $bp)
                    $active_ids[$bp->brand_id] = $bp;

                $brands = $this->services->get_all_brands(); //все бренды
                foreach ($brands as $brand) {
                    if (array_key_exists($brand->id, $active_ids)) {
                        $brand->url = $active_ids[$brand->id]->url;
                        $brand->page_id = $active_ids[$brand->id]->id;
                    } else {
                        unset($brand->url);
                    }
                }
            }
            $this->design->assign('service_brands', $brands);
        }

        // Хлебные крошки
        if ($page->brand_id) {
            $breadcrumbs = $this->services->get_path_to($page->parent);
            $breadcrumbs[] = $page;
        } else {
            $breadcrumbs = $this->services->get_path_to($page->id);
        }
        $this->design->assign('breadcrumbs', $breadcrumbs);

        // Связанные со страницей объекты
        $this->assign_related($page->id);

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

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

    private function assign_related($page_id)
    {
        // Связанные объекты
        $related_objects = $this->pages->get_related_objects(array('id' => $page_id));
        if (empty($related_objects))
            return;

        $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)) {
            foreach ($this->products->get_products(array('id' => array_keys($r_products), 'visible' => 1)) as $p)
                $r_products[$p->id] = $p;
            $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);
    }

    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>';
        }
        return $text;
    }

    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));
            $out .= '<div class="slide"><a class="fancybox" href="/files/banners/' . $row->image . '" rel="page-gallery-' . $m[2] . '"><img src="' . $src . '"></a></div>';
        }
        $out .= '</div>';
        return $out;
    }

    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";
    }



    private function update_visited($page_id, $current_count)
    {
        if (empty($_SESSION['admin']) && !empty($_COOKIE['stat_hash'])) {
            $u = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
            $this->db->query("SELECT * FROM __visited WHERE stat_hash = '" . $_COOKIE['stat_hash'] . "' AND url_hash = '" . md5($u) . "' LIMIT 1");

            if (!$this->db->num_rows()) {
                $this->db->query("INSERT INTO __visited SET 
					url = '$u',
					url_hash = '" . md5($u) . "',
					stat_hash = '" . $_COOKIE['stat_hash'] . "',
					date = NOW()
				");

                $this->pages->update_page($page_id, array('visited' => ++$current_count));
            }
        }
    }
}