<?php

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

class Orders extends Gkpos_Controller {

    function __construct() {
        parent::__construct();
        $this->site_title = $this->config->item('company');
        $this->load->model('Entry_Model');
        if (!$this->Entry_Model->is_logged_in()) {
            redirect('gkpos/entry');
        }
        $this->load->helper('gkpos');
        $this->load->model('Orders_Model');
    }

    public function index($orderId = '') {
        $this->load->model('Orders_Model');
        $this->page_title = 'Gkpos | order';
        $this->current_section = "menu order";
        $this->body_class[] = "pos-menu selection order";
        $offset = 0;
        $data = array();
        if ($this->cache->get('pos_listcategory_' . $offset)) {
            $result = $this->cache->get('pos_listcategory_' . $offset);
            $data['categories'] = $result['categories'];
        } else {
            $data['categories'] = $this->Orders_Model->get_list('gkpos_category', array('status' => 1), array('id', 'title', 'type', 'print_option', 'order', 'content'), null, $offset, 'order', 'ASC');
        }
        $data['current_page'] = "orders";
        $data['showcategory'] = $this->Orders_Model->showcategory();
        $this->render_page('gkpos/orders/index', $data);
    }

    public function indexajax($order_id = '', $accessor = null) {
        $offset = 0;
        $data = array();
        if ($this->cache->get('pos_listcategory_' . $offset)) {
            $result = $this->cache->get('pos_listcategory_' . $offset);
            $data['categories'] = $result['categories'];
        } else {
            $data['categories'] = $this->Orders_Model->get_list('gkpos_category', array('status' => 1), array('id', 'title', 'type', 'print_option', 'order', 'content'), null, $offset, 'order', 'ASC');
        }
        $data['showcategory'] = $this->Orders_Model->showcategory();
        $data['current_page'] = "orders";
        if ($order_id != '' || $order_id != null) {
            $data['currentOrderObj'] = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
            $this->Orders_Model->set_current_ordertype($data['currentOrderObj']->order_type);
            if (isset($accessor) && $accessor != $data['currentOrderObj']->created_by) {
                if ($this->Orders_Model->exists('gkpos_user', 'id', $accessor)) {
                    $this->db->update('gkpos_order', array('created_by' => $accessor), array('id' => $order_id));
                }
            }
            $data['payments_option'] = $this->Orders_Model->get_payment_options();
            $this->Orders_Model->set_current_orderid($order_id);
            if (!$this->Orders_Model->get_discount($order_id)) {
                $this->Orders_Model->initiate_discount($order_id, $data['currentOrderObj']->order_type);
            }
            if (!$this->Orders_Model->get_servicecharge($order_id)) {
                $this->Orders_Model->initiate_service_charge($order_id);
            }
            if (!$this->Orders_Model->get_vat($order_id)) {
                $this->Orders_Model->initiate_vat($order_id);
            }
            if (!$this->Orders_Model->get_cc_fee($order_id)) {
                $this->Orders_Model->initiate_cc_fee($order_id);
            }
            if ($data['currentOrderObj']->paid_status == 1) {
                $this->Orders_Model->initiate_payments($order_id);
            }
            if ($data['currentOrderObj']->bogo_discount > 0) {
                $this->Orders_Model->initiate_bogo_discount($order_id);
            }

            if ($data['currentOrderObj']->order_type == 'delivery' && !$this->Orders_Model->get_deliveryplan($order_id)) {
                $this->Orders_Model->initiate_deliveryplan($order_id);
                $DeliveryPlanArray = $this->Orders_Model->get_deliveryplan($order_id);
                if (!empty($DeliveryPlanArray)) {
                    $existingDelTime = new DateTime($data['currentOrderObj']->delivery_time);
                    $existingDelTime->sub(new DateInterval('PT45M'));
                    $existingDelTime->add(new DateInterval('PT' . $DeliveryPlanArray['delivery_time'] . 'M'));
                    $this->db->update('gkpos_order', array('delivery_time' => $existingDelTime->format('Y-m-d H:i:s')), array('id' => $order_id));
                    $data['currentOrderObj'] = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
                }
            } else {
                if ($this->Orders_Model->get_deliveryplan($order_id)) {
                    $this->Orders_Model->clear_deliveryplan($order_id);
                    $this->Orders_Model->clear_deliveryplan_amount($order_id);
                }
            }
            $data['firstTaken'] = $this->Orders_Model->get_list('gkpos_order_detail', array('order_id' => $order_id), array('first_taken', 'created_by'), 1, 0, 'first_taken', 'ASC');
            $data['lastTaken'] = $this->Orders_Model->get_list('gkpos_order_detail', array('order_id' => $order_id), array('last_taken', 'created_by'), 1, 0, 'last_taken', 'DESC');
        }
        $this->load->view('gkpos/orders/ajaxindex', $data, false);
    }

    public function listcategory($segment = 0) {
        $data = array();
        if ($this->cache->get('pos_listcategory_' . $segment)) {
            $data = $this->cache->get('pos_listcategory_' . $segment);
            $data['cache'] = 'yes';
        } else {
            $limit = $this->config->item('gk_category_line_page');
            $data['cat_counter'] = $records = $this->Orders_Model->count_rows('gkpos_category', array('status' => 1));
            $pages = $records > $limit ? $records / $limit : 0;
            $ajaxpages = is_double($pages) ? floor($pages) + 1 : $pages;
            if ($segment <= $ajaxpages) {
                $offset = $segment * $limit;
                $result = $this->Orders_Model->get_list('gkpos_category', array('status' => 1), null, $limit, $offset, 'order', 'ASC');
                $data['categories'] = $result;
                $data['ajaxpages'] = $ajaxpages;
                $data['segment'] = $segment;
                $data['prevPage'] = $segment > 0 ? $segment - 1 : 0;
                $data['nextPage'] = $segment + 1;
                if ($segment + 1 > $pages) {
                    $data['nextPage'] = 0;
                }
            } else {
                $data['categories'] = array();
                $data['ajaxpages'] = 0;
                $data['segment'] = 0;
                $data['prevPage'] = 0;
                $data['nextPage'] = 1;
            }
            $this->cache->save('pos_listcategory_' . $segment, $data, 18000);
            $data['cache'] = 'no';
        }
        $data['order_id'] = $this->Orders_Model->get_current_orderid();
        $this->load->view('gkpos/orders/listcategory', $data);
    }

    public function listmenus($segment = 0) {
        $category = $this->input->post('category');
        $index = $this->input->post('index');
        $is_special = $this->input->post('is_special');
        if ($this->cache->get('pos_menupage_' . $category . '_' . $segment)) {
            $data = $this->cache->get('pos_menupage_' . $category . '_' . $segment);
        } else {
            if ($is_special == 'yes') {
                $data = $this->_get_deals($segment, $category);
            } else {
                $data = $this->_get_menus($segment, $category);
            }
            $data['category'] = $cateGory = $this->Orders_Model->get_list('gkpos_category', array('id' => $category));
            $this->cache->save('pos_menupage_' . $category . '_' . $segment, $data, 0);
        }
        $data['index'] = $index;
        $data['order_id'] = $this->Orders_Model->get_current_orderid();
        $data['currentOrderType'] = $this->Orders_Model->get_current_ordertype();

        $data['breadcrumb_category'] = $category;
        $data['breadcrumb_index'] = $index;
        $data['breadcrumb_is_special'] = $is_special;
        $data['breadcrumb_offset'] = $segment;

        if ($data['category'][0]->is_special == 'yes') {
            $this->load->view('gkpos/orders/listdeals', $data);
        } else {
            $this->load->view('gkpos/orders/listmenus', $data);
        }
    }

