<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Cart extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Cart_Model');
    }

    public function index() {
        echo json_encode($this->collectCartData());
    }

    public function addToCart() {
        $line = $this->Cart_Model->addToCart($this->input->post('c'), $this->input->post('m'), $this->input->post('s'), $this->input->post('rule'));
        $data = $this->collectCartData();
        $data['line'] = $line;
        $this->Cart_Model->clearOnAddToCart();
        echo json_encode($data);
    }

    private function collectCartData() {
        $this->Cart_Model->manageFreeDish();
        $data['orderType'] = $this->Cart_Model->getOrderType();
        $data['cart'] = $this->Cart_Model->getCart();
        $data['subtotal'] = $this->Cart_Model->subtotal();
        $data['tax'] = $this->Cart_Model->tax();
        $data['promoDisocunt'] = $this->Cart_Model->promoDisocunt();
        $data['discount'] = $this->Cart_Model->discount();
        $data['multiDiscount'] = $this->Cart_Model->multiDiscount();
        $data['deliveryFee'] = $this->Cart_Model->getDeliveryCharge();
        $data['serviceCharge'] = $this->Cart_Model->getServiceCharge();
        $data['deliveryMinOrderAmount'] = $this->Cart_Model->getDeliveryMinOrder();
        $data['total'] = $this->Cart_Model->total();
        $data['line'] = $this->Cart_Model->getMaxKey();
        $data['freeDishOffer'] = $this->Cart_Model->getDishOfferItem();
        return $data;
    }

    public function freeDishItem() {
        $data = $this->Cart_Model->getDishOfferItem();
        $this->load->view('onlineorder/freedish', $data, false);
    }

    public function plus() {
        $line = $this->Cart_Model->plus($this->input->post('line'));
        $data = $this->collectCartData();
        $data['line'] = $line;
        echo json_encode($data);
    }

    public function minus() {
        $line = $this->Cart_Model->minus($this->input->post('line'));
        $data = $this->collectCartData();
        $data['line'] = $line;
        echo json_encode($data);
    }

    public function remove() {
        $line = $this->Cart_Model->remove($this->input->post('line'));
        $data = $this->collectCartData();
        $data['line'] = $line;
        echo json_encode($data);
    }

    public function clear() {
        $this->Cart_Model->clearCart();
        $this->Cart_Model->setOrderType('collection');
        if ($this->Cart_Model->getOrderType()) {
            echo json_encode($this->collectCartData());
        }
    }

    public function setCollectionType() {
        if ($this->input->post('type') == 'collection') {
            $this->Cart_Model->setOrderType($this->input->post('type'));
            $this->Cart_Model->emptyDeliveryMinOrder();
            $this->Cart_Model->emptyDeliveryCharge();
            $this->Cart_Model->emptyDeliveryWaitingTime();
            $this->Cart_Model->emptyDeliveryPostcode();
        }
        if ($this->Cart_Model->getOrderType() === 'collection') {
            $this->Cart_Model->initiateDiscountPlan();
            $this->Cart_Model->initiateMultiDisocunt();
            $this->Cart_Model->initiateFreeDishOffer();
            echo json_encode(array('status' => true, 'onlineOrderType' => $this->Cart_Model->getOrderType()));
        } else {
            echo json_encode(array('status' => true));
        }
    }

    public function presetPostcode() {
        $address = $this->Cart_Model->get_single('customer_address', array('type' => $this->input->post('type'), 'cid' => $this->session->userdata('customerId')))->row();
        $this->checkPostcode($address->postcode);
    }

    public function checkPostcode($postcode = null) {
        $postcode = $postcode ? postcodeFormat($postcode) : postcodeFormat($this->input->post('postcode'));
        $splitedPostcode = explode(' ', $postcode);
        $area = substr($splitedPostcode[1], 0, 1);
        $deliveryArea = $splitedPostcode[0] . ' ' . $area;
        $deliveryAreaObj = $this->Cart_Model->get_single('deliveryplan', array('title' => $deliveryArea, 'status' => '3'))->row();
        if (!empty($deliveryAreaObj)) {
            $destination = $postcode;
            $orgins = $this->Cart_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row()->address_postcode;
            $apiObj = $this->Cart_Model->get_single('apisetting', array('branch' => $this->session->userdata('branch')))->row();
            if (!empty($apiObj)) {
                if ($apiObj->costPerMile > 0) {
                    $distanceObj = getDrivingDistance($orgins, $destination, $apiObj->apiKey);
                    if (floor($distanceObj['miles']) <= $apiObj->radius) {
                        echo json_encode($this->Cart_Model->deliveryChargeSetup($postcode, $deliveryAreaObj, $apiObj, $distanceObj));
                    } else {
                        echo json_encode(array('status' => false, 'message' => 'Sorry, we do not provide delivery service this area'));
                    }
                } else {
                    echo json_encode($this->Cart_Model->deliveryChargeSetup($postcode, $deliveryAreaObj, $apiObj, array('status' => 'not ok')));
                }
            }
        } else {
            echo json_encode(array('status' => false, 'message' => 'Sorry, we do not provide delivery service this area'));
        }
    }

    function getItemAttributes() {
        $category = $this->input->post('c');
        $menu = $this->input->post('m');
        $selection = $this->input->post('s');
        $menuObj = $this->Cart_Model->get_single('menu', array('id' => $menu))->row();
        $menuObj->price = getItemPrice($menuObj);
        $selectionObj = null;
        if ($selection > 0) {
            $selectionObj = $this->Cart_Model->get_single('menuselection', array('id' => $selection))->row();
            $selectionObj->price = getItemPrice($selectionObj);
        }
        $data['itemTitle'] = !empty($selectionObj) ? $selectionObj->title . ' ' . $menuObj->title : $menuObj->title;
        $data['item'] = $itemObj = !empty($selectionObj) ? $selectionObj : $menuObj;
        if ($itemObj->deal_type == '2') {
            $data['itemSet'] = $this->Cart_Model->get_list('menuset', array('status' => '3', 'category' => $category, 'menu' => $menu, 'selection' => $selection))->result();
            if (!empty($data['itemSet'])) {
                foreach ($data['itemSet'] as $aset) {
                    $data['setItems'][$aset->id] = $this->Cart_Model->get_list('menusetitem', array('status' => '3', 'set' => $aset->id))->result();
                    if (!empty($data['setItems'][$aset->id])) {
                        foreach ($data['setItems'][$aset->id] as $key => $item) {
                            if ($item->selection > 0) {
                                $data['setItems'][$aset->id][$key]->title = get_title('menuselection', array('id' => $item->selection)) . '-' . get_title('menu', array('id' => $item->menu));
                            } else {
                                $data['setItems'][$aset->id][$key]->title = get_title('menu', array('id' => $item->menu));
                            }
                            if (!trim($data['setItems'][$aset->id][$key]->title)) {
                                $data['setItems'][$aset->id][$key]->title = "Undefined";
                            }
                        }
                    }
                    if ($itemObj->ctop !== '2') {
                        $data['setAttrCat'][$aset->id] = $this->Cart_Model->get_list('menuattrcategory', array('status' => '3', 'set' => $aset->id))->result();
                        if (!empty($data['setAttrCat'][$aset->id])) {
                            foreach ($data['setAttrCat'][$aset->id] as $setAttrCat) {
                                $data['setAttrCatItem'][$aset->id][$setAttrCat->id] = $this->Cart_Model->get_list('menuattr', array('status' => '3', 'menuttrcategory' => $setAttrCat->id))->result();
                            }
                        }
                    }
                }
            }
            if ($itemObj->ctop == '2') {
                $data['attrCats'] = $this->Cart_Model->get_list('menuattrcategory', array('status' => 3, 'category' => (int) $category, 'menu' => (int) $menu, 'selection' => (int) $selection))->result();
                if (!empty($data['attrCats'])) {
                    foreach ($data['attrCats'] as $anAttrCat) {
                        $data['attr'][$anAttrCat->id] = $this->Cart_Model->get_list('menuattr', array('menuttrcategory' => $anAttrCat->id, 'status' => '3'))->result();
                    }
                }
            }
        } else {
            $data['attrCats'] = $this->Cart_Model->get_list('menuattrcategory', array('status' => 3, 'category' => (int) $category, 'menu' => (int) $menu, 'selection' => (int) $selection))->result();
            if (!empty($data['attrCats'])) {
                foreach ($data['attrCats'] as $anAttrCat) {
                    $data['attr'][$anAttrCat->id] = $this->Cart_Model->get_list('menuattr', array('menuttrcategory' => $anAttrCat->id, 'status' => '3'))->result();
                }
            }
        }
        echo json_encode($data);
    }

    function addItemAttributes() {
        $this->Cart_Model->setTopping($this->input->post('Topping'));
        $this->Cart_Model->setSetItme($this->input->post('setItem'));
        $this->Cart_Model->setItemComment($this->input->post('comment'));
        echo json_encode(array('status' => $this->Cart_Model->getTopping() || true));
    }

    function plusItemAttribute() {
        $line = $this->Cart_Model->plusItemAttribute($this->input->post('line'), $this->input->post('category'), $this->input->post('id'));
        $data = $this->collectCartData();
        $data['line'] = $line;
        echo json_encode($data);
    }
    
     public function choose_order_type() {
        if ($this->input->post('type') == 'collection') {
            $this->Cart_Model->setOrderType($this->input->post('type'));
            $this->Cart_Model->emptyDeliveryMinOrder();
            $this->Cart_Model->emptyDeliveryCharge();
            $this->Cart_Model->emptyDeliveryWaitingTime();
            $this->Cart_Model->emptyDeliveryPostcode();
            if ($this->Cart_Model->getOrderType() === 'collection') {
                $this->Cart_Model->initiateDiscountPlan();
                $this->Cart_Model->initiateMultiDisocunt();
                $this->Cart_Model->initiateFreeDishOffer();
                echo json_encode(array('status' => true, 'onlineOrderType' => $this->Cart_Model->getOrderType()));
            } else {
                echo json_encode(array('status' => true));
            }
        } else {
            if ($this->input->post('type') === "delivery") {
                $postcode = postcodeFormat($this->input->post('postcode'));
                $splitedPostcode = explode(' ', $postcode);
                $area = substr($splitedPostcode[1], 0, 1);
                $deliveryArea = $splitedPostcode[0] . ' ' . $area;
                $deliveryAreaObj = $this->Cart_Model->get_single('deliveryplan', array('title' => $deliveryArea, 'status' => '3'))->row();
                if (!empty($deliveryAreaObj)) {
                    $destination = $postcode;
                    $orgins = $this->Cart_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row()->address_postcode;
                    $apiObj = $this->Cart_Model->get_single('apisetting', array('branch' => $this->session->userdata('branch')))->row();
                    if (!empty($apiObj)) {
                        if ($apiObj->costPerMile > 0) {
                            $distanceObj = getDrivingDistance($orgins, $destination, $apiObj->apiKey);
                            if (floor($distanceObj['miles']) <= $apiObj->radius) {
                                echo json_encode($this->Cart_Model->deliveryChargeSetup($postcode, $deliveryAreaObj, $apiObj, $distanceObj));
                            } else {
                                echo json_encode(array('status' => false, 'message' => 'Sorry, we do not provide delivery service this area'));
                            }
                        } else {
                            echo json_encode($this->Cart_Model->deliveryChargeSetup($postcode, $deliveryAreaObj, $apiObj, array('status' => 'not ok')));
                        }
                    }
                } else {
                    echo json_encode(array('status' => false, 'message' => 'Sorry, we do not provide delivery service this area'));
                }
            }
        }
    }

}
