<?php

class catalogActions extends sfActions
{

    public function executeIndex(sfWebRequest $request)
    {


        $this->catalogs = Doctrine_Query::create()
            ->select("c.id, c.photo, c.order_id, c.alias, cc.id, cc.alias, cct.*, t.*, p.id, p.alias, p.offer_count, p.is_detail, p.is_delete, pt.id, pt.lang, pt.title")
            ->from("Cat c")
            ->leftJoin("c.Translation t")
            ->leftJoin("c.Children cc")
            ->leftJoin("cc.Translation cct")
            ->leftJoin("c.Products p WITH p.is_delete = 0")
            ->leftJoin("p.Translation pt")
            ->andWhere("c.parent_id IS NULL")
            ->orderBy("c.sort, p.sort")
            ->fetchArray();

        $this->culture = $this->getUser()->getCulture();
    }

    public function executeShowCategory(sfWebRequest $request)
    {

        $alias = $request->getParameter('alias');
        $viewType = Doctrine::getTable('Cat')->findOneByAlias($alias)->getViewType();
        $category = false;

        if ($viewType == 'onlyCats') {
            $category = Doctrine_Query::create()
                ->from('Cat c')
                ->innerJoin('c.Translation t')
                ->leftJoin('c.Children ch')
                ->leftJoin('ch.CatProduct cp')
                ->leftJoin('cp.Product p')
                ->innerJoin('ch.Translation ch_t')
                ->where('t.lang = ? AND t.available = 1', $this->getUser()->getCulture())
                ->andWhere('ch_t.lang = ? AND ch_t.available = 1', $this->getUser()->getCulture())
                ->andWhere('p.deleted_at is null')
                //->andWhere('c.parent_id is null')
                ->andWhere('c.alias = ?', $alias)
                ->execute()->getFirst();

            $this->forward404Unless($category);
        } elseif ($viewType == 'onlyProducts') {
            $category = Doctrine_Query::create()
                ->from('Cat c')
                ->innerJoin('c.Translation t')
                ->leftJoin('c.CatProducts prod')
                ->innerJoin('prod.Translation prod_t')
                ->where('t.lang = ? AND t.available = 1', $this->getUser()->getCulture())
                ->andWhere('prod_t.lang = ? AND prod_t.available = 1', $this->getUser()->getCulture())
                ->andWhere('prod.deleted_at is null')
                ->andWhere('c.alias = ?', $alias)
                ->execute()->getFirst();

            $this->viewFilter = false;

        }

        $this->category = $category;
        $this->viewType = $viewType;

    }
//    public function executeShowCategoryChild(sfWebRequest $request)
//    {
//
//        $children_alias = $request->getParameter('child_alias');
//
//        $category = Doctrine_Query::create()
//            ->from('Cat c')
//            ->innerJoin('c.Translation t')
//            ->leftJoin('c.Parent p')
//            ->leftJoin('c.CatProducts prod')
//            ->innerJoin('prod.Translation prod_t')
//            ->innerJoin('p.Translation p_t')
//            ->where('t.lang = ? AND t.available = 1', $this->getUser()->getCulture())
//            ->andWhere('p_t.lang = ? AND p_t.available = 1', $this->getUser()->getCulture())
//            ->andWhere('prod_t.lang = ? AND prod_t.available = 1', $this->getUser()->getCulture())
//            ->andWhere('c.parent_id is not null')
//            ->andWhere('c.alias = ?', $children_alias)
//            ->execute()->getFirst();
//
//
//        $this->forward404Unless($category);
//
//        $this->category = $category;
//
//
//    }
    public function executeShowProduct(sfWebRequest $request)
    {

        $product_alias = $request->getParameter('alias');
        $this->culture = $this->getUser()->getCulture();
        $this->product = Doctrine_Query::create()
            ->from('Product p')
            ->leftJoin('p.Offer o')
            ->leftJoin('p.ProductPropValue ppv')
            ->leftJoin('ppv.ProductProp pp')
            ->leftJoin('pp.ProductPropList ppl')
            ->innerJoin('p.Translation t WITH t.lang = \'' . $this->culture . '\'')
            ->leftJoin('o.Translation to WITH to.lang = \'' . $this->culture . '\'')
            ->leftJoin('ppv.Translation tppv WITH tppv.lang = \'' . $this->culture . '\'')
            ->leftJoin('pp.Translation tpp WITH tpp.lang = \'' . $this->culture . '\'')
            ->leftJoin('ppl.Translation tppl WITH tppv.lang = \'' . $this->culture . '\'')
            ->andWhere('p.alias = ?', $product_alias)
            ->fetchOne();

        $this->setLayout('layoutPage');
    }