    private function _get_menus($segment, $category) {
        $data = array();
        $limit = $this->config->item('gk_menu_line_page');
        $data['menu_counter'] = $records = $this->Orders_Model->count_rows('gkpos_menu', array('status' => 1, 'category' => $category));
        $pages = $records > $limit ? $records / $limit : 1;
        $ajaxpages = is_double($pages) ? floor($pages) + 1 : $pages;
        if ($segment <= $ajaxpages) {
            $offset = $segment * $limit;
            $result = $this->Orders_Model->get_list('gkpos_menu', array('status' => 1, 'category' => $category), null, $limit, $offset, 'order', 'ASC');
            $data['menus'][$category] = $result;
            $selections = array();
            foreach ($result as $menu) {
                $selections[$menu->category][$menu->id] = $this->Orders_Model->get_list('gkpos_selection', array('category' => $menu->category, 'menu' => $menu->id, 'status' => 1), null, null, 0, 'order', 'ASC');
            }
            $data['selections'] = $selections;
            $data['menuAjaxpages'] = $ajaxpages;
            $data['menuSegment'] = $segment;
            $data['menuPrevPage'] = $segment > 0 ? $segment - 1 : 0;
            $data['menuNextPage'] = $records <= $limit ? 0 : $segment + 1;
            if ($segment + 1 > $pages) {
                $data['menuNextPage'] = 0;
            }
        } else {
            $data['menus'] = array();
            $data['menuAjaxpages'] = 1;
            $data['menuSegment'] = 0;
            $data['menuPrevPage'] = 0;
            $data['menuNextPage'] = $records <= $limit ? 0 : 1;
        }
        return $data;
    }

    private function _get_deals($segment, $category) {
        $data = array();
        $limit = $this->config->item('gk_menu_line_page');
        $data['menu_counter'] = $records = $this->Orders_Model->count_rows('meal_deal', array('status' => 1));
        $pages = $records > $limit ? $records / $limit : 1;
        $ajaxpages = is_double($pages) ? floor($pages) + 1 : $pages;
        if ($segment <= $ajaxpages) {
            $offset = $segment * $limit;
            $result = $this->Orders_Model->get_list('meal_deal', array('status' => 1), null, $limit, $offset, 'order', 'ASC');
            $data['allDeals'] = $result;
            $deal_sets = array();
            $deal_set_menus = array();
            if (!empty($data['allDeals'])) {
                foreach ($data['allDeals'] as $deal) {
                    $deal_sets[$deal->id] = $dealSets = $this->Site_Model->get_list('meal_deal_set', array('deal' => $deal->id), null, null, 0, 'id', 'ASC');
                    foreach ($dealSets as $dealSet) {
                        $deal_set_menus[$deal->id][$dealSet->id] = $this->Site_Model->get_list('meal_deal_menu', array('deal' => $deal->id, 'set' => $dealSet->id), null, null, 0, 'menu', 'ASC');
                    }
                }
            }

            $data['deal_sets'] = $deal_sets;
            $data['deal_set_menus'] = $deal_set_menus;
            $data['menuAjaxpages'] = $ajaxpages;
            $data['menuSegment'] = $segment;
            $data['menuPrevPage'] = $segment > 0 ? $segment - 1 : 0;
            $data['menuNextPage'] = $records <= $limit ? 0 : $segment + 1;
            if ($segment + 1 > $pages) {
                $data['menuNextPage'] = 0;
            }
        } else {
            $data['allDeals'] = array();
            $data['deal_set_menus'] = array();
            $data['deal_sets'] = array();
            $data['deal_toppings'] = array();
            $data['menuAjaxpages'] = 1;
            $data['menuSegment'] = 0;
            $data['menuPrevPage'] = 0;
            $data['menuNextPage'] = $records <= $limit ? 0 : 1;
        }
        return $data;
    }

    public function addtocart() {
        $data = $this->input->post();
        $result = $this->Orders_Model->addtocart($data);
        echo json_encode($result);
    }

    public function loadcart($order_id = null) {
        $data = [];
        $isCartEmty = true;
        $isFoodCartEmpty = true;
        $isNonFoodCartEmpty = true;
        $isDbcEmpty = true;
        $isDbcFoodCartEmpty = true;
        $isDbcNonFoodCartEmpty = true;

        if ($this->input->post('order_id')) {
            $order_id = $this->input->post('order_id');
        }
        if ($order_id != null || $order_id = '') {
            $data['currentOrderObj'] = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));

            $this->Orders_Model->set_current_orderid($order_id);
            if (!$this->Orders_Model->get_cc_fee($order_id)) {
                $this->Orders_Model->initiate_cc_fee($order_id);
            }
            if (!$this->Orders_Model->get_servicecharge($order_id)) {
                $this->Orders_Model->initiate_service_charge($order_id);
            }
            if (!$this->Orders_Model->get_vat($order_id)) {
                $this->Orders_Model->initiate_vat($order_id);
            }

            if ($data['currentOrderObj']->order_type == 'delivery' && !$this->Orders_Model->get_deliveryplan($order_id)) {
                $this->Orders_Model->initiate_deliveryplan($order_id);
            }
            //check DBC cart data
            if (!$this->Orders_Model->get_cart_db($order_id)) {
                $cart_db = $this->Orders_Model->get_list_array('gkpos_order_detail', array('order_id' => $order_id));
                if (!empty($cart_db)) {
                    $items = array();
                    foreach ($cart_db as $key => $item) {
                        $items[$item['line']] = $item;
                    }
                    $this->Orders_Model->set_cart_db($order_id, $items);
                }
            }
            $cart_items = $this->Orders_Model->get_cart($order_id);
            $food_cart_items = array();
            $beverage_cart_items = array();
            if (!empty($cart_items)) {
                $isCartEmty = false;
                foreach ($cart_items as $key => $itemObj) {
                    if ($itemObj ['category_type'] == '1') {
                        $food_cart_items[] = $itemObj;
                    } else {
                        $beverage_cart_items[] = $itemObj;
                    }
                }
            }
            $data['isCartEmty'] = $isCartEmty;
            $data['order_id'] = $order_id;
            $data['maxLine'] = $this->get_maxline($order_id);
            $data['foodCart'] = $food_cart_items;
            $data['isFoodCartEmpty'] = $isFoodCartEmpty = empty($food_cart_items) ? true : false;
            $data['nonFoodCart'] = $beverage_cart_items;
            $data['isNonFoodCartEmpty'] = $isNonFoodCartEmpty = empty($beverage_cart_items) ? true : false;
            //Manage existing db cart items 
            $dbc_food_cart_items = array();
            $dbc_beverage_cart_items = array();
            $dbcart_items = $this->Orders_Model->get_cart_db($order_id);
            if (!empty($dbcart_items)) {
                $isDbcEmpty = false;
                foreach ($dbcart_items as $key => $itemObj) {
                    if ($itemObj ['category_type'] == '1') {
                        $dbc_food_cart_items[] = $itemObj;
                    } else {
                        $dbc_beverage_cart_items[] = $itemObj;
                    }
                }

                $data['dbcFoodCart'] = $dbc_food_cart_items;
                $isDbcFoodCartEmpty = empty($dbc_food_cart_items) ? true : false;
                $data['dbcNonFoodCart'] = $dbc_beverage_cart_items;
                $isDbcNonFoodCartEmpty = empty($dbc_beverage_cart_items) ? true : false;
            }
            $data['isDbcEmpty'] = $isDbcEmpty;
            $data['newString'] = $isDbcEmpty && $data['currentOrderObj']->grand_total < 1 ? '' : 'New';
            $data['hasDBCart'] = $isDbcEmpty && $data['currentOrderObj']->grand_total < 1 ? false : true;
            $data['isDbcFoodCartEmpty'] = $isDbcFoodCartEmpty;
            $data['isDbcNonFoodCartEmpty'] = $isDbcNonFoodCartEmpty;
            $data['has_new'] = 'no';
            if ($this->Orders_Model->get_cart_new($order_id)) {
                $data['has_new'] = $this->Orders_Model->get_cart_new($order_id);
            }
            $data['has_update'] = 'no';
            if ($this->Orders_Model->get_updated_cart($order_id)) {
                $data['has_update'] = $this->Orders_Model->get_updated_cart($order_id);
            }

            $cart = array(
                'food_cart' => $food_cart_items,
                'nonfood_cart' => $beverage_cart_items,
                'db_food_cart' => $dbc_food_cart_items,
                'db_nonfood_cart' => $dbc_beverage_cart_items
            );
            if ($this->Orders_Model->get_discount_on($order_id)) {
                $data['cart_discount_order_amount'] = $this->_discount_min_order($cart, $this->Orders_Model->get_discount_on($order_id));
                $this->Orders_Model->set_order_total($order_id, $data['cart_discount_order_amount']);
                if (!$this->Orders_Model->get_discount($order_id)) {
                    $this->Orders_Model->initiate_discount($order_id, $data['currentOrderObj']->order_type);
                }
            } else {
                $this->Orders_Model->initiate_discount($order_id, $data['currentOrderObj']->order_type);
                $data['cart_discount_order_amount'] = $this->_discount_min_order($cart, $this->Orders_Model->get_discount_on($order_id));
                $this->Orders_Model->set_order_total($order_id, $data['cart_discount_order_amount']);
            }

