<?php

class myUser extends doAuthSecurityUser
{
    static private
        $basket_info = array(),
        $basket = false;

    public function isFirstRequest($boolean = null)
    {
        if (is_null($boolean))
        {
            return $this->getAttribute('first_request', true);
        }

        $this->setAttribute('first_request', $boolean);
    }

    public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array())
    {
        parent::initialize($dispatcher, $storage, $options);
        $r = sfContext::getInstance()->getRequest();
        $culture = $r->getParameter('sf_culture');
        if(!$culture){
            $culture = $r->getParameter('lang');
        }
        if ($culture) {
            if (in_array($culture, array('ru', 'en'))) {
                $this->setCulture($culture);
                sfContext::getInstance()->getResponse()->addHttpMeta('language', $this->getCulture(), true);
            } else {
                header('Location: /404.html');
                die();
            }
        }
    }

    public function getBasket()
    {
        if(!self::$basket){
            $basket = false;
            if ($this->getAttribute('basket_id')) {
                $basket = Doctrine_Query::create()
                    ->from("Basket")
                    ->where("id = ?", $this->getAttribute('basket_id'))
                    ->andWhere("basket_order_id IS NULL")
                    ->fetchOne();
            }
            if (!$basket) {
                $basket = new Basket();
                $basket->save();
                $this->setAttribute('basket_id', $basket->getId());
            }
            self::$basket = $basket;
        }
        return self::$basket;
    }

    public function getBasketInfo()
    {
        if(count(self::$basket_info) == 0){
            $info = Doctrine_Query::create()
                ->select("COUNT(*) as offer_count, SUM(b.price) as price_sum")
                ->from("BasketOffer b")
                ->innerJoin("b.Offer o WITH o.is_delete = 0")
                ->where("basket_id = ?", $this->getBasket()->getId())
                ->fetchOne();
            self::$basket_info = array(
                'offerCount' => $info['offer_count'],
                'offerCountText' => $info['offer_count'] . ' ' . (!in_array('en', array(sfContext::getInstance()->getRequest()->getParameter('lang'), $this->getCulture())) ? 'товар' . Page::niceRusEnds($info['offer_count'], '', 'а', 'ов') : ('product' . ($info['offer_count'] == 1 ? '' : 's'))),
                'price' => $info['price_sum'],
                'priceText' => number_format($info['price_sum'], 0, ',', ' ')
            );
        }
        return self::$basket_info;
    }
}