    public function executeGood_list(sfWebRequest $request)
    {
        $this->query = $request->getParameter('query', false);
        $this->setLayout('layoutNotLeftMenuNotSearchField');
    }

    public function executeShow(sfWebRequest $request)
    {

        $this->cat = $this->getRoute()->getObject();
        $this->culture = $this->getUser()->getCulture();
        $this->cats = Doctrine_Query::create()
            ->select("c.alias, c.photo, c.parent_id, t.*")
            ->from("Cat c")
            ->innerJoin("c.Translation t")
            ->where("c.parent_id = ?", $this->cat->getId())
            ->fetchArray();
        if(count($this->cats) == 0){
            $products_all_q = Doctrine_Query::create()
                ->select("p.id, p.offer_count, p.is_delete, p.product_img, c.cat_id, c.product_id")
                ->from("Product p INDEXBY p.id")
                ->leftJoin("p.CatProduct c")
                ->where("c.cat_id = ?", $this->cat->getId())
                ->andWhere("p.offer_count > 0")
                ->andWhere("p.is_delete = 0")
                ->orderBy('p.sort asc');
                //->andWhere("CHAR_LENGTH(p.product_img) > 0");
            $products_q = Doctrine_Query::create()
                ->select("p.id, p.alias, p.product_img, p.is_detail, p.offer_count, p.is_delete, c.*, t.id, t.lang, t.title, o.id, o.product_id, o.price, o.quantity_type_select, ot.*, ppv.*")
                ->from("Product p")
                ->leftJoin("p.CatProduct c")
                ->leftJoin("p.Translation t")
                ->leftJoin("p.Offer o")
                ->leftJoin("o.Translation ot")
                ->where("c.cat_id = ?", $this->cat->getId())
                ->andWhere("p.offer_count > 0")
                ->andWhere("p.is_delete = 0")
                ->orderBy('p.sort asc, o.sort asc');
                //->andWhere("CHAR_LENGTH(p.product_img) > 0");
            $filter_list = $request->getParameter('filter_list');
            $filter_range = $request->getParameter('filter_range');
            if($request->isXmlHttpRequest() && ($filter_list || $filter_range)){
                $filter_q = array();                
                foreach (array('list' => $filter_list, 'range' => $filter_range) as $list_key => $list){
                    if(is_array($list) && count($list) > 0){
                        foreach ($list as $prop_id => $values){
                            if(is_numeric($prop_id) && is_array($values) && count($values) > 0){
                                $values_q = array();
                                foreach ($values as $value_key => $value){
                                    if(is_numeric($value)){
                                        if($list_key == 'list'){
                                            $values_q[] = $value;
                                        }elseif($list_key == 'range' && in_array($value_key, array('min', 'max'))){
                                            $values_q[] = $value;
                                        }
                                    }
                                }
                                if(count($values_q) > 0){
                                    if($list_key == 'list'){
                                        $filter_q[] = "p.prop_id = " . $prop_id . " AND p.value IN(" . implode(',', $values_q) . ")";
                                    }elseif($list_key == 'range' && count($values_q) == 2){
                                        $filter_q[] = "p.prop_id = " . $prop_id . " AND p.value >= " . $values_q[0] . " AND p.value <= " . $values_q[1];
                                    }
                                }
                            }
                        }
                    }
                }            
                $filter_q_count = count($filter_q);
                if($filter_q_count > 0){
                    $product_prop_value = Doctrine_Query::create()
                        ->select("p.product_id, COUNT(*)")
                        ->from("ProductPropValue p")
                        ->groupBy("p.product_id")
                        ->where("(" . implode(') OR (', $filter_q) . ")")
                        ->fetchArray();
                    $product_prop_value_real = array();
                    if(count($product_prop_value) > 0){
                    	foreach ($product_prop_value as $key => $value) {
                    		if($value['COUNT'] == $filter_q_count){
                    			$product_prop_value_real[] = $value['product_id'];
                    		}                    		
                    	}
                    }
                    if(count($product_prop_value_real) == 0){                    
                        $product_prop_value_real[] = 'empty';
                    }
                    $products_q->andWhereIn("p.id", $product_prop_value_real);
                    $products_all_q->andWhereIn("p.id", $product_prop_value_real);
                }
            }
            $this->products_all = $products_all_q->fetchArray();
            $this->product_ids = array_keys($this->products_all);
            $page = (int)$request->getParameter('page', 1);
            if(!is_numeric($page) || $page <= 0){
                $page = 1;
            }
            $this->in_page_count = 12;

            $products_all_count = count($this->products_all);
            if ($products_all_count == 1)
            {
                $product_id = array_shift($this->products_all)['id'];
                $product_alias = Doctrine::getTable('Product')->findOneById($product_id)->getAlias();
                $culture = $this->getUser()->getCulture();
                $this->redirect('/' . $culture . '/product/' . $product_alias . '/');
            }
            $this->forward404Unless($products_all_count == 0 || $page <= ceil($products_all_count / $this->in_page_count));
            if($page > 1){
                $products_q->offset($this->in_page_count * ($page - 1));
            }
            $products_q->limit($this->in_page_count);
            $this->products = $products_q->fetchArray();
            if($request->isXmlHttpRequest()){
                if (count($this->products) > 0) {
                    foreach ($this->products as $product) {
                        echo $this->getPartial("product/product", array("product" => $product));
                    }
                    echo $this->getPartial('catalog/pagination', array('count' => $products_all_count, 'in_page_count' => $this->in_page_count));
                }else{
                    echo 'Нет товаров.';
                }
                return sfView::NONE;
            }
        }
    }

