<?php

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

class Cart_Model extends MY_Model {

    function __construct() {
        parent::__construct();
    }

    public function setOrderType($data) {
        $this->session->set_userdata('onlineOrderType', $data);
    }

    public function getOrderType() {
        if ($this->session->userdata('onlineOrderType')) {
            return $this->session->userdata('onlineOrderType');
        }
    }

    public function emptyOrderType() {
        $this->session->unset_userdata('onlineOrderType');
    }

    public function addToCart($category, $menu, $selection, $rule) {
        if ((int) $category > 0 && (int) $menu > 0 && (int) $selection >= 0) {
            $categoryObj = $this->get_single('menucategory', array('id' => $category))->row();
            $menuObj = $this->get_single('menu', array('id' => $menu))->row();
            $selectionObj = $this->get_single('menuselection', array('id' => $selection))->row();
            if (empty($this->getCart())) {
                if (!$this->getOrderType()) {
                    $this->setOrderType('collection');
                }
                $this->initiateDiscountPlan();
                $this->initiateMultiDisocunt();
                $this->initiateFreeDishOffer();
                $cart = $this->getCart();
                $bag = $this->addBag();
                if ($bag['price'] > 0) {
                    array_push($cart, $bag);
                }
                $item = $this->addItem($categoryObj, $menuObj, $selectionObj, $rule);
                array_push($cart, $item);
                $this->setCart($cart);
                return $this->getMaxKey();
            } else {
                $line = $this->preCheckItem($categoryObj, $menuObj, $selectionObj);
                $cart = $this->getCart();
                if ($line != null && $line >= '0' && !empty($cart[$line])) {
                    $cart[$line]['qty'] = $cart[$line]['qty'] + 1;
                    $cart[$line]['total'] = $this->getItemTotalPrice($cart[$line]['price'], $cart[$line]['qty'], $cart[$line]['Topping']);
                    $this->setCart($cart);
                    return $line;
                } else {
                    $item = $this->addItem($categoryObj, $menuObj, $selectionObj, $rule);
                    $cart = $this->getCart();
                    array_push($cart, $item);
                    $this->setCart($cart);
                    return $this->getMaxKey();
                }
            }
        } else {
            return array();
        }
    }

    private function preCheckItem($categoryObj, $menuObj, $selectionObj) {
        $cart = $this->getCart();
        $doesMatch = false;
        $matchedLine = null;
        if (!empty($cart)) {
            foreach ($cart as $key => $item) {
                if (isset($selectionObj) && !empty($selectionObj) && count((array) $selectionObj > 0)) {
                    if ($item['category'] == $categoryObj->id && $item['menu'] == $menuObj->id && $item['selection'] == $selectionObj->id) {
                        if ($this->getSetItme($categoryObj, $menuObj, $selectionObj) || $this->getTopping() || $this->getModifier()) {
                            $doesMatch = false;
                        } else {
                            $doesMatch = true;
                        }
                        if ($item['isFree'] === 'yes') {
                            $doesMatch = false;
                        }
                        if ($doesMatch) {
                            $matchedLine = "$key";
                            break;
                        }
                    } else {
                        continue;
                    }
                } else {
                    if ($item['category'] == $categoryObj->id && $item['menu'] == $menuObj->id && $item['selection'] == '0') {
                        if ($this->getSetItme($categoryObj, $menuObj, $selectionObj) || $this->getTopping() || $this->getModifier()) {
                            $doesMatch = false;
                        } else {
                            $doesMatch = true;
                        }
                        if ($item['isFree'] === 'yes') {
                            $doesMatch = false;
                        }
                        if ($doesMatch) {
                            $matchedLine = "$key";
                            break;
                        }
                    } else {
                        continue;
                    }
                }
            }
        }
        return $matchedLine;
    }

    public function initiateFreeDishOffer() {
        $itemOffer = $this->get_list('discountitem', array('status' => 3), null, null, 0, 'order', 'DESC')->result();
        if (!empty($itemOffer)) {
            foreach ($itemOffer as $key => $anOffer) {
                $itemOffer[$key]->type = unserialize($anOffer->type);
                $itemOffer[$key]->item = unserialize($anOffer->item);
            }
        }
        if (!empty($itemOffer)) {
            $this->setFreeDishOffer($itemOffer);
        } else {
            $this->emptyFreeDishOffer();
        }
    }