            if ($this->Orders_Model->get_discount_on($order_id)) {
                $data['cart_discount_order_amount'] = $this->_discount_min_order($cart, $this->Orders_Model->get_discount_on($order_id));
                $this->Orders_Model->set_order_total($order_id, $data['cart_discount_order_amount']);
            }
            if ($this->Orders_Model->get_discount($order_id) && $this->Orders_Model->get_min_order_discounted_amount($order_id)) {
                if ($this->Orders_Model->get_min_order_discounted_amount($order_id) > $this->Orders_Model->get_order_total($order_id)) {
                    $this->Orders_Model->clear_discount($order_id);
                }
            }
            $this->Orders_Model->calculate_bogo_discount_amount($order_id);
            $data['bogo_discount'] = $this->Orders_Model->get_bogodiscount_amount($order_id);
        }

        $this->load->view('gkpos/orders/cartajax', $data, false);
    }

    private function _discount_min_order($cart, $type) {
        $food_total = 0;
        $nonfood_total = 0;
        if (!empty($cart['food_cart'])) {
            $hereTotal = 0;
            foreach ($cart['food_cart'] as $fc) {
                $hereTotal += $fc ['quantity'] * $fc ['price'];
            }
            $food_total += $hereTotal;
        }
        if (!empty($cart['db_food_cart'])) {
            $hereTotal = 0;
            foreach ($cart['db_food_cart'] as $dfc) {
                $hereTotal += $dfc ['quantity'] * $dfc ['price'];
            }
            $food_total += $hereTotal;
        }

        if (!empty($cart['nonfood_cart'])) {
            $hereTotal = 0;
            foreach ($cart['nonfood_cart'] as $nfc) {
                $hereTotal += $nfc['quantity'] * $nfc['price'];
            }
            $nonfood_total += $hereTotal;
        }
        if (!empty($cart['db_nonfood_cart'])) {
            $hereTotal = 0;
            foreach ($cart['db_nonfood_cart'] as $dnfc) {
                $hereTotal += $dnfc['quantity'] * $dnfc['price'];
            }
            $nonfood_total += $hereTotal;
        }
        if ($type == 'food') {
            return $food_total;
        }
        if ($type == 'nonfood') {
            return $nonfood_total;
        }
        if ($type == 'both') {
            return $food_total + $nonfood_total;
        }
    }

    public function get_maxline($order_id) {
        $currentCartItems = $this->Orders_Model->get_cart($order_id);
        $dbcart_items = $this->Orders_Model->get_cart_db($order_id);
        $maxLine = 0;
        if (empty($currentCartItems)) {
            if (empty($dbcart_items)) {
                $maxLine = $maxLine;
            } else {
                foreach ($dbcart_items as $line => $item) {
                    if ($maxLine <= $item['line']) {
                        $maxLine = $item['line'];
                    }
                }
            }
        } else {
            foreach ($currentCartItems as $line => $item) {
                if ($maxLine <= $item['line']) {
                    $maxLine = $item['line'];
                }
            }
        }
        return $maxLine;
    }

    public function updatecart() {
        $line = $this->input->post('line');
        $action = $this->input->post('action');
        $order_id = $this->input->post('order_id');
        $quantity = $this->input->post('quantity');
        if ($order_id && $line && $action) {
            $items = $this->Orders_Model->get_cart($order_id);
            if ($items != null && array_key_exists($line, $items)) {
                $action_method = 'cart_item_' . $action;
                $result = $this->Orders_Model->$action_method($order_id, $line, $quantity);
                echo json_encode($result);
            } else {
                $items_db = array();
                $items_db = $this->Orders_Model->get_cart_db($order_id);
                if ($items_db != null && array_key_exists($line, $items_db)) {
                    $action_method = 'dbcart_item_' . $action;
                    $result = $this->Orders_Model->$action_method($order_id, $line, $quantity);
                    echo json_encode($result);
                }
            }
        }
    }

    public function updatecarttoppings() {
        $title = $this->input->post('title');
        $price = $this->input->post('price');
        $line = $this->input->post('line');
        $order_id = $this->input->post('order_id');
        if ($order_id && $line && $title && $price) {
            $items = $this->Orders_Model->get_cart($order_id);
            if ($items != null && array_key_exists($line, $items)) {
                if ($items[$line]['toppings'] != null) {
                    $items[$line]['toppings'] .= ',' . $title;
                } else {
                    $items[$line]['toppings'] = $title;
                }
                $items[$line]['price'] += $price;
                $this->Orders_Model->set_cart($order_id, $items);
                $this->Orders_Model->set_cart_new($order_id, 'yes');
                echo json_encode(array('success' => true, 'order_id' => $order_id, 'line' => $line));
            } else {
                $items = $this->Orders_Model->get_cart_db($order_id);
                if ($items != null && array_key_exists($line, $items)) {
                    if ($items[$line]['toppings'] != null) {
                        $items[$line]['toppings'] .= ',' . $title;
                    } else {
                        $items[$line]['toppings'] = $title;
                    }
                    $items[$line]['price'] += $price;
                    $this->Orders_Model->set_cart_db($order_id, $items);
                    $this->Orders_Model->set_cart_new($order_id, 'yes');
                    echo json_encode(array('success' => true, 'order_id' => $order_id, 'line' => $line));
                }
            }
        }
    }

    public function addservicecharge() {
        $order_id = $this->input->post('order_id');
        $data = $this->prepareData();
        $this->Orders_Model->set_servicecharge($order_id, $data);
        $this->Orders_Model->set_updated_cart($order_id, 'yes');
        $success = false;
        if ($this->Orders_Model->get_servicecharge($order_id)) {
            $amount = calculate_service_charge($order_id, $this->Orders_Model->get_subtotal($order_id), $this->Orders_Model->get_servicecharge($order_id));
            if ($amount) {
                // get service charge from session and save it into order service charge table 
                $servicecharge_data = $this->Orders_Model->get_servicecharge($order_id);
                $service_charge_success = false;
                if (!empty($servicecharge_data)) {
                    $servicecharge_data['amount'] = $this->Orders_Model->get_servicecharge_amount($order_id);
                    $servicecharge_data_exists = $this->Orders_Model->exists('gkpos_order_servicecharge', 'order_id', $order_id);
                    if ($servicecharge_data_exists) {
                        unset($servicecharge_data['order_id']);
                        $success = $service_charge_success = $this->Orders_Model->save_servicecharge($servicecharge_data, $order_id);
                    } else {
                        $success = $service_charge_success = $this->Orders_Model->save_servicecharge($servicecharge_data);
                    }
                }
            }
        }
        $this->Orders_Model->clear_servicecharge($order_id);
        $this->Orders_Model->clear_servicecharge_amount($order_id);
        echo json_encode(array('success' => $success, 'order_id' => $order_id));
    }

    public function adddiscount() {
        $order_id = $this->input->post('order_id');
        $data = $this->prepareData();
        $success = false;
        if (!isset($data['func'])) {
            $data['func'] = 1;
        }
        if (!isset($data['food']) && !isset($data['nonfood'])) {
            $data['food'] = 'yes';
            $data['nonfood'] = 'yes';
        }
        if (!isset($data['food'])) {
            $data['food'] = Null;
        }
        if (!isset($data['nonfood'])) {
            $data['nonfood'] = Null;
        }
        $this->Orders_Model->set_discount_on($order_id, array('food' => $data['food'], 'nonfood' => $data['nonfood']));
        $this->Orders_Model->set_min_order_discounted_amount($order_id, 1);
        $this->Orders_Model->set_discount($order_id, $data);
        $this->Orders_Model->set_updated_cart($order_id, 'yes');
        if ($this->Orders_Model->get_discount($order_id) && $this->Orders_Model->get_updated_cart($order_id)) {
            $discount_data = $this->Orders_Model->get_discount($order_id);
            calculate_discount($order_id, $this->Orders_Model->get_subtotal($order_id), $this->Orders_Model->get_foodtotal($order_id), $this->Orders_Model->get_nonfoodtotal($order_id), $discount_data);
            $discount_amount = $this->Orders_Model->get_discount_amount($order_id);
            $discount_data['amount'] = $discount_amount > 0 ? $discount_amount : '0';
            $discount_data_exists = $this->Orders_Model->exists('gkpos_order_discount', 'order_id', $order_id);
            if ($discount_data_exists) {
                $discount_data['amount'] = $this->Orders_Model->get_discount_amount($order_id);
                unset($discount_data['order_id']);
                $success = $this->Orders_Model->save_discount($discount_data, $order_id);
            } else {
                $success = $this->Orders_Model->save_discount($discount_data);
            }
        }
        echo json_encode(array('success' => $success, 'order_id' => $order_id));
    }

    public function save_order($order_id = null, $sent_option = null, $is_sent = null) {
        $order_id = $this->input->post('order_id') ? $this->input->post('order_id') : $order_id;
        $sent_option = $this->input->post('sent') ? $this->input->post('sent') : $sent_option;
        if ($order_id && $this->Orders_Model->get_subtotal($order_id) > 0 && $this->Orders_Model->get_total($order_id) > 0) {
            $success = false;
            //get current order object 
            $existingOrder = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
            // get Dbc cart items update from session and update existing items on the board 
            $cart_db = $this->Orders_Model->get_cart_db($order_id);
            $has_db_category_type_one = false;
            $has_cart_category_type_one = false;
            if (!empty($cart_db) && $is_sent == null) {
                $this->db->update('gkpos_order_detail', array('changed' => NULL), array('order_id' => $order_id));
                $db_cart = $this->Orders_Model->get_list_array('gkpos_order_detail', array('order_id' => $order_id), array('id', 'line', 'menu_title', 'selection_title', 'quantity'));
                //order the db cart according to line 
                $db_cart_arr = array();
                foreach ($db_cart as $key => $item) {
                    $db_cart_arr[$item['line']] = $item;
                }
                $changed = 'no';
                foreach ($cart_db as $line => $item) {
                    if ($has_db_category_type_one == false && $item['category_type'] == 1) {
                        $has_db_category_type_one = true;
                    }
                    if ($db_cart_arr[$line]['id'] == $item['id'] && $db_cart_arr[$line]['quantity'] != $item['quantity']) {
                        $changed = 'yes';
                        //get the previous quantity 
                        $pre_qty = $db_cart_arr[$line]['quantity'];
                        //get the current quantity 
                        $current_qty = $item['quantity'];
                        //get the different quantity
                        $new_qty = $current_qty - $pre_qty;
                        $success = $this->db->update('gkpos_order_detail', array('quantity' => $current_qty, 'quantity_new' => $new_qty, 'changed' => $changed, 'last_taken' => date('Y-m-d H:i:s')), array('id' => $item['id'], 'order_id' => $order_id));
                    }
                    if ($db_cart_arr[$line]['id'] == $item['id'] && $db_cart_arr[$line]['selection_title'] != $item['selection_title']) {
                        $changed = 'yes';
                        $success = $this->db->update('gkpos_order_detail', array('selection_title' => $item['selection_title'], 'changed' => $changed, 'last_taken' => date('Y-m-d H:i:s')), array('id' => $item['id'], 'order_id' => $order_id));
                    } else {
                        if ($db_cart_arr[$line]['id'] == $item['id'] && $db_cart_arr[$line]['menu_title'] != $item['menu_title']) {
                            $changed = 'yes';
                            $success = $this->db->update('gkpos_order_detail', array('menu_title' => $item['menu_title'], 'changed' => $changed, 'last_taken' => date('Y-m-d H:i:s')), array('id' => $item['id'], 'order_id' => $order_id));
                        }
                    }
                    if ($changed == 'no') {
                        $success = $this->db->update('gkpos_order_detail', array('quantity_new' => 'NULL', 'changed' => 'NULL',), array('id' => $item['id'], 'order_id' => $order_id));
                    }
                }
            }
            // get current cart items from session and save it into order_detail_table
            $cart_data = $this->Orders_Model->get_cart($order_id);
            if (!empty($cart_data) && $is_sent == null) {
                foreach ($cart_data as $item) {
                    $item = $this->prepareGkposData($item);
                    if ($has_cart_category_type_one == false && $item['category_type'] == 1) {
                        $has_cart_category_type_one = true;
                    }
                    $item['changed'] = 'yes';
                    $item['first_taken'] = date('Y-m-d H:i:s');
                    $item['last_taken'] = date('Y-m-d H:i:s');
                    $item['created_by'] = $this->session->userdata('gkpos_userid');
                    $id = $this->Orders_Model->save_cart($item);
                    $changed = $id ? 'yes' : 'no';
                    $success = $id ? true : false;
                }
            }
            // get discount from session and save it into order discount table 
            $discount_data = $this->Orders_Model->get_discount($order_id);
            if (!empty($discount_data)) {
                $discount_amount = $this->Orders_Model->get_discount_amount($order_id);
                $discount_data['amount'] = $discount_amount > 0 ? $discount_amount : '0';
                $discount_data_exists = $this->Orders_Model->exists('gkpos_order_discount', 'order_id', $order_id);
                if ($discount_data_exists) {
                    $discount_data['amount'] = $this->Orders_Model->get_discount_amount($order_id);
                    unset($discount_data['order_id']);
                    $this->Orders_Model->save_discount($discount_data, $order_id);
                } else {
                    $this->Orders_Model->save_discount($discount_data);
                }
            }
            // get vat from session and save it into order vat table 
            $vat_data = $this->Orders_Model->get_vat($order_id);
            if (!empty($vat_data)) {
                $vat_data['amount'] = $this->Orders_Model->get_vat_amount($order_id);
                $vat_data_exists = $this->Orders_Model->exists('gkpos_order_vat', 'order_id', $order_id);
                if ($vat_data_exists) {
                    unset($vat_data['order_id']);
                    $this->Orders_Model->save_vat($vat_data, $order_id);
                } else {
                    $this->Orders_Model->save_vat($vat_data);
                }
            }
            // get service charge from session and save it into order service charge table 
            $servicecharge_data = $this->Orders_Model->get_servicecharge($order_id);
            if (!empty($servicecharge_data)) {
                $servicecharge_data['amount'] = $this->Orders_Model->get_servicecharge_amount($order_id);
                $servicecharge_data_exists = $this->Orders_Model->exists('gkpos_order_servicecharge', 'order_id', $order_id);
                if ($servicecharge_data_exists) {
                    unset($servicecharge_data['order_id']);
                    $this->Orders_Model->save_servicecharge($servicecharge_data, $order_id);
                } else {
                    $this->Orders_Model->save_servicecharge($servicecharge_data);
                }
            }
            // get promo from session 
            $is_printed = 1;
            $has_print = 0;
            if ($is_sent == null) {
                if (($existingOrder->order_type != 'table' || $existingOrder->order_type != 'bar') && $changed == 'yes') {
                    $is_printed = 0;
                    $has_print = 1;
                } else {
                    if (($existingOrder->order_type == 'table' || $existingOrder->order_type == 'bar') && $changed == 'yes' && ($has_db_category_type_one || $has_cart_category_type_one) && $sent_option == 'all') {
                        $is_printed = 0;
                        $has_print = 1;
                    }
                    if ($existingOrder->order_type == 'table' || $existingOrder->order_type == 'bar' && $changed == 'yes' && $has_cart_category_type_one && $sent_option == 'new') {
                        $is_printed = 0;
                        $has_print = 1;
                    }
                }
            }

            //manage bogo dicount 
            $bogo_discount = $this->Orders_Model->get_bogo_discount($order_id) ? $this->Orders_Model->get_bogo_discount($order_id) : array();
            $bogo_discount_amount = $this->Orders_Model->get_bogodiscount_amount($order_id) ? $this->Orders_Model->get_bogodiscount_amount($order_id) : to_currency_no_money(0);
            if ($bogo_discount_amount > 0 && !empty($bogo_discount)) {
                $this->db->delete('bogo_discount', array('order_id' => $order_id));
                foreach ($bogo_discount as $key => $bgamount) {
                    $this->db->insert('bogo_discount', array('order_id' => $order_id, 'item' => $key, 'value' => $bgamount));
                }
            } else {
                $this->db->delete('bogo_discount', array('order_id' => $order_id));
            }


            $orderInfoArray = array();
            $orderInfoArray['status'] = 2;
            $orderInfoArray['order_total'] = $this->Orders_Model->get_subtotal($order_id);
            $orderInfoArray['grand_total'] = $this->Orders_Model->get_total($order_id);
            $orderInfoArray['cc_fee'] = $this->Orders_Model->get_cc_fee($order_id);
            $orderInfoArray['delivery_charge'] = $this->Orders_Model->get_deliveryplan_amount($order_id);
            $orderInfoArray['is_printed'] = $is_printed;
            $orderInfoArray['has_print'] = $has_print;
            $orderInfoArray['sent_option'] = $sent_option;
            $orderInfoArray['bogo_discount'] = $bogo_discount_amount;

            $success = $this->db->update('gkpos_order', $orderInfoArray, array('id' => $order_id));
            if ($success && $is_sent == null) {
                $message = $this->lang->line('gkpos_common_print_sent_successfully');
                $this->Orders_Model->clear_all($order_id);
            }
            if ($success && $is_sent != null) {
                $message = $this->lang->line('gkpos_update_success');
                $this->Orders_Model->clear_all($order_id);
            }
            echo json_encode(array('success' => $success, 'order_id' => $order_id, 'message' => $message));
        } else {
            $this->save_order($order_id, $sent_option);
        }
    }

    public function cart_post_update() {
        $order_id = $this->input->post('order_id');
        if ($this->Orders_Model->get_cart_db($order_id)) {
            $this->db->trans_start();
            $this->db->delete('gkpos_order_discount', array('order_id' => $order_id));
            $this->db->delete('gkpos_order_payment', array('order_id' => $order_id));
            $this->db->delete('gkpos_order_servicecharge', array('order_id' => $order_id));
            $this->db->delete('gkpos_order_vat', array('order_id' => $order_id));
            $this->db->trans_complete();
            if ($this->db->trans_status()) {
                //$this->Orders_Model->get_updated_cart($order_id);
                $this->save_order($order_id, 'all', 'no');
            }
        } else {
            $this->Orders_Model->clear_updated_cart($order_id);
            if (!$this->Orders_Model->get_updated_cart($order_id)) {
                echo json_encode(array('success' => true, 'order_id' => $order_id, 'message' => $this->lang->line('gkpos_update_success')));
            } else {
                echo json_encode(array('success' => false, 'order_id' => $order_id, 'message' => $this->lang->line('gkpos_update_success')));
            }
        }
    }

    public function addpayment() {
        $order_id = $this->input->post('order_id');
        $method = $this->input->post('method');
        $amount = $this->input->post('amount');
        if ($method && $amount) {
            $payments = $this->Orders_Model->get_payments($order_id);
            if (isset($payments[$method])) {
                $payments[$method]['amount'] = to_currency_no_money(bcadd($payments[$method]['amount'], $amount, PRECISION));
            } else {
                $payment = array(
                    'method' => $method,
                    'amount' => to_currency_no_money($amount),
                    'code' => isset($_POST['code']) ? $this->input->post('code') : NULL
                );
                $payments [$method] = $payment;
            }
            $this->Orders_Model->set_payments($order_id, $payments);
            echo json_encode(array('success' => true, 'payments' => $this->Orders_Model->get_payments($order_id), 'dueAmount' => $this->Orders_Model->get_amount_due($order_id)));
        } else {
            echo json_encode(array('success' => false));
        }
    }

    public function deletepayment() {
        $order_id = $this->input->post('order_id');
        $method = $this->input->post('method');
        if ($this->Orders_Model->delete_payment($order_id, $method)) {
            echo json_encode(array('success' => true, 'payments' => $this->Orders_Model->get_payments($order_id), 'dueAmount' => $this->Orders_Model->get_amount_due($order_id)));
        } else {
            echo json_encode(array('success' => false));
        }
    }

    public function get_due_amount() {
        $order_id = $this->input->post('order_id');
        echo json_encode(array('success' => true, 'dueAmount' => $this->Orders_Model->get_amount_due($order_id)));
    }

    public function checkvoucher() {
        $code = $this->input->post('code');
        $amount = $this->input->post('amount');
        $this->db->where('end >=', date('Y-m-d'));
        $this->db->where('start <=', date('Y-m-d'));
        $this->db->where('code', $code);
        $result = $this->db->get('gkpos_giftcard')->row();
        $receivedAmount = 0;
        if (!empty($result)) {
            if ($result->status == 1) {
                if ($result->balance < $amount) {
                    $receivedAmount = $result->balance;
                } else {
                    $receivedAmount = $amount;
                }
                echo json_encode(array('success' => true, 'amount' => $receivedAmount, 'result' => $result));
            } else {
                echo json_encode(array('success' => false, 'result' => $result, 'message' => 'This Voucher is dissolved or inactive'));
            }
        } else {
            echo json_encode(array('success' => false, 'result' => array(), 'message' => 'Invalid Voucher Code'));
        }
    }

    public function payandclose() {
        $order_id = $this->input->post('order_id');
        $payments = $this->Orders_Model->get_payments($order_id);
        if (!empty($payments)) {
            foreach ($payments as $payment) {
                $sales_payments_data = array(
                    'order_id' => $order_id,
                    'method' => $payment['method'],
                    'amount' => $payment['amount'],
                    'code' => $payment['code'],
                );
                $this->db->insert('gkpos_order_payment', $sales_payments_data);

                if ($payment['method'] == $this->lang->line('gkpos_payment_voucher')) {
                    $voucher = $this->db->where('code', $payment['code'])->get('gkpos_giftcard')->row();
                    $balance = $voucher->balance - $payment['amount'];
                    $status = $balance <= 0 ? 3 : 1;
                    $this->db->update('gkpos_giftcard', array('balance' => $balance, 'status' => $status), array('code' => $payment['code']));
                }
            }
            $dueAmount = $this->Orders_Model->get_amount_due($order_id);

            if ($this->db->update('gkpos_order', array('status' => 4, 'paid_status' => 1, 'change_due' => $dueAmount, 'pay_tip' => $this->input->post('pay_tip')), array('id' => $order_id))) {
                $currentOrderObj = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
                if ($currentOrderObj->order_type == 'table') {
                    $this->db->update('gkpos_table', array('guest_quantity' => '', 'is_vacant' => 1), array('id' => $currentOrderObj->table_id, 'table_number' => $currentOrderObj->table_number));
                }
                $this->Orders_Model->clear_all($order_id);
                $this->Orders_Model->empty_payments($order_id);
                $paidOrder = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
                $closingDate = null;
                $createdDate = null;
                if ($paidOrder->created) {
                    $createDateObj = new DateTime($paidOrder->created);
                    $orderTime = $createDateObj->format('h:i:s a');
                    $orderDate = $createDateObj->format('Y-m-d');
                    if (strtotime($orderTime) > strtotime('00:00:00 am') && strtotime($orderTime) < strtotime('03:00:00 am')) {
                        $newDateObj = new DateTime($orderDate);
                        $newDateObj->sub(new DateInterval('P1D'));
                        $closingDate = $newDateObj->format('Y-m-d');
                        $createDateObj->sub(new DateInterval('P1D'));
                        $createdDate = $createDateObj->format('Y-m-d') . ' ' . date('H:i:s', mktime(23, 59, 59));
                    } else {
                        $closingDate = $orderDate;
                        $createdDate = $paidOrder->created;
                    }
                    $this->db->update('gkpos_order', array('closing_date' => $closingDate, 'created' => $createdDate), array('id' => $order_id));
                }

                echo json_encode(array('success' => true, 'message' => 'paid and close successfully'));
            } else {
                echo json_encode(array('success' => false, 'message' => 'There is an internal problem in processing. Please Try again later'));
            }
        } else {
            echo json_encode(array('success' => false, 'message' => 'You have not yet made any payment'));
        }
    }

    public function get_special() {
        $term = $this->input->get('term');
        $this->db->select('title');
        $this->db->from('gkpos_special');
        $this->db->where("title LIKE '%" . $term . "%'");
        $this->db->where('status', 1);
        $this->db->order_by("title", "asc");
        $result = $this->db->get()->result();
        $customer = array_map('current', $result);
        echo json_encode($customer);
    }

    public function addmisc() {
        $success = false;
        $message = '';
        if ($this->form_validation->run('gkpos_misc') == false) {
            $success = false;
            $message = validation_errors();
            echo json_encode(array('success' => $success, 'order_id' => $order_id, 'message' => $message));
            exit();
        } else {
            $menu_title = $this->input->post('menu_title');
            $price = $this->input->post('price');
            $quantity = $this->input->post('quantity');
            $order_id = $this->input->post('order_id');
            $type = $this->input->post('type');
            $print_option = $this->input->post('print_option');
            $items = $this->Orders_Model->get_cart($order_id);
            $null_category = array();
            if (!empty($items)) {
                foreach ($items as $anitem) {
                    if ($anitem ['category'] === null) {
                        $null_category[] = $anitem['menu'];
                    }
                }
            }
            $menu = empty($null_category) ? 999999 : max($null_category) + 1;
            $curentMaxline = $this->get_maxline($order_id);
            $line = $curentMaxline + 1;
            $item = array(
                'line' => $line,
                'order_id' => $order_id,
                'category' => NULL,
                'category_title' => NULL,
                'category_print_option' => $print_option,
                'category_type' => $type,
                'is_special' => NULL,
                'deal' =>'',
                'menu' => $menu,
                'menu_title' => $menu_title,
                'selection' => NULL,
                'selection_title' => NULL,
                'quantity' => $quantity,
                'price' => $price,
                'is_special' => '',
                'set_items' => '',
                'toppings' => '',
                'bogo' => '',
                'bogo_discount_on' => ''
            );
            $items[$line] = $item;
            $this->Orders_Model->set_cart($order_id, $items);
            $setItems = $this->Orders_Model->get_cart($order_id);
            if (isset($setItems[$line]) && !empty($setItems[$line])) {
                $message = 'added successfully';
                $this->Orders_Model->set_cart_new($order_id, 'yes');
                echo json_encode(array('success' => true, 'order_id' => $order_id, 'line' => $line, 'item' => $item, 'message' => $message));
            } else {
                $message = "internal problem";
                echo json_encode(array('success' => false, 'order_id' => $order_id, 'line' => $line, 'item' => $item, 'message' => $message));
            }
        }
    }
    public function show_item_description() {
        $selection = $this->input->post('sel');
        $menu = $this->input->post('menu');
        if ((int) $selection > 0) {
            $selection = $this->db->where('id', $selection)->get('gkpos_selection')->row();
            echo json_encode(array('success' => true, 'result' => $selection, 'message' => 'ok'));
        } else {
            $menu = $this->db->where('id', $menu)->get('gkpos_menu')->row();
            echo json_encode(array('success' => true, 'result' => $menu, 'message' => 'ok'));
        }
    }

    public function convert() {
        $data['existing_type'] = $this->input->post('existing_order_type');
        $data['new_type'] = $this->input->post('new_order_type');
        $data['order_id'] = $this->input->post('order_id');
        $data['current_section'] = $data['new_type'];
        $data['current_page'] = $data['new_type'];
        $data['order_info'] = $this->Orders_Model->get_single('gkpos_order', array('id' => $data['order_id']));
        $this->load->view('gkpos/orders/conversion/' . $data['new_type'], $data, false);
    }

    public function to_collection() {
        $existing_type = $this->input->post('existing_type');
        $new_type = $this->input->post('new_type');
        $order_id = $this->input->post('order_id');
        $name = $this->input->post('name');
        $phone = $this->input->post('phone');
        $thisOrder = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
        $data = array(
            'order_type' => $new_type,
            'table_id' => NULL,
            'table_number' => NULL,
            'guest_quantity' => NULL,
            'switched_from' => $existing_type,
            'phone' => $phone,
            'name' => $name,
            'floor_or_apt' => NULL,
            'building' => NULL,
            'house' => NULL,
            'street' => NULL,
            'city' => NULL,
            'state' => NULL,
            'country' => NULL,
            'postcode' => NULL,
            'delivery_time' => $this->input->post('delivery_time'),
            'delivery_charge' => NULL,
        );


        if ($existing_type == 'table') {
            $this->db->update('gkpos_table', array('is_vacant' => '1'), array('id' => $thisOrder->table_id));
            $this->_convert_cart($order_id, 'out');
        }
        $success = $this->db->update('gkpos_order', $data, array('id' => $order_id));
        $this->Orders_Model->clear_while_conversion($order_id);
        $this->Orders_Model->set_updated_cart($order_id, 'yes');
        echo json_encode(array('success' => $success, 'order_id' => $order_id));
    }

    public function to_waiting() {
        $existing_type = $this->input->post('existing_type');
        $new_type = $this->input->post('new_type');
        $order_id = $this->input->post('order_id');
        $name = $this->input->post('name');
        $phone = $this->input->post('phone');
        $thisOrder = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
        $data = array(
            'order_type' => $new_type,
            'table_id' => NULL,
            'table_number' => NULL,
            'guest_quantity' => NULL,
            'switched_from' => $existing_type,
            'phone' => $phone,
            'name' => $name,
            'floor_or_apt' => NULL,
            'building' => NULL,
            'house' => NULL,
            'street' => NULL,
            'city' => NULL,
            'state' => NULL,
            'country' => NULL,
            'postcode' => NULL,
            'delivery_time' => NULL,
            'delivery_charge' => NULL,
        );

        if ($existing_type == 'table') {
            $this->db->update('gkpos_table', array('is_vacant' => '1'), array('id' => $thisOrder->table_id));
            $this->_convert_cart($order_id, 'out');
        }
        $success = $this->db->update('gkpos_order', $data, array('id' => $order_id));
        $this->Orders_Model->clear_while_conversion($order_id);
        $this->Orders_Model->set_updated_cart($order_id, 'yes');
        echo json_encode(array('success' => $success, 'order_id' => $order_id));
    }

    public function to_delivery() {
        $postedData = $this->input->post();
        $thisOrder = $this->Orders_Model->get_single('gkpos_order', array('id' => $postedData['order_id']));
        $now = date('Y-m-d H:i:s');
        $nowDate = new DateTime($now);
        if ($postedData['delivery_time'] != null) {
            $postedData['delivery_time'] = $postedData['delivery_time'] + 45;
            $nowDate->add(new DateInterval('PT' . $postedData['delivery_time'] . 'M'));
            $postedData['delivery_time'] = $nowDate->format('Y-m-d H:i:s');
        } else {
            $nowDate->add(new DateInterval('PT45M'));
            $postedData['delivery_time'] = $nowDate->format('Y-m-d H:i:s');
        }
        $data = $this->prepareGkposData($postedData);
        unset($data['existing_type']);
        unset($data['order_id']);
        $success = false;
        $postedData['switched_from'] = $postedData['existing_type'];
        if ($postedData['existing_type'] == 'table') {
            $data['table_id'] = NULL;
            $data['table_number'] = NULL;
            $data['guest_quantity'] = NULL;
            $success_1 = $this->db->update('gkpos_table', array('is_vacant' => '1'), array('id' => $thisOrder->table_id));
            $this->_convert_cart($postedData['order_id'], 'out');
            $success_2 = $this->db->update('gkpos_order', $data, array('id' => $postedData['order_id']));
            $success = $success_1 && $success_2 ? true : false;
        } else {
            $success = $this->db->update('gkpos_order', $data, array('id' => $postedData['order_id']));
        }
        $this->Orders_Model->clear_while_conversion($postedData['order_id']);
        $this->Orders_Model->set_updated_cart($postedData['order_id'], 'yes');
        echo json_encode(array('success' => $success, 'order_id' => $postedData['order_id']));
    }

    public function to_table() {
        $existing_type = $this->input->post('existing_type');
        $new_type = $this->input->post('order_type');
        $order_id = $this->input->post('order_id');
        $table_number = $this->input->post('table_number');
        $guest_quantity = $this->input->post('guest_quantity');
        $thisOrder = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
        if ($new_type == 'table') {
            $table_info = $this->Orders_Model->get_single('gkpos_table', array('table_number' => (int) $table_number));
            if (!empty($table_info)) {
                if ($table_info->is_vacant == '2') {
                    $table_id = $table_info->id;
                    echo json_encode(array('success' => false, 'message' => $this->lang->line('gkpos_table') . ' ' . (int) $table_number . ' ' . $this->lang->line('gkpos_table_not_vacant')));
                    exit();
                } else {
                    $data_table['modified_by'] = $this->session->userdata('gkpos_userid');
                    $data_table['guest_quantity'] = $guest_quantity;
                    $data_table['modified'] = date('Y-m-d H:i:s');
                    if ($this->db->update('gkpos_table', $data_table, array('id' => $table_info->id, 'table_number' => $table_info->table_number))) {
                        $this->_convert_cart($order_id, 'in');
                        $data = array(
                            'order_type' => $new_type,
                            'table_id' => $table_info->id,
                            'table_number' => $table_info->table_number,
                            'guest_quantity' => $data_table['guest_quantity'],
                            'switched_from' => $existing_type,
                            'phone' => NULL,
                            'name' => NULL,
                            'floor_or_apt' => NULL,
                            'building' => NULL,
                            'house' => NULL,
                            'street' => NULL,
                            'city' => NULL,
                            'state' => NULL,
                            'country' => NULL,
                            'postcode' => NULL,
                            'delivery_time' => NULL,
                            'delivery_charge' => NULL,
                        );
                        if ($this->db->update('gkpos_order', $data, array('id' => $order_id))) {
                            $this->Orders_Model->clear_while_conversion($order_id);
                            $this->Orders_Model->set_updated_cart($order_id, 'yes');
                            echo json_encode(array('success' => true, 'order_id' => $order_id));
                            exit();
                        }
                    }
                }
            } else {
                $data_table = array();
                $data_table['status'] = '1';
                $data_table['created_by'] = $this->session->userdata('gkpos_userid');
                $data_table['is_vacant'] = '2';
                $data_table['table_number'] = (int) $table_number;
                $data_table['guest_quantity'] = (int) $guest_quantity;
                $this->load->model('Gkpos_Model');
                $table_id = $this->Gkpos_Model->save_table_info($data_table);
                if ($table_id) {
                    $this->_convert_cart($order_id, 'in');
                    $data = array(
                        'order_type' => $new_type,
                        'table_id' => $table_id,
                        'table_number' => (int) $table_number,
                        'guest_quantity' => (int) $guest_quantity,
                        'switched_from' => $existing_type,
                        'phone' => NULL,
                        'name' => NULL,
                        'floor_or_apt' => NULL,
                        'building' => NULL,
                        'house' => NULL,
                        'street' => NULL,
                        'city' => NULL,
                        'state' => NULL,
                        'country' => NULL,
                        'postcode' => NULL,
                        'delivery_time' => NULL,
                        'delivery_charge' => NULL,
                    );
                    if ($this->db->update('gkpos_order', $data, array('id' => $order_id))) {
                        $this->Orders_Model->clear_while_conversion($order_id);
                        $this->Orders_Model->set_updated_cart($order_id, 'yes');
                        echo json_encode(array('success' => true, 'order_id' => $order_id));
                        exit();
                    }
                }
            }
        }
    }

    private function _convert_cart($order_id, $price_option) {
        $current_items = $this->Orders_Model->get_cart($order_id);
        $db_items = $this->Orders_Model->get_cart_db($order_id);
        if (!empty($current_items)) {
            $items = $current_items;
            foreach ($current_items as $key => $item) {
                if ($item['category'] != null && $item['menu'] != null && $item['selection'] != null) {
                    $item_info = $this->Orders_Model->get_cart_item($item['category'], $item['menu'], $item['selection']);
                    $current_items[$key]['price'] = $price_option == 'in' ? ($item_info->in_price > 0 ? $item_info->in_price : $item_info->base_price) : ($item_info->out_price > 0 ? $item_info->out_price : $item_info->base_price);
                    $items [$key] = $current_items[$key];
                } else {
                    if ($item['category'] != null && $item['menu'] != null && $item['selection'] == null) {
                        $item_info = $this->Orders_Model->get_cart_item($item['category'], $item['menu']);
                        $current_items[$key]['price'] = $price_option == 'in' ? ($item_info->in_price > 0 ? $item_info->in_price : $item_info->base_price) : ($item_info->out_price > 0 ? $item_info->out_price : $item_info->base_price);
                        $items[$key] = $current_items[$key];
                    } else {
                        $items[$key] = $item;
                    }
                }
            }
            $this->Orders_Model->set_cart($order_id, $current_items);
        }
        if (!empty($db_items)) {
            foreach ($db_items as $key => $item) {
                $price = 0;
                if ($item['category'] != null && $item['menu'] != null && $item['selection'] != null) {
                    $item_info = $this->Orders_Model->get_cart_item($item['category'], $item['menu'], $item['selection']);
                    if (!empty($item_info)) {
                        if ($price_option == 'in') {
                            $price = $item_info->in_price > 0 ? $item_info->in_price : $item_info->base_price;
                        } else {
                            $price = $item_info->out_price > 0 ? $item_info->out_price : $item_info->base_price;
                        }
                        $this->db->update('gkpos_order_detail', array('price' => $price), array('id' => $item['id']));
                    }
                } else {
                    if ($item['category'] != null && $item['menu'] != null && $item['selection'] == null) {
                        $item_info = $this->Orders_Model->get_cart_item($item['category'], $item['menu']);
                        if (!empty($item_info)) {
                            if ($price_option == 'in') {
                                $price = $item_info->in_price > 0 ? $item_info->in_price : $item_info->base_price;
                            } else {
                                $price = $item_info->out_price > 0 ? $item_info->out_price : $item_info->base_price;
                            }
                            $this->db->update('gkpos_order_detail', array('price' => $price), array('id' => $item['id']));
                        }
                    } else {
                        $price = $item['price'];
                        $this->db->update('gkpos_order_detail', array('price' => $price), array('id' => $item['id']));
                    }
                }
            }
            $this->Orders_Model->empty_cart_db($order_id);
            $this->Orders_Model->set_updated_cart($order_id, 'yes');
        }
    }

    public function print_guest_bill() {
        $order_id = $this->input->post('order_id');
        $status = (int) $this->input->post('status');
        $doesExist = $this->Orders_Model->exists('gkpos_billcopy', 'order_id', $order_id);
        $success = false;
        if ($doesExist) {
            $esxistingBillCopy = $this->db->where('order_id', $order_id)->get('gkpos_billcopy')->row();
            if ($this->db->update('gkpos_billcopy', array('status' => 0, 'print_count' => $esxistingBillCopy->print_count + 1), array('order_id' => $esxistingBillCopy->order_id))) {
                $success = $this->db->update('gkpos_order', array('status' => $status), array('id' => $order_id));
            }
        } else {
            $data = array(
                'order_id' => $order_id,
                'created' => date('Y-m-d H:i:s'),
                'created_by' => $this->session->userdata('gkpos_userid')
            );
            if ($this->db->insert('gkpos_billcopy', $data)) {
                $success = $this->db->update('gkpos_order', array('status' => $status), array('id' => $order_id));
            }
        }
        echo json_encode(array('success' => $success, 'message' => $success ? 'Print Sent Successfully' : 'Print sending Failed..'));
    }

    public function update_guest_bill_status() {
        $order_id = $this->input->post('order_id');
        $status = (int) $this->input->post('status');
        $success = false;
        if ($this->db->update('gkpos_order', array('status' => $status, 'bill_printed' => 1, 'is_printed' => 1, 'has_print' => 0, 'sent_option' => NULL), array('id' => $order_id))) {
            $this->db->update('gkpos_order_detail', array('changed' => NULL), array('order_id' => $order_id));
            $doesExist = $this->Orders_Model->exists('gkpos_billcopy', 'order_id', $order_id);
            if ($doesExist) {
                $esxistingBillCopy = $this->db->where('order_id', $order_id)->get('gkpos_billcopy')->row();
                $this->db->update('gkpos_billcopy', array('status' => 1, 'print_count' => $esxistingBillCopy->print_count + 1), array('order_id' => $esxistingBillCopy->order_id));
            } else {
                $data = array(
                    'order_id' => $order_id,
                    'created' => date('Y-m-d H:i:s'),
                    'created_by' => $this->session->userdata('gkpos_userid'),
                    'status' => 1,
                    'print_count' => $esxistingBillCopy->print_count + 1
                );
                $success = $this->db->insert('gkpos_billcopy', $data);
            }
        }
        echo json_encode(array('success' => $success, 'message' => $success ? 'Print sent Succefully' : 'Print sending Failed..'));
    }

    public function resend_to_kitchen() {
        $order_id = $this->input->post('order_id');
        $order_detailes = $this->Orders_Model->get_list('gkpos_order_detail', array('order_id' => $order_id));
        $has_category_type_one = $this->Orders_Model->get_list('gkpos_order_detail', array('order_id' => $order_id, 'category_type' => 1));
        $existingOrder = $this->Orders_Model->get_single('gkpos_order', array('id' => $order_id));
        $success = false;
        $is_printed = 1;
        $has_print = 0;
        if (!empty($order_detailes) && ($existingOrder->order_type != 'table' || $existingOrder->order_type != 'table')) {
            $is_printed = 0;
            $has_print = 1;
        } else {
            if (($existingOrder->order_type == 'table' || $existingOrder->order_type == 'bar') && !empty($has_category_type_one) && !empty($order_detailes)) {
                $is_printed = 0;
                $has_print = 1;
            }
        }
        if ($this->db->update('gkpos_order', array('is_printed' => $is_printed, 'has_print' => $has_print, 'sent_option' => 'all'), array('id' => $order_id))) {
            $success = $this->db->update('gkpos_order_detail', array('changed' => NULL), array('order_id' => $order_id));
        }
        echo json_encode(array('success' => $success, 'order_id' => $order_id, 'message' => $success ? 'Resend Successfully!' : 'Resending Failed!'));
    }

    public function get_caller_id() {
        $availableCallerIds = $this->Orders_Model->get_list('gkpos_caller', array('status' => 1));
        $missedCalls = $this->Orders_Model->get_list('gkpos_caller', array('status' => 0, 'missed_call' => 1));
        $cuurrentTime = date('Y-m-d H:i:s');
        $cuurrentTimeObject = new DateTime($cuurrentTime);
        if (!empty($availableCallerIds)) {
            foreach ($availableCallerIds as $key => $availableCallerId) {
                $availableCallerIdObj = new DateTime($availableCallerId->created);
                $interval = $availableCallerIdObj->diff($cuurrentTimeObject);
                $missed_call = $availableCallerId->missed_call == NULL ? 1 : 0;
                if ($interval->format('%s') >= 10) {
                    $this->db->update('gkpos_caller', array('status' => 0, 'missed_call' => $missed_call), array('id' => $availableCallerId->id));
                }
            }
        }
        $callerObj = $this->Orders_Model->get_list('gkpos_caller', array('status' => 1), array('caller_id'), 1, 0, 'created', 'DESC');
        $pendingBooking = $this->Orders_Model->get_single('gkpos_booking', array('status' => 0), array('id'), 1, 0, 'created_at', 'DESC');

        if (!empty($callerObj)) {
            $nameObj = $this->db->where('phone', $callerObj[0]->caller_id)->get('gkpos_customer')->row();
            $name = null;
            if (!empty($nameObj)) {
                $name = $nameObj->name;
            }
            echo json_encode(array('success' => true, 'caller_id' => $callerObj[0]->caller_id, 'name' => $name, 'missed_call' => $missedCalls, 'has_booking' => !empty($pendingBooking) ? $pendingBooking : false, 'has_pending_orders' => $this->Orders_Model->has_pending_orders()));
        } else {
            echo json_encode(array('success' => false, 'missed_call' => $missedCalls, 'has_booking' => !empty($pendingBooking) ? $pendingBooking : false, 'has_pending_orders' => $this->Orders_Model->has_pending_orders()));
        }
    }

    public function voidorder_cart($order_id) {
        if ($order_id != null || $order_id = '') {
            $this->Orders_Model->set_voidorder_status($order_id, true);
            $this->indexajax($order_id);
        }
    }

    public function empty_cart() {
        $id = $this->input->post('id');
        if ($id) {
            $this->Orders_Model->clear_while_conversion($id);
            $this->Orders_Model->empty_cart($id);
            $this->Orders_Model->clear_cart_new($id);
            echo json_encode(array('success' => true, 'order_id' => $id));
        } else {
            echo json_encode(array('success' => false, 'order_id' => $id));
        }
    }

    public function send_kitchen_note() {
        $id = $this->input->post('order_id');
        $msg = $this->input->post('delivery_note');
        $success = false;
        $message = 'Message sending Failed! Try Again';
        if ($id && $msg) {
            $success = $this->db->update('gkpos_order', array('delivery_note' => $msg), array('id' => $id));
            $message = $success ? $this->lang->line('gkpos_system_kitchen_text_success') : 'Message Sending Failed';
        }
        echo json_encode(array('success' => $success, 'message' => $message, 'order_id' => $id));
    }

    public function add_cc_fee() {
        $order_id = $this->input->post('id');
        $ccFee = $this->input->post('cc_fee');
        if ($this->Orders_Model->get_cc_fee($order_id)) {
            $this->Orders_Model->clear_cc_fee($order_id);
        }
        if ($order_id && $ccFee && !$this->Orders_Model->get_cc_fee($order_id)) {
            $this->Orders_Model->set_cc_fee($order_id, to_currency_no_money($ccFee));
        }
        if ($this->Orders_Model->get_cc_fee($order_id)) {
            $success = $this->db->update('gkpos_order', array('cc_fee' => to_currency_no_money($this->Orders_Model->get_cc_fee($order_id))), array('id' => $order_id));
            $this->Orders_Model->set_updated_cart($order_id, 'yes');
            echo json_encode(array('success' => $success, 'order_id' => $order_id, 'message' => $this->lang->line('gkpos_add_cce_fee_success_message')));
        } else {
            echo json_encode(array('success' => false, 'order_id' => $order_id, 'message' => $this->lang->line('gkpos_add_cce_fee_failed_message')));
        }
    }

    public function unlock_order() {
        $message = $this->lang->line('gkpos_order_not_exited');
        $order_id = $this->input->post('order_id');
        $order = $this->Orders_Model->get_single('gkpos_order_lookup', array('order_id' => $order_id));
        $cart = $this->Orders_Model->get_cart($order_id);
        if (!empty($cart)) {
            $success = $this->db->update('gkpos_order_lookup', array('is_locked' => 1), array('order_id' => $order_id));
        } else {
            $success = $this->db->update('gkpos_order_lookup', array('is_locked' => 0), array('order_id' => $order_id));
            $this->Orders_Model->clear_all($order_id);
        }
        if (isset($order->occupied_by) && isset($order->occupied_by) != $this->session->userdata('gkpos_userid')) {
            $this->Orders_Model->clear_all($order_id);
        }
        echo json_encode(array('success' => $success, 'message' => $success ? 'ok' : $message));
    }

    public function is_order_occupied() {
        $order_id = $this->input->post('order_id');
        $order = $this->Orders_Model->get_single('gkpos_order_lookup', array('order_id' => $order_id));
        $success = false;
        $message = $this->lang->line('gkpos_order_entry_not_found_lookup_table');
        if (!empty($order)) {
            switch ($order->is_locked) {
                case 1:
                    $success = $this->session->userdata('gkpos_userid') == $order->occupied_by;
                    $message = $this->lang->line('gkpos_order_occupied') . get_user_name($order->occupied_by);
                    break;
                case 0:
                    $success = $this->db->update('gkpos_order_lookup', array('occupied_by' => $this->session->userdata('gkpos_userid'), 'is_locked' => 1), array('order_id' => $order_id));
                    $message = 'Ok';
                    break;
                default :
                    $success = false;
                    $message = $message;
            }
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function kitchen_text_opener() {
        $data = array(
            'ktcOrderId' => $this->input->post('ktcOrderId')
        );
        $this->load->view('gkpos/orders/popups/kitchen_text', $data);
    }

    public function ccFee_opener() {
        $data = array(
            'ktcOrderId' => $this->input->post('ktcOrderId')
        );
        $this->load->view('gkpos/orders/popups/add_ccFee', $data);
    }

}