    public function executeShow_prod(sfWebRequest $request)
    {
        $this->forward404Unless($request->hasParameter('alias'));

        $alias = $request->getParameter('alias');

        $product = Doctrine::getTable('Product')->findOneByAlias($alias);

        if ($product) {
            $cat_id = $product->getCatProducts()->getFirst()->getId();

            $current_category = Doctrine::getTable('Cat')->find($cat_id);
            $parents = $current_category->getParents();

            $breadcrumbs = array();
            foreach ($parents as $parent) {
                $parent_alias = Doctrine::getTable('Cat')->findOneById($parent->getParentId());

                $breadcrumbs[] = array(
                    'title' => $parent->getTitle(),
                    'id' => $parent->getParentId(),
                    'alias' => $parent_alias->getAlias()
                );
            }
            $breadcrumbs[] = array('title' => $current_category->getTitle(), 'id' => $current_category->getId(), 'alias' => $current_category->getAlias());
            $breadcrumbs[] = array('title' => $product->getTitle(), 'id' => null);

            $this->breadcrumbs = $breadcrumbs;
            $this->product = $product;
        }


    }

    public function executeSpecials(sfWebRequest $request)
    {
        if ($request->hasParameter('type')) {
            $type = $request->getParameter('type');
            $this->type = $type;

            $products = false;

            if ($type == 'sale') {

                $default_price_type = Doctrine::getTable('PriceType')->findOneByIsDefault(1);

                $products = Doctrine_Query::create()
                    ->select("p.id, p.created_at, p.alias, p.title, p.product_code, p.sell_out, min_order, (psc.value) as stockCount")
                    ->addSelect("(SELECT pp.Value FROM ProductPrice pp WHERE pp.product_id = p.id AND pp.price_type_id = " . $default_price_type->getId() . ") as price")
                    ->from("Product p")
                    ->innerJoin("p.CatProduct cp")
                    ->innerJoin("p.ProductStockCount psc")
                    ->where("p.sell_out = 1")
                    ->andWhere("p.deleted_at is null");

                $query = Doctrine_Query::create()
                    ->select("COUNT(p.id)")
                    ->from("Product p")
                    ->innerJoin("p.CatProduct cp")
                    ->innerJoin("p.ProductStockCount psc")
                    ->where("p.sell_out = 1")
                    ->andWhere('p.deleted_at is null');

                $this->breadcrumbs = 'Распродажа';
            }


            $inPage = $request->getParameter('inPage', 10);
            $this->inPage = $inPage;
            $sort = $request->getParameter('sort', 'id');
            $this->sort = $sort;
            $order = $request->getParameter('order', 'asc');
            $this->order = $order;

            if ($order && $sort) {
                switch ($sort) {
                    case 'product_code':
                        $products->orderBy('CAST(p.product_code AS UNSIGNED) ' . strtoupper($order));
                        break;
                    case 'title':
                        $products->orderBy('p.title ' . strtoupper($order));
                        break;
                    case 'price':
                        $products->orderBy('CAST(price AS UNSIGNED) ' . strtoupper($order));
                        break;
                    default:
                        $products->orderBy($sort . ' ' . strtoupper($order));
                        break;
                }
            }


            $product_info = $query->fetchArray();

            $productsCount = $product_info[0]['COUNT'];
            $this->productCount = $productsCount;
            $page = $request->getParameter('page');
            $countPage = ceil($productsCount / $inPage);
            if (!is_numeric($page) || $page <= 0 || $page > $countPage) {
                $page = 1;
            }

            $this->page = $page;
            $this->countPage = $countPage;

            $offset = ($page - 1) * $inPage;

            if ($offset >= $productsCount && $productsCount != 0) {
                $offset = $productsCount - $inPage;
            }

            $products->limit($inPage)->offset($offset);
            $this->products = $products->fetchArray();


        }
    }