    public function manageFreeDish() {
        if (!empty($this->getFreeDishOffer())) {
            $subtotal = $this->subtotal();
            $rule = array();
            foreach ($this->getFreeDishOffer() as $anOffer) {
                if ($subtotal >= $anOffer->order) {
                    $rule['id'] = $anOffer->id;
                    $rule['order'] = $anOffer->order;
                    $rule['qty'] = $anOffer->qty;
                    break;
                }
            }
            $preRule = $this->getActiveDishOfferRule();
            if (!empty($rule)) {
                if (!empty($preRule)) {
                    if ($preRule['id'] != $rule['id']) {
                        $this->setActiveDishOfferRule($rule);
                        $this->removeThePreviousFreeDishItem();
                    }
                } else {
                    $this->setActiveDishOfferRule($rule);
                }
            } else {
                if (!empty($this->getActiveDishOfferRule())) {
                    $this->removeThePreviousFreeDishItem();
                }
                $this->emptyActiveDishOfferRule();
            }
        }
    }

    private function removeThePreviousFreeDishItem() {
        $activeDishOfferRule = $this->getActiveDishOfferRule();
        if (!empty($activeDishOfferRule)) {
            $cart = $this->getCart();
            foreach ($cart as $key => $item) {
                if ($item['isFree'] === 'yes') {
                    if ($item['isFreeRule'] === $activeDishOfferRule['order']) {
                        if ($this->getFreeItemCurrentQty() >= $activeDishOfferRule['qty']) {
                            $this->remove($key);
                        }
                    } else {
                        $this->remove($key);
                    }
                }
            }
            $this->getCart();
        }
    }

    private function getFreeItemCurrentQty() {
        $cart = $this->getCart();
        $rule = $this->getActiveDishOfferRule();
        $count = 0;
        foreach ($cart as $item) {
            if ($item['isFree'] === 'yes' && $rule['order'] == $item['isFreeRule']) {
                $count++;
            }
        }
        return $count;
    }

    public function getDishOfferItem() {
        $rule = $this->getActiveDishOfferRule();
        $data = array();
        $status = false;
        if (!empty($rule)) {
            $cart = $this->getCart();
            foreach ($cart as $item) {
                if ($item['isFree'] == 'yes' && $item['isFreeRule'] == $rule['order']) {
                    if ($this->getFreeItemCurrentQty() < $rule['qty']) {
                        $status = false;
                    } else {
                        $status = true;
                    }
                    break;
                }
            }
        }
        if (!empty($rule) && !$status && $this->getFreeDishOffer()) {
            foreach ($this->getFreeDishOffer() as $anOffer) {
                if ($anOffer->id === $rule['id']) {
                    $data['items'] = $anOffer->item;
                    $data['title'] = $anOffer->title;
                    $data['qty'] = $anOffer->qty - $this->getFreeItemCurrentQty();
                    $data['order'] = $anOffer->order;
                    break;
                }
            }
        }
        $itemArray = array();
        if (!empty($data['items'])) {
            foreach ($data['items'] as $item) {
                $explodeItemIds = explode('_', $item);
                $newItem = array();
                $newItem['category'] = $explodeItemIds[0];
                $newItem['menu'] = $explodeItemIds[1];
                $newItem['selection'] = $explodeItemIds[2];
                if ($explodeItemIds[2] > 0) {
                    $newItem['itemName'] = get_title('menuselection', array('id' => $explodeItemIds[2])) . '-' . get_title('menu', array('id' => $explodeItemIds[1]));
                } else {
                    $newItem['itemName'] = get_title('menu', array('id' => $explodeItemIds[1]));
                }
                array_push($itemArray, $newItem);
            }
        }
        $data['items'] = $itemArray;
        return $data;
    }

    public function getFreeDishOffer() {
        if ($this->session->userdata('freeDishOffer')) {
            return $this->session->userdata('freeDishOffer');
        } else {
            return array();
        }
    }

    public function setFreeDishOffer($data) {
        $this->session->set_userdata('freeDishOffer', $data);
    }

    public function emptyFreeDishOffer() {
        $this->session->unset_userdata('freeDishOffer');
    }

    public function getActiveDishOfferRule() {
        if ($this->session->userdata('activeDishOfferRule')) {
            return $this->session->userdata('activeDishOfferRule');
        } else {
            return array();
        }
    }

    public function setActiveDishOfferRule($data) {
        $this->session->set_userdata('activeDishOfferRule', $data);
    }

    public function emptyActiveDishOfferRule() {
        $this->session->unset_userdata('activeDishOfferRule');
    }

    public function getMaxKey() {
        if (!empty($this->getCart())) {
            return max(array_keys($this->getCart()));
        } else {
            return '';
        }
    }

