<?PHP

/**
 * Simpla CMS
 *
 * @copyright   2011 Denis Pikusov
 * @link        http://simplacms.ru
 * @author      Denis Pikusov
 *
 * Этот класс использует шаблон product.tpl
 *
 */

require_once('View.php');
include $_SERVER['DOCUMENT_ROOT'] . '/modal-form/cp.php';


class ProductView extends View
{

    function fetch()
    {

        require_once($_SERVER['DOCUMENT_ROOT'] . '/mobiledetect/Mobile_Detect.php');
        $detect = new Mobile_Detect;
        $this->design->assign('detect', $detect);

        //print_r($_SESSION);die;
        $product_url = $this->request->get('product_url', 'string');

        //$this->design->assign('additional_title', ' Санкт-Петербурге');

        if(empty($product_url))
            return false;

        // Выбираем товар из базы
        $product = $this->products->get_product((string)$product_url);
        if(empty($product) || (!$product->visible && empty($_SESSION['admin'])))
            return false;

        if($product->visible && empty($_SESSION['admin']))
        $this->products->update_views($product->id);
        $product->images = $this->products->get_images(array('product_id'=>$product->id));
        $product->image = &$product->images[0];

        $variants = array();
        //foreach($this->variants->get_variants(array('product_id'=>$product->id, 'in_stock'=>true)) as $v)
        foreach($this->variants->get_variants(array('product_id'=>$product->id)) as $v)
            $variants[$v->id] = $v;

        $product->variants = $variants;

        $featuresvars = array();
        $options2 = $this->features->get_product_variant_options($product->id);
        if(is_array($options2)){
            foreach($options2 as $option){
                $product->variants[$option->id_veriant]->options[$option->feature_id][] = $option;
                $featuresvars[$option->feature_id][] = $option->value;
            }
        }
        foreach($featuresvars AS $index=>$arr){
            sort($arr);
            $temp[$index] = array_unique($arr);
        }
        //$featuresvars = $temp;
        $featuresvars = $this->features->get_features(array('id'=>array_keys($featuresvars)));
        foreach($featuresvars AS &$featur){
            if($temp[$featur->id])
                $featur->options = $temp[$featur->id];
        }
        $this->design->assign('featuresvars', $featuresvars);
        //$this->design->assign('options2', $options2);


        // Вариант по умолчанию
        if(($v_id = $this->request->get('variant', 'integer'))>0 && isset($variants[$v_id]))
            $product->variant = $variants[$v_id];
        else
            $product->variant = reset($variants);

        $product->features = $this->features->get_product_options(array('product_id'=>$product->id,'on_prod'=>1));



        // Автозаполнение имени для формы комментария
        if(!empty($this->user))
            $this->design->assign('comment_name', $this->user->name);

        // Принимаем комментарий
        if ($this->request->method('post') && $this->request->post('comment'))
        {
            $comment->name = $this->request->post('name');
            $comment->text = $this->request->post('text');

            // Передадим комментарий обратно в шаблон - при ошибке нужно будет заполнить форму
            $this->design->assign('comment_text', $comment->text);
            $this->design->assign('comment_name', $comment->name);

            $cp = new ReCaptcha('6LegdywdAAAAAJaQLxIlHnITncRtuHQu-HHxeAYG');
            $cpResult = $cp->verifyResponse($_SERVER['REMOTE_ADDR'], $this->request->post('recaptcha_response'));
            if (!$cpResult->success) {
                $this->design->assign('error', 'recaptcha');
            }

            elseif (empty($comment->name))
            {
                $this->design->assign('error', 'empty_name');
            }
            elseif (empty($comment->text))
            {
                $this->design->assign('error', 'empty_comment');
            }
            else
            {
                // Создаем комментарий
                $comment->object_id = $product->id;
                $comment->type      = 'product';
                $comment->ip        = $_SERVER['REMOTE_ADDR'];

                // Если были одобренные комментарии от текущего ip, одобряем сразу
                $this->db->query("SELECT 1 FROM __comments WHERE approved=1 AND ip=? LIMIT 1", $comment->ip);
                if($this->db->num_rows()>0)
                    $comment->approved = 1;

                // Добавляем комментарий в базу
                if($this->request->post('email') == '' )
                    $comment_id = $this->comments->add_comment($comment);

                // Отправляем email
                $this->notify->email_comment_admin($comment_id);
                
                header('location: '.$_SERVER['REQUEST_URI'].'#comment_'.$comment_id);
            }
        }

        // Комментарии к товару
        $comments = $this->comments->get_comments(array('type'=>'product', 'object_id'=>$product->id, 'approved'=>1, 'ip'=>$_SERVER['REMOTE_ADDR']));
        $this->design->assign('comments', $comments);


        // Связанные товары
        $related_ids = array();
        $related_products = array();
        foreach($this->products->get_related_products($product->id) as $p)
        {
            $related_ids[] = $p->related_id;
            $related_products[$p->related_id] = null;
        }
        if(!empty($related_ids))
        {
            foreach($this->products->get_products(array('id'=>$related_ids, 'in_stock'=>1, 'visible'=>1)) as $p)
                $related_products[$p->id] = $p;

            $related_products_images = $this->products->get_images(array('product_id'=>array_keys($related_products)));
            foreach($related_products_images as $related_product_image)
                if(isset($related_products[$related_product_image->product_id]))
                    $related_products[$related_product_image->product_id]->images[] = $related_product_image;
            $related_products_variants = $this->variants->get_variants(array('product_id'=>array_keys($related_products), 'in_stock'=>1));
            foreach($related_products_variants as $related_product_variant)
            {
                if(isset($related_products[$related_product_variant->product_id]))
                {
                    $related_products[$related_product_variant->product_id]->variants[] = $related_product_variant;
                }
            }
            foreach($related_products as $id=>$r)
            {
                if(is_object($r))
                {
                    $r->image = &$r->images[0];
                    $r->variant = &$r->variants[0];
                }
                else
                {
                    unset($related_products[$id]);
                }
            }
            $this->design->assign('related_products', $related_products);
        }
        else {
    $products->categories = $this->categories->get_categories(array('product_id'=>$product->id));
    $category = reset($products->categories);

    $related_products = array();
    $after = false;

    $products = $this->products->get_products(array('category_id' => $category->id, 'limit' => 100, 'in_stock'=>1, 'visible'=>1));

    foreach($products as $p)
    {
        if($after && count($related_products) < 6)
            $related_products[$p->id] = $p;
        elseif($p->id == $product->id)
            $after = true;
    }

    if(count($related_products) < 6)
        foreach($products as $p)
            if($p->id != $product->id && count($related_products) < 6)
                $related_products[$p->id] = $p;
            else break;

    $related_products_images = $this->products->get_images(array('product_id'=>array_keys($related_products)));
    foreach($related_products_images as $related_product_image)
        if(isset($related_products[$related_product_image->product_id]))
            $related_products[$related_product_image->product_id]->images[] = $related_product_image;
    $related_products_variants = $this->variants->get_variants(array('product_id'=>array_keys($related_products), 'instock'=>true));
    foreach($related_products_variants as $related_product_variant)
    {
        if(isset($related_products[$related_product_variant->product_id]))
        {
            $related_product_variant->price *= (100-$discount)/100;
            $related_products[$related_product_variant->product_id]->variants[] = $related_product_variant;
        }
    }
    foreach($related_products as $r)
    {
        $r->image = &$r->images[0];
        $r->variant = &$r->variants[0];
    }
    $this->design->assign('related_products', $related_products);
}

        // Отзывы о товаре
        $comments = $this->comments->get_comments(array('type'=>'product', 'object_id'=>$product->id, 'approved'=>1, 'ip'=>$_SERVER['REMOTE_ADDR']));

        // Соседние товары
        $this->design->assign('next_product', $this->products->get_next_product($product->id));
        $this->design->assign('prev_product', $this->products->get_prev_product($product->id));

        // И передаем его в шаблон
        $this->design->assign('product', $product);
        $this->design->assign('comments', $comments);

        // Категория и бренд товара
        $product->categories = $this->categories->get_categories(array('product_id'=>$product->id));
        $this->design->assign('brand', $this->brands->get_brand(intval($product->brand_id)));
        $this->design->assign('category', reset($product->categories));
        // Категории товаров
        $this->design->assign('categories', $this->categories->get_categories_tree());



        // Добавление в историю просмотров товаров
        $max_visited_products = 100; // Максимальное число хранимых товаров в истории
        $expire = time()+60*60*24*30; // Время жизни - 30 дней
        if(!empty($_COOKIE['browsed_products']))
        {
            $browsed_products = explode(',', $_COOKIE['browsed_products']);
            // Удалим текущий товар, если он был
            if(($exists = array_search($product->id, $browsed_products)) !== false)
                unset($browsed_products[$exists]);
        }
        // Добавим текущий товар
        $browsed_products[] = $product->id;
        $cookie_val = implode(',', array_slice($browsed_products, -$max_visited_products, $max_visited_products));
        setcookie("browsed_products", $cookie_val, $expire, "/");


            // Связанные объекты
            $related_objects = $this->articles->get_related_articles(array('id'=>$product->id,'type'=>'product'));
            if(!empty($related_objects))
            {

            foreach($related_objects as $related_a)
                $r_articles[$related_a->article_id] = $related_a;
            $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_articles', $r_articles);
        }



    //  if(!$product->meta_keywords){
            $ssid = $this->categories->get_product_categories($product->id);
            $this->db->query("SELECT id, name FROM __categories WHERE id=?", $ssid[0]->category_id);
            $rows = $this->db->results();
            $cname = $rows[0]->name;
    //  }

    //  echo $rows[0]->id;
        /*
        if(!$product->meta_title && $rows[0]->id == 443) $product->meta_title = $product->name.' в' ;
        if(!$product->meta_keywords && $rows[0]->id == 443) $product->meta_keywords = $product->name.', для автомобиля, купить, цена, спб, установка, тюнинг, интернет-магазин carheart';
        if(!$product->meta_description && $rows[0]->id == 443) $product->meta_description = 'В продаже '.$product->name.' по выгодным ценам в Санкт-Петербурге | CarHeart - продажа товаров для тюнинга авто.';
        */

        $lowerName = htmlspecialchars(mb_strtolower($product->name, 'utf-8'));
        $minPrice = $this->getMinPrice($product->variants);

        if(!$product->meta_title) $product->meta_title = htmlspecialchars($product->name) . ' - купить в Санкт-Петербурге | Тюнинг центр';
        if(!$product->meta_description){
            if($minPrice != 0) $product->meta_description = $product->name . ' - купить в Санкт-Петербурге по цене '. number_format($minPrice, 0, '', ' ') .' руб. | Низкие цены, большой выбор, доставка по всей России - Интернет-магазин Atomic Garage - установка линз, тюнинг и ремонт фар, ПТФ, ДХО автомобиля.';
            else $product->meta_description = $product->name . ' - купить в Санкт-Петербурге | Низкие цены, большой выбор, доставка по всей России - Интернет-магазин Atomic Garage - установка линз, тюнинг и ремонт фар, ПТФ, ДХО автомобиля.';
        }
        if(!$product->meta_keywords) $product->meta_keywords = $lowerName . ', купить, для автомобиля, авто, санкт-петербург, россия, доставка, цена, установка, тюнинг центр, линзы, оптика, фары, фонари, птф, ремонт';


        $this->design->assign('meta_title', $product->meta_title);
        $this->design->assign('meta_keywords', $product->meta_keywords);
        $this->design->assign('meta_description', $product->meta_description);

        if($product->product_h1 == '') $product->product_h1 = $product->name;
        $this->design->assign('product_h1', $product->product_h1);

        $adminBtn = '';
        if(isset($_SESSION['admin']) && $_SESSION['admin'] == 'admin') $adminBtn = '/simpla/index.php?module=ProductAdmin&id=' . $product->id;
        $this->design->assign('adminBtn', $adminBtn);

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

    function getMinPrice($variants){
        $minPrice = 0;
        foreach($variants as $row){
            if($minPrice == 0 || $minPrice > $row->price) $minPrice = $row->price;
        }
        return $minPrice;
    }

    function lcfirst( $str ) {
        $str = mb_strtolower( mb_substr($str, 0, 1) ) . mb_substr($str, 1);
        return $str;
    }

}