<?php

class Mcommerce_Mobile_CartController extends Mcommerce_Controller_Mobile_Default {

    public function findAction() {

        $option = $this->getCurrentOptionValue();

        $cart = $this->getCart();

        $application = $this->getApplication();
        $color = $application->getBlock('background')->getColor();

        $trashImageUrl = $this->_getColorizedImage($this->_getImage("pictos/trash.png"), $color);

        $moreImageUrl = $this->_getColorizedImage($this->_getImage("pictos/more.png"), $color);

        $isValidCart = !$this->getStore()->getMinAmount() || $this->getCart()->getSubtotalInclTax() >= $this->getStore()->getMinAmount();

        $html["cart"] = array(
            "id" => $cart->getId(),
            "valid" => $isValidCart,
            "deliveryMethodId" => $cart->getDeliveryMethodId(),
            "paymentMethodId" => $cart->getPaymentMethodId(),
            "paymentMethodName" => $cart->getPaymentMethod() != null ? $cart->getPaymentMethod()->getName(): null,
            "customer" => array(
                "id" => $cart->getCustomerId(),
                "firstname" => $cart->getCustomerFirstname(),
                "lastname" => $cart->getCustomerLastname(),
                "email" => $cart->getCustomerEmail(),
                "phone" => $cart->getCustomerPhone(),
                "birthday" => $cart->getCustomerBirthday(),
                "street" => $cart->getCustomerStreet(),
                "postcode" => $cart->getCustomerPostcode(),
                "city" => $cart->getCustomerCity(),
                "latitude" => $cart->getCustomerLatitude(),
                "longitude" => $cart->getCustomerLongitude()
            ),
            "storeId" => $cart->getStoreId(),
            "subtotalExclTax" => (float) $cart->getSubtotalExclTax(),
            "formattedSubtotalExclTax" => $cart->getSubtotalExclTax() > 0 ? $cart->getFormattedSubtotalExclTax() : null,
            "deliveryCost" => (float)  $cart->getDeliveryCost(),
            "formattedDeliveryCost" => $cart->getDeliveryCost() > 0 ? $cart->getFormattedDeliveryCost() : null,
            "deliveryTaxRate" => (float)  $cart->getDeliveryTaxRate(),
            "formattedDeliveryTaxRate" => $cart->getDeliveryTaxRate() > 0 ? $cart->getFormattedDeliveryTaxRate() : null,
            "totalExclTax" => (float)  $cart->getTotalExclTax(),
            "formattedTotalExclTax" => $cart->getTotalExclTax() > 0 ? $cart->getFormattedTotalExclTax() : null,
            "totalTax" => (float)  $cart->getTotalTax(),
            "formattedTotalTax" => $cart->getTotalTax() > 0 ? $cart->getFormattedTotalTax() : null,
            "total" => (float)  $cart->getTotal(),
            "formattedTotal" => $cart->getTotal() > 0 ? $cart->getFormattedTotal() : null,
            "lines" => array(),
            "pictos" => array(
                "trash" => $trashImageUrl,
                "more" => $moreImageUrl
            )
        );

        $lines = $cart->getLines();

        foreach ($lines as $line){

            $product = $line->getProduct();

            $lineJson = array(
                "id" => $line->getId(),
                "product" => array(
                    "picture" => $product->getPictureUrl()
                ),
                "name" => $line->getName(),
                "qty" => $line->getQty(),
                "price" => (float) $line->getPrice(),
                "formattedPrice" => $line->getPrice() > 0 ? $line->getFormattedPrice() : null,
                "formattedPriceInclTax" => $line->getPriceInclTax() > 0 ? $line->getFormattedPriceInclTax() : null,
                "formattedBasePrice" => $line->getFormattedBasePrice(),
                "formattedBasePriceInclTax" => $line->getFormattedBasePriceInclTax(),
                "total" => (float) $line->getTotal(),
                "formattedTotal" => $line->getTotal() > 0 ? $line->getFormattedTotal() : null,
                "totalInclTax" => (float) $line->getTotalInclTax(),
                "formattedTotalInclTax" => $line->getTotalInclTax() > 0 ? $line->getFormattedTotalInclTax() : null,
                "options" => array ()
            );


            foreach ($line->getOptions() as $option){

                $lineJson["options"][] = array(
                    "id" => $option->getId(),
                    "qty" => $option->getQty(),
                    "name" => $option->getName(),
                    "price" => (float) $option->getPrice(),
                    "formattedPrice" => $option->getFormattedPrice(),
                    "priceInclTax" => (float) $option->getPriceInclTax(),
                    "formattedPriceInclTax" => $option->getFormattedPriceInclTax(),
                );
            }

            $html["cart"]["lines"][] = $lineJson;

        }


        $this->_sendHtml($html);
    }