    private function addItem($categoryObj, $menuObj, $selectionObj, $rule) {
        if ($rule == 'yes') {
            $this->removeThePreviousFreeDishItem();
        }
        $item = array(
            'category' => $categoryObj->id,
            'categoryTitle' => $categoryObj->title,
            'type' => $categoryObj->type,
            'menu' => $menuObj->id,
            'menuTitle' => $menuObj->title,
            'selection' => count((array) $selectionObj) > 0 ? $selectionObj->id : '0',
            'selectionTitle' => count((array) $selectionObj) > 0 ? $selectionObj->title : '',
            'price' => $rule == 'yes' ? 0 : count((array) $selectionObj) > 0 ? $this->getItemPrice($selectionObj) : $this->getItemPrice($menuObj),
            'taxOption' => $rule == 'yes' ? 0 : count((array) $selectionObj) > 0 ? $selectionObj->tax_option : $menuObj->tax_option,
            'tax' => $rule == 'yes' ? 0 : count((array) $selectionObj) > 0 ? $selectionObj->tax : $menuObj->tax,
            'taxPercent' => $rule == 'yes' ? 0 : count((array) $selectionObj) > 0 ? $this->getItemTax($selectionObj->tax_option, $categoryObj, $menuObj, $selectionObj) : $this->getItemTax($menuObj->tax_option, $categoryObj, $menuObj, new stdClass()),
            'discountOption' => $rule == 'yes' ? 0 : count((array) $selectionObj) > 0 ? $selectionObj->discount_option : $menuObj->discount_option,
            'discount' => $rule == 'yes' ? 0 : count((array) $selectionObj) > 0 ? $this->getItemDiscount($selectionObj->discount_option, $categoryObj, $menuObj, $selectionObj) : $this->getItemDiscount($menuObj->discount_option, $categoryObj, $menuObj, new stdClass()),
            'qty' => '1',
            'newQty' => '0',
            'sent' => 'no',
            'setItem' => $this->getSetItme($categoryObj, $menuObj, $selectionObj),
            'Topping' => $this->getTopping(),
            'modifier' => $this->getModifier(),
            'printat' => count((array) $selectionObj) > 0 ? $selectionObj->printat : $menuObj->printat,
            'isFree' => $rule == 'yes' ? 'yes' : 'no',
            'isFreeRule' => $rule == 'yes' ? $this->getActiveDishOfferRule()['order'] : 'no',
            'total' => $rule == 'yes' ? 0 : $this->getItemTotalPrice($this->getItemPrice(count((array) $selectionObj) > 0 ? $selectionObj : $menuObj), 1, $this->getTopping()),
            'comment' => $this->getItemComment()
        );
        return $item;
    }

    private function addBag() {
        $item = array(
            'category' => 9999,
            'categoryTitle' => "Carier Bag",
            'type' => "Kitchen",
            'menu' => 99999,
            'menuTitle' => "Bag",
            'selection' => '0',
            'selectionTitle' => '',
            'price' => 0,
            'taxOption' => 0,
            'tax' => 0,
            'taxPercent' => 0,
            'discountOption' => 0,
            'discount' => 0,
            'qty' => '1',
            'newQty' => '0',
            'sent' => 'no',
            'setItem' => array(),
            'Topping' => array(),
            'modifier' => array(),
            'printat' => 9999,
            'isFree' => 'no',
            'isFreeRule' => 'no',
            'total' => 0,
            'comment' => ''
        );
        return $item;
    }

    private function getItemPrice($item) {
        if ($item->out_price > 0) {
            return $item->out_price;
        } else {
            return $item->base_price;
        }
    }

    private function getItemTotalPrice($unitPrice, $qty, $topping) {
        $itemPrice = to_currency_no_money($unitPrice * $qty);
        if (!empty($topping)) {
            $toppingTotal = 0;
            foreach ($topping as $aTop) {
                $toppingTotal += $aTop['total'];
            }
            $itemPrice += $toppingTotal;
        }
        return $itemPrice;
    }

    private function getItemTax($option, $categoryObj, $menuObj, $selectionObj) {
        if ($option == 2) {
            $taxObj = $this->get_single('branch', array('id' => $this->session->userdata('branch')), array('default_tax', 'taxIsIncluded'))->row();
            if ($taxObj->taxIsIncluded == 'yes') {
                return 0;
            } else {
                return $taxObj->default_tax;
            }
        } else if ($option == 3) {
            return $categoryObj->tax;
        } else if ($option == 4) {
            return $menuObj->tax;
        } else if ($option == 5) {
            return $selectionObj->tax;
        } else {
            return '0';
        }
    }

    private function getItemDiscount($option, $categoryObj, $menuObj, $selectionObj) {
        if ($option == 2) {
            return $this->get_single('branch', array('id' => $this->session->userdata('branch')))->row()->default_discount;
        } else if ($option == 4) {
            return $categoryObj->discount;
        } else if ($option == 5) {
            return $menuObj->discount;
        } else if ($option == 6) {
            return $selectionObj->discount;
        } else {
            return '0';
        }
    }

    public function plus($line) {
        $cart = $this->getCart();
        $cart[$line]['qty'] += 1;
        $cart[$line]['total'] = $this->getItemTotalPrice($cart[$line]['price'], $cart[$line]['qty'], $cart[$line]['Topping']);
        $this->setCart($cart);
        return $line;
    }

