<?php

class basketActions extends sfActions
{
    private function add($offers, $basket_id)
    {
        $add_ids = array();
        if(is_array($offers) &&  count($offers) > 0 && $basket_id){
            foreach ($offers as $offer_id => $offer_amount){
                if(is_numeric($offer_id) && is_numeric($offer_amount) && $offer_amount > 0){
                    if($offer = Doctrine::getTable("Offer")->findOneByIdAndIsDelete($offer_id, false)){
                        $basket_offer = Doctrine::getTable("BasketOffer")->findOneByOfferIdAndBasketId($offer->getId(), $basket_id);
                        $amount = ($basket_offer ? $basket_offer->getAmount() : 0) + $offer_amount;
                        if(!$basket_offer){
                            $basket_offer = new BasketOffer();
                        }
                        $basket_offer->setBasketId($basket_id);
                        $basket_offer->setOfferId($offer->getId());
                        $basket_offer->setAmount($amount);
                        $basket_offer->setPrice(($offer->getPrice() * $amount));
                        $basket_offer->save();
                        $add_ids[] = $offer->getId();
                    }
                }
            }
        }
        return $add_ids;
    }
    function executeAjaxSetCountProduct(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest()) {
            $prod_id = $request->getParameter('prod_id');
            $value = $request->getParameter('value');
            $can_new = $request->getParameter('can_new', false);

            $product = Doctrine::getTable('Product')->find($prod_id);

            if ($value % $product->getMinOrder() == 0) {
                $basket = $this->getUser()->getBasket();
                $productsInBasket = $basket->getBasketProduct();

                $sets = false;
                foreach ($productsInBasket as $productInBasket) {
                    if ($productInBasket->getProductId() == $prod_id) {
                        if ($value == 0) {
                            $productInBasket->delete();
                        } else {
                            $productInBasket->setProductCount($value);
                            $productInBasket->save();
                        }
                        $sets = true;
                    }
                }

                if (!$sets && $can_new) {
                    $newBasketProduct = new BasketProduct();
                    $newBasketProduct->setBasket($basket);
                    $newBasketProduct->setProduct($product);
                    $newBasketProduct->setProductCount($value);
                    $newBasketProduct->save();
                }

            }


            return $this->renderComponent('basket', 'counter');

        } else {
            $this->forward404();
        }
    }

    function executeAjaxUpOrDownCountProduct(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest()) {
            $prod_id = $request->getParameter('prod_id');
            $operation = $request->getParameter('operation');

            $basket = $this->getUser()->getBasket();
            $productsInBasket = $basket->getBasketProduct();

            $sets = false;
            foreach ($productsInBasket as $productInBasket) {
                if ($productInBasket->getProductId() == $prod_id) {
                    if ($operation == 'plus') {
                        $product = $productInBasket->getProduct();
                        $value = $productInBasket->getProductCount() + $product->getMinOrder();
                        $productInBasket->setProductCount($value);
                        $productInBasket->save();
                    }
                    if ($operation == 'minus') {
                        $product = $productInBasket->getProduct();
                        $value = $productInBasket->getProductCount() - $product->getMinOrder();

                        if ($value == 0) {
                            $productInBasket->delete();
                        } else {
                            $productInBasket->setProductCount($value);
                            $productInBasket->save();
                        }
                    }
                    $sets = true;
                }
            }

            if (!$sets) {
                $product = Doctrine::getTable("Product")->findOneById($prod_id);
                if ($operation == 'plus' && $product) {
                    $newBasketProduct = new BasketProduct();
                    $newBasketProduct->setProduct($product);
                    $newBasketProduct->setBasket($basket);
                    $newBasketProduct->setProductCount($product->getMinOrder());
                    $newBasketProduct->save();
                }
            }


            return $this->renderComponent('basket', 'counter');

        } else {
            $this->forward404();
        }
    }

    function executeAjaxAddProduct(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest()) {

            $prod_id = $request->getParameter('prod_id');
            $value = $request->getParameter('value');

            $product = Doctrine::getTable('Product')->find($prod_id);

            if ($product && $product->getMinOrder() > 0 && $product->getDefaultPrice() != 0) {
                $basket = $this->getUser()->getBasket();
                $productsInBasket = $basket->getBasketProduct();

                $found = false;
                foreach ($productsInBasket as $productInBasket) {
                    if ($productInBasket->getProductId() == $product->getId()) {
                        $found = true;
                        if ($productInBasket->getProductCount() != $value) {
                            if ($value % $product->getMinOrder() == 0) {
                                $productInBasket->setProductCount($value);
                                $productInBasket->save();
                            }
                        }
                    }


                }

                if (!$found) {
                    $newBasketProduct = new BasketProduct();
                    $newBasketProduct->setProduct($product);
                    $newBasketProduct->setBasket($basket);
                    $newBasketProduct->setProductCount($value);
                    $newBasketProduct->save();
                }

                return $this->renderComponent('basket', 'counter');

            }

            return sfView::NONE;
        } else {
            $this->forward404();
        }
    }


    public function executeMake_order(sfWebRequest $request)
    {

        if ($request->isXmlHttpRequest() && $this->getUser()->isAuthenticated()) {
            $this->setLayout(false);

            $comment = false;
            if ($request->hasParameter('comment')) {
                $comment = strip_tags($request->getParameter('comment'));
            }

            $basket = $this->getUser()->getBasket();
            $productsInBasket = $basket->getBasketProduct();

            if (count($productsInBasket) > 0) {
                $newClientOrder = new ClientOrder();
                $newClientOrder->setUserId($this->getUser()->getUserId());
                $newClientOrder->setOrderStatusId(1);

                if ($comment) {
                    $newClientOrder->setComment($comment);
                }

                $delivery = $request->getParameter('delivery');
                $delivery_address = null;

                if ($delivery) {
                    $delivery_address = $request->getParameter('delivery_address');
                } else {
                    $newClientOrder->setTimeToPickup($request->getParameter('time_to_pickup'));
                }

                $newClientOrder->save();

                foreach ($productsInBasket as $products) {
                    $newOrderItem = new OrderItem();
                    $newOrderItem->setProduct_id($products->getProductId());
                    $newOrderItem->setProductCount($products->getProductCount());
                    $newOrderItem->setClientOrder($newClientOrder);
                    $newOrderItem->save();
                }


                $basket->setDelivery($delivery);
                $basket->setDeliveryAddress($delivery_address);

                $basket->setOrderId($newClientOrder->getId());
                $basket->save();


                sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');
                get_component('pages', 'emailSender', array('type' => 'adminNotificationAboutOrder', 'emailTo' => 'admin', 'param' => array('delivery_address' => $delivery_address, 'delivery' => $delivery, 'order_id' => $newClientOrder->getId(), 'inn' => $this->getUser()->getUsername(), 'phone_number' => $this->getUser()->getAccount()->getPhoneNumber(), 'org' => $this->getUser()->getAccount()->getOrganization(), 'comment' => $comment, 'products_order' => $this->getUser()->getProductsNameAndCountAndSumInBasket())));


                $this->getUser()->unbindBasket();

                echo json_encode(array('state' => 'success', 'id' => $newClientOrder->getId()));

            } else {
                echo 'empty_basket';
            }

        } else {
            $this->forward404();
        }
        return sfView::NONE;
    }

    public function executeFast_make_order(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest() && $request->hasParameter('phone')) {


            $this->setLayout(false);
            $phone = (int)str_replace(array('(', ')', '+', '-', ' '), '', $request->getParameter('phone'));
            $email = $request->getParameter('email');
            
            if (strlen($phone) == 11 && is_int($phone)) {

                $comment = false;
                if ($request->hasParameter('comment')) {
                    $comment = strip_tags($request->getParameter('comment'));
                }

                $basket = $this->getUser()->getBasket();
                $productsInBasket = $basket->getBasketProduct();

                if (count($productsInBasket) > 0) {

                    $user = Doctrine::getTable('user')->findOneByUsername($phone);

                    if (!$user) {
                        $user = new User();
                        $user->setUsername($phone);
                        $user->save();
                    }

                    $newClientOrder = new ClientOrder();
                    $newClientOrder->setUserId($user->getId());
                    $newClientOrder->setOrderStatusId(1);

                    if ($comment) {
                        $newClientOrder->setComment($comment);
                    }

                    $delivery = $request->getParameter('delivery');
                    $delivery_address = null;

                    if ($delivery) {
                        $delivery_address = $request->getParameter('delivery_address');
                    } else {
                        $newClientOrder->setTimeToPickup($request->getParameter('time_to_pickup'));
                    }

                    $newClientOrder->save();

                    foreach ($productsInBasket as $products) {
                        $newOrderItem = new OrderItem();
                        $newOrderItem->setProduct_id($products->getProductId());
                        $newOrderItem->setProductCount($products->getProductCount());
                        $newOrderItem->setClientOrder($newClientOrder);
                        $newOrderItem->save();
                    }

                    $basket->setOrderId($newClientOrder->getId());

                    $order_id = $newClientOrder->getId();
                    $basket->setDelivery($delivery);
                    $basket->setDeliveryAddress($delivery_address);

                    $basket->save();


                    sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');
                    get_component('pages', 'emailSender',
                        array(
                            'type' => 'adminNotificationAboutFastOrder',
                            'emailTo' => 'admin',
                            'param' => array(
                                'delivery_address' => $delivery_address,
                                'delivery' => $delivery, 'phone' => $phone,
                                'comment' => $comment,
                                'email' => $email,
                                'order_id' => $order_id,
                                'products_order' => $this->getUser()->getProductsNameAndCountAndSumInBasket()
                        )));


                    $this->getUser()->unbindBasket();

                    echo json_encode(array('state' => 'success', 'id' => $newClientOrder->getId()));

                } else {
                    echo 'empty_basket';
                }

            } else {
                echo 'no_valid_phone';
            }
            return sfView::NONE;
        } else {
            $this->forward404();
        }
    }
    public function executeIndex(sfWebRequest $request)
    {
        $this->order_form = new wwwBasketOrderForm();
        if($request->isMethod('post')){
            $user = $this->getUser();
            $basket = $user->getBasket();
            $basket_info = $user->getBasketInfo();
            if($basket_info['offerCount'] > 0){
                $this->order_form->bind($request->getParameter($this->order_form->getName()));
                if($this->order_form->isValid()){

                    $order = $this->order_form->save();
                    $basket->setBasketOrderId($order->getId());
                    $basket->save();
                    $user->setAttribute('basket_complete_id', $order->getId());


                    $order_id = $order->getId();
                    $email = $order->getEmail();
                    $phone = $order->getPhone();

                    $delivery_type = $order->getDeliveryType();
                    $delivery_address = $order->getDeliveryAddress();
                    $payment_type = $order->getPaymentType();
                    $name = $order->getUsername();
                    $comment = $order->getComment();

                    $products['elem'] = array();
                    $products['sum'] = 0;


                    foreach ($basket->getBasketOffer()->toArray() as $key => $basketOffer)
                    {
                        $offerTranslation = Doctrine_Query::create()
                            ->select('o.*, t.*')
                            ->from('Offer o')
                            ->where('o.id = ?', intval($basketOffer['offer_id']))
                            ->leftJoin('o.Translation t')
                            ->fetchArray();


                        $products['elem'][$key]['name'] = $offerTranslation[0]['Translation']['ru']['title'];
                        $products['elem'][$key]['price'] = intval($basketOffer['price'])/$basketOffer['amount'];
                        $products['elem'][$key]['count'] = $basketOffer['amount'];
                        $products['sum'] = $products['sum'] + intval($basketOffer['price']);
                    }


                    $emails_dirty = NotificationEmailsTable::getInstance()->createQuery('e')
                        ->select('e.email')
                        ->where("e.is_active = 1")
                        ->andWhere("e.notic_type = 'order' OR e.notic_type = 'all'")
                        ->fetchArray();

                    if (count($emails_dirty) > 0)
                    {
                        $emails = array();

                        foreach ($emails_dirty as $e)
                        {
//                            $emails[] = 'yakov@atmadev.ru';
//                            break;
                            $emails[] = $e['email'];
                        }

                        sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');

                        get_component('pages', 'emailSender',
                            array(
                                'type' => 'adminNotificationAboutFastOrder',
                                'emailTo' => $emails,
                                'param' =>  array(
                                    'delivery_address' => $delivery_address,
                                    'delivery_type' => $delivery_type,
                                    'payment_type' => $payment_type,
                                    'email' => $email,
                                    'order_id' => $order_id,
                                    'name' => $name,
                                    'phone' => $phone,
                                    'comment' => $comment,
                                    'products_order' => $products,
                                    'host' => $request->getHost()
                                )
                            )
                        );
                    }


                    $this->redirect('@basket_complete');
                }
            }
        }
        $this->setLayout('layoutFullWidth');

    }
    public function executeAppend(sfWebRequest $request)
    {
        $table = $request->getParameter('instance');
        if ($table !== 'offer' && $table !== 'product') {
            $result = array('status' => 'error', 'message' => 'incorrect instance');
            return $this->returnSwitch($request, $result);
        }
        $this->setTemplate(false);
        $basket = $this->getUser()->getBasket();
        $elemId = $request->getParameter('id');
        $elem = Doctrine_Core::getTable($table)->find($elemId);
        $count = $request->getParameter('count_' . $elemId);

        try {
            $basket->addOrUpdate($elem, $count);
            $result = array('status' => 'success');
        } catch (Exception $e) {
            $result = array('status' => 'error', 'message' => $e->getMessage());
        }

        return $this->returnSwitch($request, $result);
    }
    public function executeChangeProductCount(sfWebRequest $request)
    {
        $basket = $this->getUser()->getBasket();
        $basketProduct = BasketProductTable::getInstance()->findBoundBasket($request->getParameter('bp_id'), $basket);
        if (!$basketProduct instanceof BasketProduct) {
            return $this->returnSwitch($request, array('status' => 'error', 'message' => 'BasketProduct not found'));
        }
        $count = 0;
        switch ($request->getParameter('operation')) {
            case 'up':
                $count = 1;
                break;
            case 'down':
                $count = -1;
                break;
            default:
                return $this->returnSwitch($request, array('status' => 'error', 'message' => 'Broken operation'));
        }
        $basketProduct->addProductCount($count);
        $basketProduct->save();
        return $this->returnSwitch($request, array('status' => 'success', 'count' => $basketProduct->getProductCount()));
    }

    protected function returnSwitch(sfWebRequest $request, $data = null)
    {
        if ($request->isXmlHttpRequest() || $request->getReferer() == '') {
            return $this->renderText(json_encode($data));
        } else {
            $this->redirect($request->getReferer());
        }
    }

    public function executeRe_ordering(sfWebRequest $request)
    {
        if ($request->hasParameter('orderId') && $this->getUser()->isAuthenticated()) {
            $orderId = $request->getParameter('orderId');
            $order = Doctrine::getTable("ClientOrder")->findOneByIdAndUserId($orderId, $this->getUser()->getUserId());

            if ($order) {

                $order_item = Doctrine::getTable("OrderItem")->findByClientOrderId($orderId);

                $this->getUser()->unbindBasket();
                $new_basket = $this->getUser()->getBasket();

                foreach ($order_item as $item) {
                    $this->addInBasket($item['product_id'], $item['product_count']);
                }

                $this->forward('basket', 'index');

            } else {
                $this->forward404();
            }
        } else {
            $this->forward404();
        }
    }

    public function executeAjax(sfWebRequest $request)
    {
        $res = array('state' => 'error');
        $user = $this->getUser();
        $basket = $user->getBasket();
        if($request->getParameter('type') == 'add'){
            $add_ids = $this->add($request->getParameter('offers'), $basket->getId());
            if(count($add_ids) > 0){
                $res['state'] = 'success';
                $res['info'] = $user->getBasketInfo();
            }
        }elseif($request->getParameter('type') == 'update'){
            $ids = array();
            foreach ($request->getParameter('offers') as $key => $item)
            {
                $ids[] = $key;
            }
            Doctrine_Query::create()
                ->delete("BasketOffer")
                ->whereIn("offer_id", $ids)
                ->andWhere("basket_id = ?", $basket->getId())
                ->execute();
            $add_ids = $this->add($request->getParameter('offers'), $basket->getId());
            $res['state'] = 'success';
            $res['html'] = $this->getComponent('basket', 'basket');
            $res['info']= $user->getBasketInfo();
        }elseif($request->getParameter('type') == 'clean'){
            Doctrine_Query::create()
                ->delete("BasketOffer")
                ->where("basket_id = ?", $basket->getId())
                ->execute();
            $res['state'] = 'success';
        }
        echo json_encode($res);
        return sfView::NONE;
    }

    protected function addInBasket($productId, $setValue = false)
    {
        $basket = $this->getUser()->getBasket();
        $product = Doctrine::getTable('Product')->find($productId);
        $default_price_type = Doctrine::getTable('PriceType')->findOneByIsDefault(1);


        $product = Doctrine_Query::create()->select('p.*')->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')->where('p.id = ' . $productId)->fetchOne();

        if ($product && $basket && $product->getMinOrder() != 0 && $product->getPrice()) {
            $found = false;
            $productsInBasket = $basket->getBasketProduct();
            $minOrder = $product->getMinOrder();
            $stock = $product->getProductStockCount()->getFirst()->getValue();

            foreach ($productsInBasket as $productInBasket) {
                if ($productInBasket->getProductId() == $product->getId()) {
                    $found = true;

                    $count = $setValue !== false ? $setValue : $productInBasket->getProductCount() + $minOrder;

                    if ($count % $minOrder == 0 && $count <= $stock) {
                        $productInBasket->setProductCount($count);
                        $productInBasket->save();

                    }

                    break;
                }
            }

            if (!$found && $stock > 0) {

                $newBasketProduct = new BasketProduct();
                $newBasketProduct->setProduct($product);
                $newBasketProduct->setBasket($basket);

                if ($setValue !== false && $setValue % $minOrder == 0) {
                    $newBasketProduct->setProductCount($setValue);
                } else {
                    $newBasketProduct->setProductCount($minOrder);
                }

                $newBasketProduct->save();

                $basket->getBasketProduct()->add($newBasketProduct);

            }

        }

    }

    protected function removeInBasket($productId, $notCountCheck = false)
    {
        $productsInBasket = $this->getUser()->getBasket()->getBasketProduct();

        foreach ($productsInBasket as $productInBasket) {
            if ($productInBasket->getProductId() == $productId) {
                if ($notCountCheck) {
                    $count = 0;
                } else {
                    $min_p = $productInBasket->getProduct()->getMinOrder();
                    $count = $productInBasket->getProductCount() - $min_p;
                }

                if ($count > 0) {
                    $productInBasket->setProductCount($count);
                    $productInBasket->save();
                } else {
                    $productInBasket->delete();
                }

            }
        }

    }

    public function executeComplete(sfWebRequest $request)
    {
        $basket_order_id = $this->getUser()->getAttribute('basket_complete_id');
        $this->forward404Unless($basket_order_id && is_numeric($basket_order_id));
        $this->getUser()->setAttribute('basket_complete_id', null);
        $this->basket_order = Doctrine_Query::create()
            ->select("o.*, b.*, of.*, SUM(of.price) AS offer_price")
            ->from("BasketOrder o")
            ->innerJoin("o.Basket b")
            ->innerJoin("b.BasketOffer of")
            ->where("id = ?", $basket_order_id)
            ->fetchOne();
        $this->forward404Unless($this->basket_order);
    }
}