<?php

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

class Printer_Model extends MY_Model {

    function __construct() {
        parent::__construct();
        $this->load->helper('gkpos');
    }

    function get_ktc_print() {

        $OrderObj = $this->get_list('gkpos_order', array('has_print' => '1', 'is_printed' => '0'), array('id', 'order_type', 'online_type', 'phone', 'name', 'table_number', 'guest_quantity', 'delivery_time', 'delivery_note', 'grand_total', 'floor_or_apt', 'building', 'house', 'postcode', 'street', 'city', 'created', 'is_printed', 'has_print', 'sent_option'), 1, '', 'created', 'ASC');
        $items = array();
        if (!empty($OrderObj)) {
            $this->db->trans_start();
            if ($OrderObj[0]->sent_option == 'new') {
                if ($OrderObj[0]->order_type != 'table') {
                    $items = $this->get_list('gkpos_order_detail', array('order_id' => $OrderObj[0]->id, 'changed' => 'yes'), array('id', 'order_id', 'category_print_option', 'menu_title', 'selection_title', 'quantity', 'quantity_new', 'set_items', 'toppings'));
                } else {
                    $items = $this->get_list('gkpos_order_detail', array('order_id' => $OrderObj[0]->id, 'category_type' => 1, 'changed' => 'yes'), array('id', 'order_id', 'category_print_option', 'menu_title', 'selection_title', 'quantity', 'quantity_new', 'set_items', 'toppings'));
                }
            }
            if ($OrderObj[0]->sent_option == 'all') {
                if ($OrderObj[0]->order_type != 'table') {
                    $items = $this->get_list('gkpos_order_detail', array('order_id' => $OrderObj[0]->id), array('id', 'order_id', 'category_print_option', 'menu_title', 'selection_title', 'quantity', 'set_items', 'toppings'));
                } else {
                    $items = $this->get_list('gkpos_order_detail', array('order_id' => $OrderObj[0]->id, 'category_type' => 1), array('id', 'order_id', 'category_print_option', 'menu_title', 'selection_title', 'quantity', 'set_items', 'toppings'));
                }
            }
            $print_option = printing_options(); //array(1 => $this->lang->line('gkpos_kitchen_print_setting1'), 2 => $this->lang->line('gkpos_kitchen_print_setting2'), 3 => $this->lang->line('gkpos_kitchen_print_setting3'), 4 => $this->lang->line('gkpos_kitchen_print_setting4'));
            if (!empty($items)) {
                $data = array(
                    'status' => true,
                    'restaurant' => $this->config->item('gk_name'),
                    'ktc_printer' => $this->config->item('gk_ktcprinter'),
                    'info' => $OrderObj,
                    'items' => $items,
                    'total' => to_currency($OrderObj[0]->grand_total),
                    'print_option' => $print_option
                );
            } else {
                if ($this->db->update('gkpos_order', array('is_printed' => 1, 'has_print' => 0), array('id' => $OrderObj[0]->id))) {
                    $data = array(
                        'status' => false
                    );
                }
            }
            $this->db->trans_complete();
        } else {
            $data = array(
                'status' => false
            );
        }

        return $data;
    }