    public function minus($line) {
        $cart = $this->getCart();
        if ($cart[$line]['qty'] > 1) {
            $cart[$line]['qty'] -= 1;
            $cart[$line]['total'] = $this->getItemTotalPrice($cart[$line]['price'], $cart[$line]['qty'], $cart[$line]['Topping']);
            $line = $line;
        } else {
            if ($cart[$line]['menuTitle'] !== "Bag") {
                unset($cart[$line]);
                $line = '';
            }
        }
        $this->setCart($cart);
        return $line;
    }

    public function remove($line) {
        $cart = $this->getCart();
        unset($cart[$line]);
        $this->setCart($cart);
        return '';
    }

    public function getCart() {
        if ($this->session->userdata('cart')) {
            return $this->session->userdata('cart');
        } else {
            return array();
        }
    }

    public function setCart($data) {
        $this->session->set_userdata('cart', $data);
    }

    public function emptyCart() {
        $this->session->unset_userdata('cart');
    }

    public function getTopping() {
        if ($this->session->userdata('Topping')) {
            return $this->session->userdata('Topping');
        } else {
            return array();
        }
    }

    public function setTopping($data) {
        $this->session->set_userdata('Topping', $data);
    }

    public function emptyTopping() {
        $this->session->unset_userdata('Topping');
    }

    public function setItemComment($data) {
        $this->session->set_userdata('itemComment', $data);
    }

    public function getItemComment() {
        if ($this->session->userdata('itemComment')) {
            return $this->session->userdata('itemComment');
        } else {
            return '';
        }
    }

    public function emptyItemComment() {
        $this->session->unset_userdata('itemComment');
    }

    public function plusItemAttribute($line, $category, $id) {
        $cart = $this->getCart();
        if (!empty($cart[$line]['Topping'])) {
            foreach ($cart[$line]['Topping'] as $key => $aTop) {
                if ((int) $category === (int) $aTop['category'] && (int) $id === (int) $aTop['id']) {
                    if ($cart[$line]['Topping'][$key]['price'] > 0) {
                        $cart[$line]['Topping'][$key]['qty'] += 1;
                        $cart[$line]['Topping'][$key]['total'] = $cart[$line]['Topping'][$key]['qty'] * $cart[$line]['Topping'][$key]['price'];
                    }
                }
            }
        }
        $this->setCart($cart);
        $cart = $this->getCart();
        $cart[$line]['total'] = $this->getItemTotalPrice($cart[$line]['price'], $cart[$line]['qty'], $cart[$line]['Topping']);
        $this->setCart($cart);
        return $line;
    }

    public function getModifier() {
        if ($this->session->userdata('modifier')) {
            return $this->session->userdata('modifier');
        } else {
            return array();
        }
    }

    public function setModifier($data) {
        $this->session->set_userdata('modifier', $data);
    }

    public function emptyModifier() {
        $this->session->unset_userdata('modifier');
    }

    public function getSetItme($categoryObj, $menuObj, $selectionObj) {
        if ($this->session->userdata('setItem')) {
            return $this->session->userdata('setItem');
        } else {
            $fixedDealItems = array();
            $fixedDealItemCollection = null;
            if (isset($selectionObj) && !empty($selectionObj) && count((array) $selectionObj) > 0) {
                if ($selectionObj->deal_type === '3') {
                    $fixedDealItemCollection = $this->get_list('menufixeddeal', array('deal_category' => $categoryObj->id, 'deal_menu' => $menuObj->id, 'deal_selection' => $selectionObj->id))->result();
                }
            } else {
                if ($menuObj->deal_type === '3') {
                    $fixedDealItemCollection = $this->get_list('menufixeddeal', array('deal_category' => $categoryObj->id, 'deal_menu' => $menuObj->id, 'deal_selection' => '0'))->result();
                }
            }
            if (!empty($fixedDealItemCollection)) {
                foreach ($fixedDealItemCollection as $item) {
                    $fixedDealItem = array();
                    $menuObjIn = $this->get_single('menu', array('id' => $item->menu))->row();
                    $selectionObjIn = null;
                    if ($item->selection > 0) {
                        $selectionObjIn = $this->get_single('menuselection', array('id' => $item->selection))->row();
                    }
                    $fixedDealItem['id'] = $item->id;
                    $fixedDealItem['title'] = $selectionObjIn ? $selectionObjIn->title . '-' . $menuObjIn->title : $menuObjIn->title;
                    $fixedDealItem['qty'] = $item->qty;
                    $fixedDealItem['set'] = $item->deal;
                    $fixedDealItem['setTitle'] = count((array) $selectionObj) > 0 ? $selectionObj->title . '-' . $menuObj->title : $menuObj->title;
                    array_push($fixedDealItems, $fixedDealItem);
                }
            }
            return $fixedDealItems;
        }
    }