    /**
     * Ajoute un produit au panier
     *
     * @throws Exception
     */
    public function addAction() {

        $logger = Zend_Registry::get("logger");

        if ($data = Zend_Json::decode($this->getRequest()->getRawBody())) {

            $form = $data["form"];


            $html = array();

            try {
                if(empty($form['product_id'])) throw new Exception($this->_('An error occurred during the process. Please try again later.'));

                $product = new Catalog_Model_Product();
                $product->find($form['product_id']);

                $errors = array();

                foreach($product->getGroups() as $group) {
                    if($group->isRequired() AND empty($form['options'][$group->getId()])) $errors[] = $group->getTitle();
                }

                if(empty($errors)) {
                    $current_store = $this->getStore();
                    $cart = $this->getCart();
                    $product->setTaxRate($current_store->getTax($product->getTaxId())->getRate())
                        ->setQty(!empty($form['qty']) ? $form['qty'] : 1)
                        ;


                    if(!empty($form['options'])) {
                        $options = array();
                        foreach($product->getGroups() as $group) {
                                
                            $logger->log('Option id:'. $form['options'][$group->getId()]['option_id'] . ' for group ' . $group->getId(), Zend_Log::DEBUG);
                            
                            foreach($group->getOptions() as $option) {
                                
                                $logger->log($option->getOptionId(), Zend_Log::DEBUG);
                                
                                if(isset($form['options'][$group->getId()]['option_id']) AND $option->getOptionId() == $form['options'][$group->getId()]['option_id']) {
                                    $option->setQty(isset($form['options'][$group->getId()]['qty']) ? $form['options'][$group->getId()]['qty'] : 1);
                                    $options[] = $option;
                                }
                            }

                        }

                        if (sizeof($form['options']) != sizeof($options)) {
                            $logger->log("Only " . sizeof($options) . " of " . sizeof($form['options']) . " options have been fount in " . sizeof($product->getGroups()) . " groups.", Zend_Log::ERR);
                        }else{ 
                            $logger->log(sizeof($options) . " have been fount.", Zend_Log::DEBUG);
                        }
                        $product->setOptions($options);
                    }

                    $cart->addProduct($product)
                        ->save()
                    ;

                    $html = array('success' => 1);
                }
                else {
                    if(count($errors) == 1) $message = $this->_("The option %s is required", current($errors));
                    else $message = $this->_('The following options are required:<br />%s', implode('<br />- ', $errors));
                    throw new Exception($message);
                }

            }
            catch(Exception $e) {
                $html = array(
                    'error' => 1,
                    'message' => $e->getMessage()
                );
            }

            $this->_sendHtml($html);
        } 

    }

    public function deleteAction() {

        if($lineId = $this->getRequest()->getParam('line_id')) {

            $html = array();

            try {
                if(empty($lineId)) throw new Exception($this->_('An error occurred during the process. Please try again later.'));

                $this->getCart()
                    ->removeProduct($lineId)
                    ->save()
                    ;

                $html = array('success' => 1, 'line_id' => $lineId);

            }
            catch(Exception $e) {
                $html = array(
                    'error' => 1,
                    'message' => $e->getMessage()
                );
            }

            $this->_sendHtml($html);

        }
    }
}