<?php

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

class Api extends Epos_Template {

    private $branch = 0;

    function __construct() {
        parent::__construct();
        $this->load->model('Api_Model');
        if ($this->Api_Model->isThisUserAnEposLogger() && (($this->cookies && !empty($this->cookies)) || ($this->session->userdata('group') == 2))) {
            $this->branch = $this->session->userdata('branch');
            return true;
        } else {
            redirect('user/login/index/' . $this->session->userdata('branch') . '/' . $this->session->userdata('team'));
        }
    }

    public function epos_configuration() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->get('configuration')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  configuration'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_branch() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('id' => $this->branch))->get('branch')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  branch info'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_menucategory() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->order_by('position', 'ASC')->get('menucategory')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  menu category'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_menu() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->order_by('position', 'ASC')->get('menu')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  menu'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_menuselection() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->order_by('position', 'ASC')->get('menuselection')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  menu selection'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_menuset() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('menuset')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  menu set'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_menusetitem() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('menusetitem')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  menu set item'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_menuattrcategory() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('menuattrcategory')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  toppings category'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_menuattr() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('menuattr')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  toppings'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_modifiercategory() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('modifiercategory')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  modifier category'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_modifiermenu() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('modifiermenu')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  modifiers'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_nattrcategory() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('nattrcategory')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  global toppings category'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_nattr() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('nattr')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  global toppings'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_modifier() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('modifier')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  global modifier'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_menufixeddeal() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('menufixeddeal')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  fixed deal'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_discountitem() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('discountitem')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  item offer'
            );
            if (!empty($data)) {
                foreach ($data as $key => $obj) {
                    $data[$key]->type = unserialize($obj->type);
                    $data[$key]->item = unserialize($obj->item);
                }
            }
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_lcountry() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('lcountry', null, array('id', 'title', 'position', 'status'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced country'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_lregion() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('lregion', null, array('id', 'title', 'country', 'position', 'status'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced region'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_lcity() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('lcity', null, array('id', 'title', 'region', 'position', 'status'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced city'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_larea() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('larea', null, array('id', 'title', 'city', 'position', 'status'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced area'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_lpostcode() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('lpostcode', null, array('id', 'city', 'area', 'title'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced postcode'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_ldooraddress() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('ldooraddress')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced area'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_customer() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('customer', null, array('id', 'name', 'phone', 'email'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced customer'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_customer_address() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('customer_address', null, array('cid', 'country', 'region', 'city', 'area', 'postcode', 'street', 'building', 'floor', 'apartment'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced customer address'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_discountplan() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('discountplan', array('branch' => $this->branch))->result();
            if (!empty($data)) {
                foreach ($data as $key => $discountPlan) {
                    $data[$key]->onday = unserialize($discountPlan->onday);
                    $data[$key]->onapp = unserialize($discountPlan->onapp);
                    $data[$key]->onitem = unserialize($discountPlan->onitem);
                    $data[$key]->min_order = (int) $discountPlan->min_order;
                    $data[$key]->discount = (int) $discountPlan->discount;
                    $startTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->start_time);
                    $data[$key]->start_time = $startTimeObject->format('g:i:s A');
                    $endTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->end_time);
                    $data[$key]->end_time = $endTimeObject->format('g:i:s A');
                }
            }
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced discount plan'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_discountmulti() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('discountmulti', array('branch' => $this->branch))->result();
            if (!empty($data)) {
                foreach ($data as $key => $discountPlan) {
                    $data[$key]->onday = unserialize($discountPlan->onday);
                    $data[$key]->onapp = unserialize($discountPlan->onapp);
                    $data[$key]->min_order = (int) $discountPlan->min_order;
                    $data[$key]->buy = (double) $discountPlan->buy;
                    $data[$key]->get = (double) $discountPlan->get;
                    $data[$key]->category = (int) $discountPlan->category;
                    $data[$key]->menu = (int) $discountPlan->menu;
                    $data[$key]->selection = (int) $discountPlan->selection;
                    $startTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->start_time);
                    $data[$key]->start_time = $startTimeObject->format('g:i:s A');
                    $endTimeObject = DateTime::createFromFormat('h:i a', $data[$key]->end_time);
                    $data[$key]->end_time = $endTimeObject->format('g:i:s A');
                }
            }
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced multi discount plan'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_deliveryplan() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->db->where(array('branch' => $this->branch))->get('deliveryplan')->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced delivery plan'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    function epos_order() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $thisOrder = $this->input->post('theOrder');
            $customer = isset($thisOrder['cid']) && $thisOrder['cid'] > 0 ? $thisOrder['cid'] : 0;
            if ($thisOrder['type'] === 'bar' || $thisOrder['type'] === 'collection' || $thisOrder['type'] === 'delivery') {
                $customer = $this->updateCustomer($customer, $thisOrder);
            }
            $pushedData = array(
                'orderId' => $thisOrder['orderId'],
                'branch' => $thisOrder['branch'] ? $thisOrder['branch'] : $this->session->userdata('branch'),
                'cid' => $customer,
                'owner' => $thisOrder['owner'],
                'team' => $thisOrder['team'],
                'status' => $thisOrder['status'],
                'source' => $thisOrder['source'],
                'type' => $thisOrder['type'],
                'orderInfo' => serialize($thisOrder['orderInfo']),
                'cart' => serialize($thisOrder['cart']),
                'subTotal' => $thisOrder['subTotal'],
                'tax' => $thisOrder['tax'],
                'deliveryCharge' => $thisOrder['deliveryCharge'],
                'serviceCharge' => $thisOrder['serviceCharge'],
                'ccFee' => $thisOrder['ccFee'],
                'cbFee' => $thisOrder['cbFee'],
                'discount' => $thisOrder['discount'],
                'promo' => $thisOrder['promo'],
                'multiDiscount' => $thisOrder['multiDiscount'],
                'grandTotal' => $thisOrder['grandTotal'],
                'hours' => $thisOrder['dateInfo']['hours'],
                'minutes' => $thisOrder['dateInfo']['minutes'],
                'seconds' => $thisOrder['dateInfo']['seconds'],
                'day' => $thisOrder['dateInfo']['day'],
                'month' => $thisOrder['dateInfo']['month'],
                'year' => $thisOrder['dateInfo']['year'],
                'firstTakenAt' => $thisOrder['firstTakenAt'],
                'lastTakenAt' => $thisOrder['lastTakenAt'],
                'taxIsIncluded' => $thisOrder['taxIsIncluded'],
                'taxIncludedPercent' => $thisOrder['taxIncludedPercent']
            );
            if (!empty($thisOrder['payment'])) {
                $pushedData['payment'] = serialize($thisOrder['payment']);
            }

            $sid = isset($thisOrder['sid']) && $thisOrder['sid'] > 0 ? $thisOrder['sid'] : NULL;
            $rid = $this->savePrinting($sid, $thisOrder, $pushedData);
            if ($sid || $rid) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' has created order # ' . $rid
                );
                $this->Api_Model->posactivity($activity);
            }
            echo json_encode(array('sid' => $rid, 'customer' => $customer));
        }
    }

    private function updateCustomer($customer, $thisOrder) {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            if ($thisOrder['type'] === 'delivery') {
                $this->updateLookupAddress($thisOrder['orderInfo']);
            }
            $customerInfo = array(
                'name' => isset($thisOrder['orderInfo']['name']) ? $thisOrder['orderInfo']['name'] : '',
                'phone' => isset($thisOrder['orderInfo']['phone']) ? $thisOrder['orderInfo']['phone'] : '',
                'branch' => $this->session->userdata('branch')
            );
            if ($customer <= 0) {
                $doesCustomerExist = $this->db->where(array('phone' => $customerInfo['phone']))->get('customer')->row();
                if (empty($doesCustomerExist)) {
                    $customer = $this->Api_Model->save_customer($customerInfo, NULL);
                }
                if ($thisOrder['type'] === 'delivery' && $customer > 0) {
                    $deliveryInfo = $thisOrder['orderInfo'];
                    unset($deliveryInfo['deliveryTime']);
                    unset($deliveryInfo['name']);
                    unset($deliveryInfo['phone']);
                    unset($deliveryInfo['deliveryCharge']);
                    unset($deliveryInfo['minOrderAmount']);
                    $deliveryInfo['cid'] = $customer;
                    $deliveryInfo['lid'] = $thisOrder['orderInfo']['lid'];
                    $deliveryInfo['lcid'] = $thisOrder['orderInfo']['lcid'];
                    $deliveryInfo['created_by'] = $this->session->userdata('owner');
                    $deliveryInfo['branch'] = $this->session->userdata('branch');
                    $this->Api_Model->save_address($deliveryInfo, NULL);
                }
            }
            return $customer;
        }
    }

    private function updateLookupAddress($deliveryAddress) {
        $data = array(
            'street_number' => $deliveryAddress['sector'],
            'route' => $deliveryAddress['street'],
            'administrative_area_level_2' => $deliveryAddress['city'],
            'postal_code' => $deliveryAddress['postcode'],
            'country' => $deliveryAddress['country']
        );
        if ($this->db->where($data)->count_all_results('ldooraddress') <= 0) {
            $postcodeObj = $this->db->where(array('title' => $data['postal_code']))->get('lpostcode')->row();
            if (!empty($postcodeObj)) {
                $data['postcodeId'] = $postcodeObj->id;
                $this->db->insert('ldooraddress', $data);
            } else {
                $this->db->insert('ldooraddress', $data);
            }
        }
    }

    private function savePrinting($sid, $thisOrder, $pushedData) {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            if ($sid !== NULL && $this->Api_Model->exists('order', 'sid', $sid)) {
                $rid = $this->Api_Model->save($pushedData, $sid);
                if ($rid) {
                    $printData = array(
                        'lid' => $thisOrder['orderId'],
                        'owner' => $thisOrder['owner'],
                        'team' => $thisOrder['team'],
                        'type' => $this->input->post('type'),
                        'sent' => $this->input->post('sent'),
                        'isPrinted' => 2,
                        'additionals' => !empty($this->input->post('additionals')) ? $this->input->post('additionals') : '',
                        'branch' => $this->session->userdata('branch')
                    );
                    $this->Api_Model->save_printer($printData, $sid);
                }
                return $rid;
            } else {
                $rid = $this->Api_Model->save($pushedData, NULL);
                if ($rid) {
                    $printData = array(
                        'sid' => $rid,
                        'lid' => $thisOrder['orderId'],
                        'owner' => $thisOrder['owner'],
                        'team' => $thisOrder['team'],
                        'type' => $this->input->post('type'),
                        'sent' => $this->input->post('sent'),
                        'isPrinted' => 2,
                        'branch' => $this->session->userdata('branch')
                    );
                    $this->Api_Model->save_printer($printData, NULL);
                }
                return $rid;
            }
        }
    }

    function postupdateForExtraCharge() {
        $sid = $this->input->post('sid');
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $grandTotal = $this->input->post('grandTotal');
        $status = $this->db->update('order', array($column => $value, 'grandTotal' => $grandTotal), array('sid' => $sid));
        echo json_encode(array('status' => $status));
    }

    function sentktchmsg() {
        $data = $this->preparePostedData();
        $status = $this->db->insert('ktchmsg', $data);
        echo json_encode(array('status' => $status ? true : false));
    }

    function sendCommandToEpos($command) {
        $branch = $this->session->userdata('branch');
        $team = $this->session->userdata('team');
        $commandObj = $this->Api_Model->get_single('command', array('branch' => $branch, 'team' => $team, 'command' => $command))->row();
        $status = false;
        if (!empty($commandObj)) {
            $status = $this->db->update('command', array('isExecuted' => 'no'), array('branch' => $branch, 'team' => $team, 'command' => $command));
        } else {
            $status = $this->db->insert('command', array('branch' => $branch, 'team' => $team, 'command' => $command, 'isExecuted' => 'no'));
        }
        echo json_encode(array('status' => $status ? true : false));
    }

    function epos_booking() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $bookingList = array();
            $today = $this->input->post('today');
            if ($today === 'yes') {
                $bookingList = $this->db->where(array('date' => date('Y-m-d'), 'branch' => $this->branch))->order_by('date', 'ASC')->get('booking')->result();
            } else {
                $bookingList = $this->db->where(array('date >=' => date('Y-m-d'), 'branch' => $this->branch))->order_by('date', 'ASC')->get('booking')->result();
            }
            if (!empty($bookingList)) {
                foreach ($bookingList as $key => $abl) {
                    $bookingList[$key]->date = date('d/m/Y', strtotime($abl->date));
                }
            }
            echo json_encode($bookingList);
        }
    }

    function save_epos_booking() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->preparePostedData();
            if (isset($data['id']) && $data['id'] > 0) {
                $data['updated_by'] = $this->session->userdata('owner');
                $BookingDate = DateTime::createFromFormat('d/m/Y', $data['date'] != null ? $data['date'] : date('d/m/Y', strtotime('today')));
                $data['date'] = $BookingDate->format('Y-m-d');
                $id = $this->Api_Model->save_booking($data, $data['id']);
                if ($id > 0) {
                    $activity = array(
                        'activity' => ucfirst($this->session->userdata('name')) . ' has created booking #' . $id
                    );
                    $this->Api_Model->posactivity($activity);
                    echo json_encode(array('status' => true));
                } else {
                    echo json_encode(array('status' => false));
                }
            } else {
                $data['branch'] = $this->branch;
                $data['created_by'] = $this->session->userdata('owner');
                $data['status'] = 2;
                $BookingDate = DateTime::createFromFormat('d/m/Y', $data['date'] != null ? $data['date'] : date('d/m/Y', strtotime('today')));
                $data['date'] = $BookingDate->format('Y-m-d');
                $id = $this->Api_Model->save_booking($data, NULL);
                if ($id > 0) {
                    $activity = array(
                        'activity' => ucfirst($this->session->userdata('name')) . ' has updated booking #' . $id
                    );
                    $this->Api_Model->posactivity($activity);
                    if (!empty($data['email'])) {
                        $status = $this->prepareBookingEmailTemplateAndForwardToSend($id, $this->lang->line('booking') . ' ' . $this->lang->line('confirmed'), $this->lang->line('booking_create_confirm'));
                    }
                    echo json_encode(array('status' => true || $status));
                } else {
                    echo json_encode(array('status' => false));
                }
            }
        }
    }

    public function prepareBookingEmailTemplateAndForwardToSend($id, $title, $msg) {
        $booking = $this->Api_Model->get_single('booking', array('id' => $id))->row_array();
        if (!empty($booking)) {
            $branch = $this->Api_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row_array();
            $data['recipent'] = $booking['first_name'] . ' ' . $booking['last_name'];
            $data['to'] = $booking['email'];
            $data['from'] = $branch['general_email'];
            $data['from_title'] = $this->config->item('general_name');
            $data['subject'] = $title;
            $data['txt'] = $msg;
            $data['verify_link'] = null;
            $data['branch'] = $branch;
            $data['message'] = $this->load->view('api/email', $data, true);
            return $this->send_email($data);
        }
    }

    public function update_booking_status() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $statusArr = array(1 => $this->lang->line('pending'), 2 => $this->lang->line('confirmed'), 3 => $this->lang->line('rejected'));
            $id = $this->input->post('id');
            $status = $this->input->post('status');
            $returnId = $this->Api_Model->save_booking(array('status' => $status), $id);
            $emailStatus = false;
            if ($returnId) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' has updated  booking  status #' . $id
                );
                if ((int) $status >= 2) {
                    $emailStatus = $this->prepareBookingEmailTemplateAndForwardToSend($returnId, 'Booking ' . $statusArr[(int) $status], $this->lang->line('booking_status_trailer') . $statusArr[(int) $status]);
                }
            }
            $this->Api_Model->posactivity($activity);
            echo json_encode(array('status' => $returnId || $emailStatus ? true : false));
        }
    }

    public function driving_distance() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $source = $this->input->post('source');
            $destination = $this->input->post('destination');
            $distance = getDrivingDistance($source, $destination);
            echo json_encode($distance);
        }
    }

    public function epos_paymentoption() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('paymentoption', null, array('id', 'title', 'status'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  payment option'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function epos_voucher() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $data = $this->Api_Model->get_list('voucher', array('branch' => $this->branch), array('id', 'code', 'amount', 'balance', 'status', 'start', 'end'))->result();
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has synced  vouchers'
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode($data);
        }
    }

    public function payAndClose() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $theOrder = $this->input->post('theOrder');
            $paymentsList = $theOrder['payment'];
            $online = 'no';
            foreach ($paymentsList as $apayment) {
                if ($apayment['type'] === 'Voucher') {
                    $this->detuctVoucherAmount($apayment['code'], $apayment['amount']);
                } else {
                    if ($apayment['type'] === 'Online') {
                        $online = 'yes';
                    }
                }
            }
            $pushedData = array(
                'payment' => serialize($theOrder['payment']),
                'isPaid' => $theOrder['isPaid'],
                'changeAmount' => $theOrder['changeAmount'],
                'changeAsTips' => $theOrder['changeAsTips'],
                'onlinePaymentDetails' => !empty($theOrder['onlinePaymentDetails']) ? serialize($theOrder['onlinePaymentDetails']) : '',
                'status' => 5,
                'closer' => $this->session->userdata('owner'),
                'group' => $this->session->userdata('group')
            );

            $nowTime = strtotime(date('h:i a'));
            $timeA = strtotime(date('h:i a', strtotime('00:00 am')));
            $timeB = strtotime(date('h:i a', strtotime('04:00 am')));
            if ($nowTime >= $timeA && $nowTime <= $timeB) {
                $date = new DateTime(date('Y-m-d'));
                $date->sub(new DateInterval('P1D'));
                $pushedData['closingData'] = $date->format('Y-m-d');
            } else {
                $pushedData['closingData'] = date("Y-m-d");
            }
            $id = $this->Api_Model->save($pushedData, (int) $theOrder['sid']);
            if ($id) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' pay and close order #' . $id
                );
                $this->Api_Model->posactivity($activity);
                if ($theOrder['hasBillPrint'] === '3') {
                    $this->Api_Model->save_printer(array('type' => 4, 'isPrinted' => 2), (int) $theOrder['sid']);
                }
            }
            echo json_encode(array('status' => $id ? true : false, 'id' => $id, 'online' => $online));
        }
    }

    function remoteOrderPayAndClose() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $payment = $this->input->post('payment');
            $sid = $this->input->post('sid');
            $nowTime = strtotime(date('h:i a'));
            $timeA = strtotime(date('h:i a', strtotime('00:00 am')));
            $timeB = strtotime(date('h:i a', strtotime('04:00 am')));
            $closingData = null;
            if ($nowTime >= $timeA && $nowTime <= $timeB) {
                $date = new DateTime(date('Y-m-d'));
                $date->sub(new DateInterval('P1D'));
                $closingData = $date->format('Y-m-d');
            } else {
                $closingData = date("Y-m-d");
            }
            $hasBillPrint = $this->input->post('hasBillPrint');
            $onlinePaymentDetails = $this->input->post('onlinePaymentDetails');
            $pushedData = array(
                'payment' => serialize($payment),
                'isPaid' => 3,
                'changeAmount' => $this->input->post('changeAmount'),
                'changeAsTips' => $this->input->post('changeAsTips'),
                'onlinePaymentDetails' => !empty($onlinePaymentDetails) ? serialize($onlinePaymentDetails) : '',
                'status' => 5,
                'closer' => $this->session->userdata('owner'),
                'group' => $this->session->userdata('group'),
                'isPushed' => 'no',
                'closingData' => $closingData
            );
            $id = $this->Api_Model->save($pushedData, (int) $sid);
            foreach ($payment as $apayment) {
                if ($apayment['type'] === 'Voucher') {
                    $this->detuctVoucherAmount($apayment['code'], $apayment['amount']);
                } else {
                    if ($apayment['type'] === 'Online') {
                        $online = 'yes';
                    }
                }
            }
            $status = true;
            if ($id && $hasBillPrint === '3') {
                $this->Api_Model->save_printer(array('type' => 4, 'isPrinted' => 2), (int) $sid);
            }
            echo json_encode(array('status' => $id && $status ? true : false));
        }
    }

    private function detuctVoucherAmount($code, $amount) {
        $vouccherObject = $this->Api_Model->get_single('voucher', array('code' => trim($code)))->row();
        if (!empty($vouccherObject)) {
            $existingBalance = $vouccherObject->balance;
            $currentBalence = $existingBalance - $amount;
            $this->db->update('voucher', array('balance' => $currentBalence), array('id' => $vouccherObject->id, 'code' => $code));
        }
    }

    public function printer() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $sid = $this->input->post('sid');
            $type = $this->input->post('type');
            $orderStatus = $this->input->post('orderStatus') ? $this->input->post('orderStatus') : 0;
            $additionals = $this->input->post('additionals') ? $this->input->post('additionals') : '';
            if ((int) $orderStatus > 0) {
                $this->db->update('order', array('status' => $orderStatus), array('sid' => $sid));
            }
            $status = $this->Api_Model->save_printer(array('type' => $type, 'isPrinted' => 2, 'additionals' => $additionals), (int) $sid);
            echo json_encode(array('status' => $status));
        }
    }

    function notifyupdate() {
        if ($this->cookies && $this->Api_Model->isThisUserAnEposLogger()) {
            $issue = $this->input->post('issue');
            $owner = $this->session->userdata('owner');
            $status = $this->db->update('user', array('hasUpdate' => 'yes'), array('id<>' => $owner, 'branch' => $this->session->userdata('branch')));
            $issueId = $this->Api_Model->get_single('updateissue', array('title' => $issue))->row()->id;
            if ($status && $issueId) {
                $users = $this->Api_Model->get_list('user', array('hasUpdate' => 'yes', 'branch' => $this->session->userdata('branch')))->result();
                if (!empty($users)) {
                    foreach ($users as $auser) {
                        $doesExist = $this->Api_Model->get_single('updates', array('user' => $auser->id, 'issue' => $issueId, 'branch' => $this->branch))->row();
                        if ($doesExist) {
                            $this->db->update('updates', array('status' => 2), array('user' => $auser->id, 'issue' => $issueId, 'branch' => $this->branch));
                        } else {
                            $this->db->insert('updates', array('issue' => $issueId, 'issueTitle' => $issue, 'user' => $auser->id, 'branch' => $this->session->userdata('branch')));
                        }
                    }
                }
            }
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has pushed remote updates for ' . $issue
            );
            $this->Api_Model->posactivity($activity);
            echo json_encode(array('status' => $status ? true : false));
        } else {
            echo json_encode(array('status' => false));
        }
    }

    public function pushOrderAtEpos() {
        $data = array(
            'sid' => $this->input->post('sid'),
            'orderId' => $this->input->post('lid'),
        );
        $status = $this->db->update('order', array('isPushed' => 'yes', 'status' => 4), $data);
        echo json_encode(array('status' => $status ? true : false));
    }

    public function getPushedOrder() {
        $pusshedOrders = $this->Api_Model->get_list('order', array('isPushed' => 'yes', 'branch' => $this->session->userdata('branch'), 'team' => $this->session->userdata('team')))->result();
        $table = array();
        $bar = array();
        $waiting = array();
        $collection = array();
        $delivery = array();
        if (!empty($pusshedOrders)) {
            foreach ($pusshedOrders as $key => $obj) {
                $pusshedOrders[$key]->orderInfo = unserialize($obj->orderInfo);
                $pusshedOrders[$key]->cart = unserialize($obj->cart);
                if ($obj->type === 'table') {
                    array_push($table, $pusshedOrders[$key]);
                }
                if ($obj->type === 'bar') {
                    array_push($bar, $pusshedOrders[$key]);
                }
                if ($obj->type === 'waiting') {
                    array_push($waiting, $pusshedOrders[$key]);
                }
                if ($obj->type === 'collection') {
                    array_push($collection, $pusshedOrders[$key]);
                }
                if ($obj->type === 'delivery') {
                    array_push($delivery, $pusshedOrders[$key]);
                }
            }
        }
        echo json_encode(array('allOrders' => $pusshedOrders, 'table' => $table, 'bar' => $bar, 'waiting' => $waiting, 'collection' => $collection, 'delivery' => $delivery));
    }

    public function appcrashreport() {
        $postedData = $this->input->post();
        if (!empty($postedData)) {
            $data['report'] = serialize($postedData);
            $this->db->insert('crashreporter', $data);
        }
    }

    public function getOnlineOrder() {
        $orders = $this->db->where(array('status <' => 5, 'status_online <' => 4, 'source' => 'online', 'branch' => $this->branch))->order_by('status_online', 'ASC')->get('order')->result();
        if (!empty($orders)) {
            foreach ($orders as $key => $order) {
                $orders[$key]->orderInfo = unserialize($order->orderInfo);
                $orders[$key]->cart = unserialize($order->cart);
                if (trim($order->payment) && $order->isPaid == 3) {
                    $orders[$key]->payment = unserialize($order->payment);
                }
                if (trim($order->onlinePaymentDetails) && $order->isPaid == 3) {
                    $orders[$key]->onlinePaymentDetails = unserialize($order->onlinePaymentDetails);
                }
            }
        }
        echo json_encode($orders);
    }

    public function acceptOnlineOrder() {
        $extraTime = $this->input->post('extraTime');
        $sid = $this->input->post('sid');
        $order = $this->Api_Model->get_single('order', array('sid' => $sid))->row();
        $orderInfo = unserialize($order->orderInfo);
        if ($order->type === 'collection') {
            $collectionTimeObj = new DateTime($orderInfo['collectionTime']);
            $collectionTimeObj->add(new DateInterval('PT' . $extraTime . 'M'));
            $nowTime = $collectionTimeObj->format('h:i a');
            $orderInfo['collectionTime'] = $nowTime;
        } else {
            $deliveryTimeObj = new DateTime($orderInfo['deliveryTime']);
            $deliveryTimeObj->add(new DateInterval('PT' . $extraTime . 'M'));
            $nowTime = $deliveryTimeObj->format('h:i a');
            $orderInfo['deliveryTime'] = $nowTime;
        }
        $s1 = $this->Api_Model->save(array('orderInfo' => serialize($orderInfo), 'status' => 2, 'status_online' => 3), $sid);
        $printData = array(
            'sid' => $order->sid,
            'lid' => $order->orderId,
            'owner' => $this->session->userdata('owner'),
            'team' => $this->session->userdata('team'),
            'type' => 2,
            'sent' => 2,
            'isPrinted' => 2,
            'additionals' => isset($orderInfo['note']) ? $orderInfo['note'] : '',
            'branch' => $this->session->userdata('branch')
        );
        $s2 = false;
        if (!empty($this->Api_Model->get_single('printing', array('sid' => $sid))->row())) {
            $s2 = $this->Api_Model->save_printer($printData, $sid);
        } else {
            $s2 = $this->Api_Model->save_printer($printData, NULL);
        }


        echo json_encode(array('status' => $s1 && $s2, 'sid' => $s1));
    }

    public function rejectOnlineOrder() {
        $rejectMsg = $this->input->post('rejectMsg');
        $sid = $this->input->post('sid');
        $s1 = $this->Api_Model->save(array('rejectMsg' => $rejectMsg, 'status_online' => 4), $sid);
        echo json_encode(array('status' => $s1));
    }

    public function resendOnlineOrder() {
        $printData = array('type' => 2, 'isPrinted' => 2);
        $s2 = $this->Api_Model->save_printer($printData, $this->input->post('sid'));
        echo json_encode(array('status' => $s2));
    }

    public function printBillOnlineOrder() {
        $printData = array('type' => 4, 'isPrinted' => 2);
        $s1 = $this->Api_Model->save(array('status' => 4), $this->input->post('sid'));
        $s2 = $this->Api_Model->save_printer($printData, $this->input->post('sid'));
        echo json_encode(array('status' => $s1 && $s2));
    }

    public function closeOnlineOrder() {
        $nowTime = strtotime(date('h:i a'));
        $timeA = strtotime(date('h:i a', strtotime('00:00 am')));
        $timeB = strtotime(date('h:i a', strtotime('04:00 am')));
        $closingData = null;
        if ($nowTime >= $timeA && $nowTime <= $timeB) {
            $date = new DateTime(date('Y-m-d'));
            $date->sub(new DateInterval('P1D'));
            $closingData = $date->format('Y-m-d');
        } else {
            $closingData = date("Y-m-d");
        }
        $status = $this->Api_Model->save(array('status' => 5, 'closingData' => $closingData), $this->input->post('sid'));
        if ($this->input->post('action') === 'yes') {
            $printData = array('type' => 4, 'isPrinted' => 2);
            $this->Api_Model->save_printer($printData, $this->input->post('sid'));
        }
        echo json_encode(array('status' => $status));
    }

}