    public function setSetItme($data) {
        $this->session->set_userdata('setItem', $data);
    }

    public function emptySetItme() {
        $this->session->unset_userdata('setItem');
    }

    public function subtotal() {
        $subtotal = 0;
        $cart = $this->getCart();
        if (!empty($cart)) {
            foreach ($cart as $item) {
                $subtotal += $item['total'];
            }
        }
        return to_currency_no_money($subtotal);
    }

    public function tax() {
        $tax = 0;
        $cart = $this->getCart();
        if (!empty($cart)) {
            foreach ($cart as $item) {
                if ($item['taxPercent'] > 0) {
                    $tax += ($item['taxPercent'] / 100) * $item['total'];
                }
            }
        }
        return to_currency_no_money($tax);
    }

    public function discount() {
        $discount = 0;
        $cart = $this->getCart();
        if (!empty($cart)) {
            foreach ($cart as $item) {
                $rel = $this->checkMultiDiscount($item);
                if ($rel == '3' || $rel == '0') {
                    if ($item['discountOption'] == '2') {
                        $discount += $this->discountOnDefault($item['total']);
                    } else if ($item['discountOption'] == '4') {
                        $discount += $this->discountOnCategory($item['category'], $item['total']);
                    } else if ($item['discountOption'] == '5') {
                        $discount += $this->discountOnMenu($item['menu'], $item['total']);
                    } else if ($item['discountOption'] == '6') {
                        $discount += $this->discountOnSelection($item['selection'], $item['total']);
                    } else {
                        $discount += 0;
                    }
                }
            }
        }
        if ($this->promoDisocunt() > 0) {
            if (!empty($this->getPromoDiscountPlan())) {
                $plan = $this->getPromoDiscountPlan();
                if ($plan['rel'] == '2') {
                    return to_currency_no_money($discount);
                } else {
                    return to_currency_no_money($discount + $this->discountOnPlan());
                }
            } else {
                return to_currency_no_money($discount + $this->discountOnPlan());
            }
        } else {
            return to_currency_no_money($discount + $this->discountOnPlan());
        }
    }

    private function discountOnDefault($itemTotal) {
        $defaultDiscount = $this->get_single('branch', array('id' => $this->session->userdata('branch')))->row()->default_discount;
        return to_currency_no_money(($defaultDiscount / 100) * $itemTotal);
    }

    private function discountOnCategory($category, $itemTotal) {
        $categoryDiscount = $this->get_single('menucategory', array('id' => $category))->row()->discount;
        return to_currency_no_money(($categoryDiscount / 100) * $itemTotal);
    }

    private function discountOnMenu($menu, $itemTotal) {
        $menuDiscount = $this->get_single('menu', array('id' => $menu))->row()->discount;
        return to_currency_no_money(($menuDiscount / 100) * $itemTotal);
    }

    private function discountOnSelection($selection, $itemTotal) {
        $selectionDiscount = $this->get_single('menuselection', array('id' => $selection))->row()->discount;
        return to_currency_no_money(($selectionDiscount / 100) * $itemTotal);
    }

    private function discountOnPlan() {
        $kitchenTotal = 0;
        $barTotal = 0;
        $bakeryTotal = 0;
        $drinksTotal = 0;
        $discount = 0;
        $onfunc = 0;
        $planDiscountTotal = 0;
        $discountPlan = $this->getDiscountPlan();
        if (!empty($discountPlan)) {
            foreach ($discountPlan as $aDiscountPlan) {
                if ($this->subtotal() >= $aDiscountPlan->min_order) {
                    $discount = $aDiscountPlan->discount;
                    $onfunc = $aDiscountPlan->onfunc;
                    $cart = $this->getCart();
                    foreach ($cart as $item) {
                        $rel = $this->checkMultiDiscount($item);
                        if ($rel == '3' || $rel == '0') {
                            if ($item['type'] === 'kitchen' && $item['discountOption'] == 3) {
                                $kitchenTotal += $item['total'];
                            }
                            if ($item['type'] === 'bar' && $item['discountOption'] == 3) {
                                $barTotal += $item['total'];
                            }
                            if ($item['type'] === 'bakery' && $item['discountOption'] == 3) {
                                $bakeryTotal += $item['total'];
                            }
                            if ($item['type'] === 'drinks' && $item['discountOption'] == 3) {
                                $drinksTotal += $item['total'];
                            }
                        }
                    }
                    break;
                }
            }
        }

        if ($onfunc == 3 && $discount > 0) {
            $planDiscountTotal += $discount;
        }
        if ($onfunc == 2 && $discount > 0) {
            if ($kitchenTotal > 0) {
                $planDiscountTotal += ($kitchenTotal * $discount) / 100;
            }
            if ($barTotal > 0) {
                $planDiscountTotal += ($barTotal * $discount) / 100;
            }
            if ($bakeryTotal > 0) {
                $planDiscountTotal += ($bakeryTotal * $discount) / 100;
            }
            if ($drinksTotal > 0) {
                $planDiscountTotal += ($drinksTotal * $discount) / 100;
            }
        }
        return $planDiscountTotal;
    }

