<?php

class Mcommerce_Mobile_Sales_DeliveryController extends Mcommerce_Controller_Mobile_Default {


    public function findstoresAction() {
        $option = $this->getCurrentOptionValue();

        $mcommerce = $option->getObject(); 

        $stores = $mcommerce->getStores();

        $html= array("stores" => array());

        foreach ($stores as $store) {

            $storeJson = array(
                "id" => $store->getId(),
                "name" =>$store->getName(),
                "deliveryMethods" => array()
            );;


            foreach ($store->getDeliveryMethods() as $deliveryMethod) {
                $deliveryMethod->setCart($this->getCart());
                if ($deliveryMethod->isAvailable()){
                    $storeJson["deliveryMethods"][] = array(
                        "id" => $deliveryMethod->getId(),
                        "name" =>$deliveryMethod->getName(),
                        "price" => (double) $deliveryMethod->getPrice(),
                        "formattedPrice" => $deliveryMethod->getPrice() > 0 ? $deliveryMethod->getFormattedPrice() : null
                    );
                }
            }

            $html["stores"][] = $storeJson;
        }

        $this->_sendHtml($html);
    }

    public function updateAction() {

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

            $datas= $data["form"];

            $html = array();

            try {

                if(empty($datas['delivery_method_id'])) throw new Exception($this->_('Please choose a delivery method'));
                if(empty($datas['store_id'])) throw new Exception($this->_('An error occurred while saving. Please try again later.'));

                $this->getCart()
                    ->setStoreId($datas['store_id'])
                    ->setDeliveryMethodId($datas['delivery_method_id'])
                    ->save();

                $html = array(
                    'store_id' => $this->getCart()->getStoreId(),
                    'delivery_method_id' => $this->getCart()->getDeliveryMethodId(),
                    'cartId' => $this->getCart()->getId()
                );
            }
            catch(Exception $e ) {
                $html = array(
                    'error' => 1,
                    'message' => $e->getMessage()
                );
            }

            $this->_sendHtml($html);
        } 

    }
}