    public function executeNew_arrivals(sfWebRequest $request)
    {

        $default_price_type = Doctrine::getTable('PriceType')->findOneByIsDefault(1);

        $this->products = Doctrine_Query::create()
            ->select("p.id, p.title, p.product_code, min_order, (psc.value) as stockCount")
            ->addSelect("(SELECT pp.Value FROM ProductPrice pp WHERE pp.product_id = p.id AND pp.price_type_id = " . $default_price_type->getId() . ") as price")
            ->from("Product p")
            ->innerJoin("p.CatProduct cp")
            ->innerJoin("p.ProductStockCount psc")
            ->orderBy('p.created_at desc')
            ->limit(100)
            ->where('p.deleted_at is null')
            ->fetchArray();
    }

    public function executeQuick_search(sfWebRequest $request)
    {
        if ($request->hasParameter('query')) {
            $searchString = trim(preg_replace('/\s\s+/', ' ', htmlspecialchars($request->getParameter('query'))));

            $default_price_type = Doctrine::getTable('PriceType')->findOneByIsDefault(1);

            $search = Doctrine_Query::create()
                ->select("p.id, p.title, p.alias, p.sell_out, p.product_code, min_order, (psc.value) as stockCount")
                ->addSelect("(SELECT pp.Value FROM ProductPrice pp WHERE pp.product_id = p.id AND pp.price_type_id = " . $default_price_type->getId() . ") as price")
                ->from("Product p")
                ->innerJoin("p.CatProduct cp")
                ->innerJoin("p.ProductStockCount psc")
                ->where('p.title LIKE ?', "%" . $searchString . "%")
                ->andWhere('p.deleted_at is null');

            $searchCount = $search->count();

            if (!$request->hasParameter('full')) {
                $search->limit(5);
            } else {


                $page = 1;
                $count = $search->count();
                $inPage = 5;
                $countPage = ceil($count / $inPage);
                $this->page = $page;
                $this->countPage = $countPage;

                $offset = ($page - 1) * $inPage;

                if ($offset >= $count && $count != 0) {
                    $offset = $count - $inPage;
                }

                $search->limit($inPage)->offset($offset);


                $this->setTemplate('quick_search_full');
            }

            $this->searchString = $searchString;
            $this->searchCount = $searchCount;
            $this->searchResult = $search->fetchArray();

        }
    }
}