    public function initiateDiscountPlan() {
        $daysArray = array('Sun' => '1', 'Mon' => '2', 'Tue' => '3', 'Wed' => '4', 'Thu' => '5', 'Fri' => '6', 'Sat' => '7');
        $plans = $this->db->where(array('start_date <=' => date('Y-m-d'), 'end_date >=' => date('Y-m-d'), 'branch' => $this->session->userdata('branch')))->order_by('min_order', 'DESC')->get('discountplan')->result();
        $resultantPlans = array();
        if (!empty($plans)) {
            foreach ($plans as $plan) {
                $onApp = unserialize($plan->onapp);
                $onDay = $plan->onday = unserialize($plan->onday);
                $orderType = $this->getOrderType();
                $orderTypeNumber = 0;
                if ($orderType === 'delivery') {
                    $orderTypeNumber = 4;
                }
                if ($orderType === 'collection') {
                    $orderTypeNumber = 5;
                }
                if (in_array(6, $onApp) && in_array($orderTypeNumber, $onApp) && in_array($daysArray[date('D')], $onDay)) {
                    $nowTime = strtotime(date('h:i a'));
                    $startTime = strtotime(date('h:i a', strtotime($plan->start_time)));
                    $endTime = strtotime(date('h:i a', strtotime($plan->end_time)));
                    if ($nowTime >= $startTime && $nowTime <= $endTime) {
                        $newPlan = new stdClass();
                        $newPlan->min_order = $plan->min_order;
                        $newPlan->discount = $plan->discount;
                        $newPlan->onfunc = $plan->onfunc;
                        $newPlan->onitem = unserialize($plan->onitem);
                        $newPlan->delivery = in_array(4, $onApp) ? 'yes' : 'no';
                        $newPlan->collection = in_array(5, $onApp) ? 'yes' : 'no';
                        array_push($resultantPlans, $newPlan);
                    }
                }
            }
        }
        $this->setDiscountPlan($resultantPlans);
    }

    public function setDiscountPlan($data) {
        $this->session->set_userdata('discountPlan', $data);
    }

    public function getDiscountPlan() {
        if ($this->session->userdata('discountPlan')) {
            return $this->session->userdata('discountPlan');
        } else {
            return array();
        }
    }

    public function emptyDiscountPlan() {
        $this->session->unset_userdata('discountPlan');
    }

    public function promoDisocunt() {
        $promoDiscountTotal = 0;
        if ($this->getPromoDiscountPlan()) {
            $plan = $this->getPromoDiscountPlan();
            if ($this->subtotal() >= $plan['min_order']) {
                $kitchenTotal = 0;
                $barTotal = 0;
                $bakeryTotal = 0;
                $drinksTotal = 0;
                foreach ($this->getCart() as $item) {
                    $rel = $this->checkMultiDiscount($item);
                    if ($rel == '3' || $rel == '0') {
                        if ($item['type'] === 'kitchen') {
                            $kitchenTotal += $item['total'];
                        }
                        if ($item['type'] === 'bar') {
                            $barTotal += $item['total'];
                        }
                        if ($item['type'] === 'bakery') {
                            $bakeryTotal += $item['total'];
                        }
                        if ($item['type'] === 'drinks') {
                            $drinksTotal += $item['total'];
                        }
                    }
                }
                if ($plan['onfunc'] == 3 && $plan['discount'] > 0) {
                    $planDiscountTotal += $plan['discount'];
                }
                if ($plan['onfunc'] == 2 && $plan['discount'] > 0) {
                    if ($kitchenTotal > 0 && in_array('kitchen', $plan['onitem'])) {
                        $promoDiscountTotal += ($kitchenTotal * $plan['discount'] ) / 100;
                    }
                    if ($barTotal > 0 && in_array('bar', $plan['onitem'])) {
                        $promoDiscountTotal += ($barTotal * $plan['discount'] ) / 100;
                    }
                    if ($bakeryTotal > 0 && in_array('bakery', $plan['onitem'])) {
                        $promoDiscountTotal += ($bakeryTotal * $plan['discount'] ) / 100;
                    }
                    if ($drinksTotal > 0 && in_array('drinks', $plan['onitem'])) {
                        $promoDiscountTotal += ($drinksTotal * $plan['discount'] ) / 100;
                    }
                }
            }
        }
        return to_currency_no_money($promoDiscountTotal);
    }