    function get_bill() {
        $billCopy = $this->get_list('gkpos_billcopy', array('status' => 0), '', 1, '', 'created', 'ASC');
        if (!empty($billCopy)) {
            $this->db->trans_start();
            $OrderObj = $this->get_single('gkpos_order', array('id' => $billCopy[0]->order_id), array('id', 'order_type', 'online_type', 'table_number', 'guest_quantity', 'online_method', 'phone', 'name', 'floor_or_apt', 'building', 'house', 'postcode', 'street', 'city', 'delivery_time', 'delivery_charge', 'order_total', 'grand_total', 'paid_status', 'change_due', 'pay_tip', 'cc_fee', 'bogo_discount'));
            if (!empty($OrderObj)) {
                $sub_total = $OrderObj->order_total = to_currency($OrderObj->order_total);
                $total = $OrderObj->grand_total = to_currency($OrderObj->grand_total);
                $change_due = $OrderObj->change_due = $OrderObj->change_due != null ? to_currency(abs($OrderObj->change_due)) : null;
                $delivery_fee = $OrderObj->delivery_charge != null ? to_currency($OrderObj->delivery_charge) : NULL;
                $cc_fee = $OrderObj->cc_fee != null ? to_currency($OrderObj->cc_fee) : NULL;
                $bogo_discount = $OrderObj->bogo_discount != null ? to_currency($OrderObj->bogo_discount) : NULL;
                $orderDetailObj = $this->get_list('gkpos_order_detail', array('order_id' => $billCopy[0]->order_id), array('id', 'order_id', 'menu_title', 'selection_title', 'quantity', 'price', 'set_items', 'toppings'), '', '', 'id', 'ASC');
                foreach ($orderDetailObj as $key => $item) {
                    $orderDetailObj[$key]->price = to_currency($item->price * $item->quantity);
                }
                $vatObj = $this->get_single('gkpos_order_vat', array('order_id' => $billCopy[0]->order_id));
                $discountObj = $this->get_single('gkpos_order_discount', array('order_id' => $billCopy[0]->order_id));
                $servichChargeObj = $this->get_single('gkpos_order_servicecharge', array('order_id' => $billCopy[0]->order_id));

                $paymentObj = null;
                if ($OrderObj->paid_status == 1) {
                    $paymentObj = $this->get_list('gkpos_order_payment', array('order_id' => $billCopy[0]->order_id));
                    foreach ($paymentObj as $key => $payment) {
                        $paymentObj[$key]->amount = to_currency($payment->amount);
                        unset($paymentObj[$key]->code);
                    }
                }
                $discount = $discountObj != null ? to_currency($discountObj->amount) : NULL;
                $vat = $vatObj != null ? ($vatObj->is_included == 1 ? $vatObj->number . '% included' : to_currency($vatObj->amount)) : NULL;
                $service_charge = $servichChargeObj != null ? to_currency($servichChargeObj->amount) : null;

                $calculation = array(
                    'sub_total' => $sub_total,
                    'discount' => $discount,
                    'vat' => $vat,
                    'service_charge' => $service_charge,
                    'delivery_charge' => $delivery_fee,
                    'total' => $total,
                    'change' => $change_due,
                    'pay_tip' => $OrderObj->pay_tip == 'yes' ? 'yes' : 'no',
                    'cc_fee' => $cc_fee,
                    'bogo_discount' => $bogo_discount
                );

                if ($calculation && $orderDetailObj) {
                    unset($OrderObj->order_total);
                    unset($OrderObj->grand_total);
                    unset($OrderObj->change_due);
                    unset($OrderObj->delivery_charge);
                    unset($OrderObj->pay_tip);
                }
                $employe_info = array(
                    'served_by' => get_user_name($billCopy[0]->created_by),
                    'time' => date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), now()),
                );
                $restaurant_info = array(
                    'name' => $this->config->item('gk_name'),
                    'logo' => UPLOAD_PATH . 'gkpos/logo/' . $this->config->item('gk_logo'),
                    'address' => $this->config->item('gk_address'),
                    'phone' => $this->config->item('gk_phone'),
                    'vat_reg_no' => $this->config->item('gk_vat_reg'),
                );
                $this->db->trans_complete();
                return array('status' => true && $this->db->trans_status(), 'bill_printer' => $this->config->item('gk_billprinter'), 'restaurant_info' => $restaurant_info, 'employee_info' => $employe_info, 'customer_info' => $OrderObj, 'items' => $orderDetailObj, 'calculation' => $calculation, 'payments' => $paymentObj);
            } else {
                return array('status' => false);
            }
        } else {
            return array('status' => false);
        }
    }

    public function appsdata() {
        $this->db->trans_start();
        $data = array();
        $data['restaurant']['name'] = $this->config->item('gk_name');
        $data['restaurant']['address'] = $this->config->item('gk_address');
        $data['restaurant']['email'] = $this->config->item('gk_email');
        $data['restaurant']['phone'] = $this->config->item('gk_phone');
        $data['pages'] = $this->get_list('page');
        $data['categories'] = $this->get_list('gkpos_category', array('status' => 1, 'online' => 1), null, null, 0, 'order', 'ASC');
        $menus = array();
        foreach ($data['categories'] as $category) {
            $menus[$category->id] = $this->get_list('gkpos_menu', array('category' => $category->id, 'status' => 1, 'online' => 1), null, null, 0, 'order', 'ASC');
        }
        $data['menus'] = $menus;
        $selections = array();
        $toppings = array();
        foreach ($menus as $menu) {
            if ($menu != null) {
                foreach ($menu as $selection) {
                    $selections[$selection->category][$selection->id] = $this->get_list('gkpos_selection', array('category' => $selection->category, 'menu' => $selection->id, 'status' => 1, 'online' => 1), null, null, 0, 'order', 'ASC');
                    $toppings[$selection->category][$selection->id] = array();
                }
            }
        }
        $data['toppings_category'] = $this->get_list('toppings_category', array('status' => 1));
        $data['selections'] = $selections;
        $data['menuToppings'] = $this->get_list('item_toppings', array('menu >' => 0, 'status' => 1));
        $data['selectionToppings'] = $this->get_list('item_toppings', array('selection >' => 0, 'status' => 1));
        $allToppingsInfo = array();
        $data['allToppings'] = $allToppingsInfo;
        $data['allDeals'] = $deals = $this->get_list('meal_deal', null, null, null, 0, 'order', 'ASC');
        $deal_sets = array();
        $deal_toppings = array();
        $deal_set_menus = array();
        if (!empty($deals)) {
            foreach ($deals as $deal) {
                $deal_sets[$deal->id] = $dealSets = $this->get_list('meal_deal_set', array('deal' => $deal->id), null, null, 0, 'id', 'ASC');
                $deal_toppings[$deal->id] = array();
                foreach ($dealSets as $dealSet) {
                    $deal_set_menus[$deal->id][$dealSet->id] = $this->get_list('meal_deal_menu', array('deal' => $deal->id, 'set' => $dealSet->id), null, null, 0, 'menu', 'ASC');
                }
            }
        }
        $data['deal_sets'] = $deal_sets;
        $data['deal_toppings'] = $this->get_list('item_toppings', array('meal_deal >' => 0, 'status' => 1));
        $data['deal_set_menus'] = $deal_set_menus;
        $data['deal_set_selections'] = $this->get_list('meal_deal_selection', null, null, null, 0, 'selection', 'ASC');
        $service_time = $this->get_list('servicetime');
        $servicetime_arr = array();
        foreach ($service_time as $st) {
            $servicetime_arr[$st->day] = $st;
        }
        $data['service_time'] = $servicetime_arr;
        $data['isRestaaurantOpened'] = $this->is_restaurant_open();
        $data['promotions'] = $promotions = $this->get_promostions();
        $vat = array();
        if ($this->config->item('gk_vat_reg') != '' || $this->config->item('gk_vat_reg')) {
            $vat['number'] = $this->config->item('gk_discount_percent');
            $vat['func'] = 1;
            $vat['amount'] = 0;
            $vat['is_included'] = $this->config->item('gk_vat_included') == 'yes' ? 1 : 2;
        }
        $discount = array();
        if ($this->config->item('gk_discount_applied') == 'yes') {
            $discount['default']['number'] = $this->config->item('gk_discount_percent');
            $discount['default']['func'] = 1;
            $discount['default']['amount'] = 0;
            $discount['default']['food'] = $this->config->item('gk_discount_food') == 'yes' ? $this->config->item('gk_discount_food') : 'no';
            $discount['default']['nonfood'] = $this->config->item('gk_discount_nonfood') == 'yes' ? $this->config->item('gk_discount_nonfood') : 'no';
            $discount['default']['min_order'] = $this->config->item('gk_discount_min_order');
            $onlineCollection = $this->get_single('gkpos_discountplan', array('type' => 'online_collection', 'is_applied' => 'yes'));
            if (!empty($onlineCollection)) {
                $discount['collection']['number'] = $onlineCollection->number;
                $discount['collection']['func'] = $onlineCollection->func;
                $discount['collection']['amount'] = 0;
                $discount['collection']['food'] = $onlineCollection->food == 'yes' ? $onlineCollection->food : 'no';
                $discount['collection']['nonfood'] = $onlineCollection->nonfood == 'yes' ? $onlineCollection->nonfood : 'no';
                $discount['collection']['min_order'] = $onlineCollection->min_order;
            }
            $onlineDelivery = $this->get_single('gkpos_discountplan', array('type' => 'online_delivery', 'is_applied' => 'yes'));
            if (!empty($onlineDelivery)) {
                $discount['delivery']['number'] = $onlineDelivery->number;
                $discount['delivery']['func'] = $onlineDelivery->func;
                $discount['delivery']['amount'] = 0;
                $discount['delivery']['food'] = $onlineDelivery->food == 'yes' ? $onlineDelivery->food : 'no';
                $discount['delivery']['nonfood'] = $onlineDelivery->nonfood == 'yes' ? $onlineDelivery->nonfood : 'no';
                $discount['delivery']['min_order'] = $onlineDelivery->min_order;
            }
        }
        $data['vat'] = $vat;
        $data['discount'] = $discount;
        $deliveryPlan = $this->get_list('gkpos_deliveryplan', array('status' => 1), array('id', 'is_free', 'delivery_charge', 'min_order', 'delivery_time', 'initial_code'));
        $organisedDeliveryPlan = array();
        if (!empty($deliveryPlan)) {
            foreach ($deliveryPlan as $key => $value) {
                $organisedDeliveryPlan[$value->initial_code] = $value;
            }
        }
        $data['deliveryPlan'] = $organisedDeliveryPlan;
        $this->db->trans_complete();
        return array('status' => true && $this->db->trans_status(), 'jsonData' => $data);
    }

    private function get_promostions() {
        $this->db->where('status', 1);
        $this->db->where('is_opened', 1);
        $this->db->where('start <=', date('Y-m-d'));
        $this->db->where('end >=', date('Y-m-d'));
        $results = $this->db->get('promotion')->result();
        $newResult = array();
        if (!empty($results)) {
            foreach ($results as $key => $value) {
                $newResult[$value->code] = $value;
            }
        }
        return $newResult;
    }

    private function is_restaurant_open() {
        $today = $this->get_single('servicetime', array('day' => strtolower(date('D'))));
        $current_time = date('g:i A');
        $sunrise = $today->open;
        $sunset = $today->closed;
        $date1 = DateTime::createFromFormat('g:i A', $current_time);
        $date2 = DateTime::createFromFormat('g:i A', $sunrise);
        $date3 = DateTime::createFromFormat('g:i A', $sunset);
        if ($date1 > $date2 && $date1 < $date3) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function bluetooth_pendingOrder() {
        $data['order'] = $order = $this->get_list('gkpos_order', array('order_type' => 'online', 'online_status' => 0), null, 1, 0, 'created', 'ASC');
        $data['items'] = array();
        if (!empty($order)) {
            $items = $this->get_list('gkpos_order_detail', array('order_id' => $order[0]->id));
            foreach ($items as $key => $item) {
                $items[$key]->price = to_currency_no_money($item->price * $item->quantity);
            }
            $data['items'] = $items;
            $discount = $this->get_single('gkpos_order_discount', array('order_id' => $order[0]->id));
            $data['discount'] = !empty($discount) ? $discount->amount : '0';
            $vat = $this->get_single('gkpos_order_vat', array('order_id' => $order[0]->id));
            $data['vat'] = !empty($vat) ? $vat->amount : '0';
            $payments = $this->get_list('gkpos_order_payment', array('order_id' => $order[0]->id));
            $payments_cool = array();
            if (!empty($payments)) {
                foreach ($payments as $key => $obj) {
                    $payments_cool[$obj->method] = array(
                        'method' => $obj->method,
                        'amount' => $obj->amount,
                        'order_id' => $obj->order_id
                    );
                }
            } else {
                $payments_cool[$this->lang->line('gkpos_payment_cash')] = array(
                    'method' => $this->lang->line('gkpos_payment_cash'),
                    'amount' => to_currency_no_money($order[0]->grand_total),
                    'order_id' => $order[0]->id
                );
            }
            $data['payments'] = $payments_cool;
        }
        if (!empty($order)) {
            $calculation = array(
                'sub_total' => to_currency_no_money($order[0]->order_total),
                'discount' => to_currency_no_money($data['discount']),
                'vat' => to_currency_no_money($data['vat']),
                'delivery_charge' => $order[0]->delivery_charge > 0 ? to_currency_no_money($order[0]->delivery_charge) : '0',
                'cc_fee' => $order[0]->cc_fee > 0 ? to_currency_no_money($order[0]->cc_fee) : '0',
                'total' => to_currency_no_money($order[0]->grand_total),
                'bogo_discount' => $order[0]->bogo_discount > 0 ? to_currency_no_money($order[0]->bogo_discount) : '0',
            );
            $data['calculation'] = $calculation;

            $restaurant_info = array(
                'name' => $this->config->item('gk_name'),
                'logo' => UPLOAD_PATH . 'gkpos/logo/' . $this->config->item('gk_logo'),
                'address' => $this->config->item('gk_address'),
                'phone' => $this->config->item('gk_phone'),
                'vat_reg_no' => $this->config->item('gk_vat_reg'),
            );
            $data['restaurant_info'] = $restaurant_info;
            $data['print_options'] = printing_options();
        }

        $bookingPending = $this->get_list('gkpos_booking', array('status' => 0), null, 1, 0, 'created_at', 'DESC');
        return array('status' => !empty($data['order']) && !empty($data['items']) ? true : false, 'data' => $data, 'booking' => !empty($bookingPending)?$bookingPending:array());
    }

}