    public function getPromoDiscountPlan() {
        if ($this->session->userdata('promoDiscountPlan')) {
            return $this->session->userdata('promoDiscountPlan');
        } else {
            return array();
        }
    }

    public function setPromoDiscountPlan($data) {
        $this->session->set_userdata('promoDiscountPlan', $data);
    }

    public function emptyPromoDiscountPlan() {
        $this->session->unset_userdata('promoDiscountPlan');
    }

    public function multiDiscount() {
        $MultiDiscountTotal = 0;
        $cart = $this->getCart();
        $mutiDiscountRule = $this->getDiscountMulti();
        if (!empty($mutiDiscountRule)) {
            foreach ($mutiDiscountRule as $aRule) {
                foreach ($cart as $item) {
                    if ($aRule->category == $item['category'] && $aRule->menu == $item['menu'] && $aRule->selection == $item['selection'] && $this->subtotal() >= $aRule->min_order) {
                        if ($item['qty'] >= ($aRule->buy + $aRule->get)) {
                            if ($aRule->buy == $aRule->get) {
                                $mask = $item['qty'] / 2;
                                $MultiDiscountTotal += $mask * $item['price'];
                            } else {
                                if ($aRule->buy <= 1) {
                                    $mask = $item['qty'] * $aRule->get;
                                    $MultiDiscountTotal += $mask * $item['price'];
                                } else {
                                    $mask = $item['qty'] / $aRule->buy;
                                    $MultiDiscountTotal += ($mask * $aRule->get) * $item['price'];
                                }
                            }
                        }
                    }
                }
            }
        }
        return $MultiDiscountTotal;
    }

    private function checkMultiDiscount($item) {
        $rel = '0';
        $mutiDiscountRule = $this->getDiscountMulti();
        if (!empty($mutiDiscountRule)) {
            foreach ($mutiDiscountRule as $aRule) {
                if ($aRule->category === $item['category'] && $aRule->menu === $item['menu'] && $aRule->selection === $item['selection'] && $this->subtotal() >= $aRule->min_order) {
                    $rel = $aRule->rel;
                    break;
                }
            }
        }
        return $rel;
    }

    public function initiateMultiDisocunt() {
        $daysArray = array('Sun' => '1', 'Mon' => '2', 'Tue' => '3', 'Wed' => '4', 'Thu' => '5', 'Fri' => '6', 'Sat' => '7');
        $plans = $this->db->where(array('start_date <=' => date('Y-m-d'), 'end_date >=' => date('Y-m-d'), 'branch' => $this->session->userdata('branch')))->order_by('min_order', 'DESC')->get('discountmulti')->result();
        $resultantPlans = array();
        if (!empty($plans)) {
            foreach ($plans as $plan) {
                $onApp = unserialize($plan->onapp);
                $onDay = $plan->onday = unserialize($plan->onday);
                $orderType = $this->getOrderType();
                $orderTypeNumber = 0;
                if ($orderType === 'delivery') {
                    $orderTypeNumber = 4;
                }
                if ($orderType === 'collection') {
                    $orderTypeNumber = 5;
                }
                if (in_array(6, $onApp) && in_array($orderTypeNumber, $onApp) && in_array($daysArray[date('D')], $onDay)) {
                    $nowTime = strtotime(date('h:i a'));
                    $startTime = strtotime(date('h:i a', strtotime($plan->start_time)));
                    $endTime = strtotime(date('h:i a', strtotime($plan->end_time)));
                    if ($nowTime >= $startTime && $nowTime <= $endTime) {
                        $newPlan = new stdClass();
                        $newPlan->min_order = $plan->min_order;
                        $newPlan->buy = $plan->buy;
                        $newPlan->get = $plan->get;
                        $newPlan->category = $plan->category;
                        $newPlan->menu = $plan->menu;
                        $newPlan->selection = $plan->selection;
                        $newPlan->rel = $plan->rel;
                        $newPlan->delivery = in_array(4, $onApp) ? 'yes' : 'no';
                        $newPlan->collection = in_array(5, $onApp) ? 'yes' : 'no';
                        array_push($resultantPlans, $newPlan);
                    }
                }
            }
        }
        $this->setDiscountMulti($resultantPlans);
    }

    public function setDiscountMulti($data) {
        $this->session->set_userdata('discountMulti', $data);
    }

    public function getDiscountMulti() {
        if ($this->session->userdata('discountMulti')) {
            return $this->session->userdata('discountMulti');
        } else {
            return array();
        }
    }

    public function emptyDiscountMulti() {
        $this->session->unset_userdata('discountMulti');
    }

    public function getServiceCharge() {
        return  0;
    }

    public function total() {
        if ($this->subtotal() > 0) {
            return to_currency_no_money(($this->subtotal() + $this->tax() + $this->getDeliveryCharge() + $this->getServiceCharge()) - ($this->discount() + $this->multiDiscount() + $this->promoDisocunt()));
        } else {
            return to_currency_no_money(($this->subtotal() + $this->tax() + $this->getDeliveryCharge()) - ($this->discount() + $this->multiDiscount() + $this->promoDisocunt()));
        }
    }

    public function deliveryChargeSetup($postcode, $deliveryAreaObj, $apiObj, $distanceObj) {
        if ($distanceObj['status'] === 'OK') {
            $paidDistance = $distanceObj['miles'] - $apiObj->freeRadius;
            $paidDistanceCost = 0;
            if ($paidDistance > 0) {
                $paidDistanceCost = $paidDistance * $apiObj->costPerMile;
            }
            $this->setDeliveryCharge($paidDistanceCost);
        } else {
            $this->setDeliveryCharge($deliveryAreaObj->delivery_charge);
        }
        $this->setDeliveryPostcode($postcode);
        $this->setDeliveryMinOrder($deliveryAreaObj->min_order);
        $this->setDeliveryWaitingTime($deliveryAreaObj->waiting_time);
        $this->setOrderType('delivery');
        if ($this->getOrderType() === 'delivery') {
            $this->initiateDiscountPlan();
            $this->initiateMultiDisocunt();
            $this->initiateFreeDishOffer();
        }
        return array('status' => $this->getDeliveryMinOrder() ? true : false, 'minimumOrderAmount' => $this->getDeliveryMinOrder(), 'DeliveryFee' => $this->getDeliveryCharge());
    }

    public function setDeliveryPostcode($data) {
        $this->session->set_userdata('deliveryPostcode', $data);
    }

    public function getDeliveryPostcode() {
        if ($this->session->userdata('deliveryPostcode')) {
            return to_currency_no_money($this->session->userdata('deliveryPostcode'));
        } else {
            return to_currency_no_money(0);
        }
    }

    public function emptyDeliveryPostcode() {
        $this->session->unset_userdata('deliveryPostcode');
    }

    public function setDeliveryMinOrder($data) {
        $this->session->set_userdata('deliveryMinOrder', $data);
    }

    public function getDeliveryMinOrder() {
        if ($this->session->userdata('deliveryMinOrder')) {
            return to_currency_no_money($this->session->userdata('deliveryMinOrder'));
        } else {
            return to_currency_no_money(0);
        }
    }

    public function emptyDeliveryMinOrder() {
        $this->session->unset_userdata('deliveryMinOrder');
    }

    public function setDeliveryWaitingTime($data) {
        $this->session->set_userdata('deliveryWaitingTime', $data);
    }

    public function getDeliveryWaitingTime() {
        if ($this->session->userdata('deliveryWaitingTime')) {
            return to_currency_no_money($this->session->userdata('deliveryWaitingTime'));
        } else {
            return false;
        }
    }

    public function emptyDeliveryWaitingTime() {
        $this->session->unset_userdata('deliveryWaitingTime');
    }

    public function getDeliveryCharge() {
        if ($this->session->userdata('deliveryCharge')) {
            return to_currency_no_money($this->session->userdata('deliveryCharge'));
        } else {
            return to_currency_no_money(0);
        }
    }

    public function setDeliveryCharge($data) {
        $this->session->set_userdata('deliveryCharge', $data);
    }

    public function emptyDeliveryCharge() {
        $this->session->unset_userdata('deliveryCharge');
    }

    public function getOrderDetail() {
        if ($this->session->userdata('customerOrderDetail')) {
            return $this->session->userdata('customerOrderDetail');
        } else {
            return array();
        }
    }

    public function setOrderDetail($data) {
        $this->session->set_userdata('customerOrderDetail', $data);
    }

    public function emptyOrderDetail() {
        $this->session->unset_userdata('customerOrderDetail');
    }

    public function clearCart() {
        $this->emptyDiscountPlan();
        $this->emptyDiscountMulti();
        $this->emptyModifier();
        $this->emptySetItme();
        $this->emptyTopping();
        $this->emptyItemComment();
        $this->emptyDeliveryCharge();
        $this->emptyDeliveryMinOrder();
        $this->emptyDeliveryWaitingTime();
        $this->emptyFreeDishOffer();
        $this->emptyActiveDishOfferRule();
        $this->emptyCart();
        $this->emptyOrderType();
        $this->emptyOrderDetail();
        $this->clearPreOrder();
    }

    public function clearOnAddToCart() {
        $this->emptySetItme();
        $this->emptyTopping();
        $this->emptyModifier();
        $this->emptyItemComment();
    }

    public function setPreOrder($data) {
        $this->session->set_userdata('preorder', $data);
    }

    public function getPreOrder() {
        if ($this->session->userdata('preorder')) {
            return true;
        } else {
            return false;
        }
    }

    public function clearPreOrder() {
        $this->session->unset_userdata('preorder');
    }

}
