<?php

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

class Printer extends MY_Controller {

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

    public function ktcprinter() {
        $data = $this->Printer_Model->get_ktc_print();
        echo json_encode($data); // OK 
    }

    public function billprinter() {
        $data = $this->Printer_Model->get_bill();
        echo json_encode($data); // OK 
    }

    public function reportprinter() {
        $data = $this->Printer_Model->get_ktc_print();
        echo json_encode($data);
    }

    public function updatektcprinter() {
        $order_id = $this->input->post('order_id');
        $is_printed = $this->input->post('is_printed');
        if ($order_id && $is_printed == 1) {
            $this->db->trans_start();
            $this->db->update('gkpos_order', array('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));
            $this->db->trans_complete();
            echo json_encode(array('status' => $this->db->trans_status()));
        } else {
            echo json_encode(array('status' => false));
        }
    }

    public function updatebillprinter() {
        $order_id = $this->input->post('order_id');
        $bill_printed = $this->input->post('bill_printed');
        if ($order_id && $bill_printed == 1) {
            $this->db->trans_start();
            $this->db->update('gkpos_order', array('bill_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));
            $this->db->delete('gkpos_billcopy', array('order_id' => $order_id));
            $this->db->trans_complete();
            echo json_encode(array('status' => $this->db->trans_status()));
        } else {
            echo json_encode(array('status' => false));
        }
    }

    public function callerid() {
        $caller_id = $this->input->post('caller_id');
        if ($caller_id != null || $caller_id != '') {
            $caller_id = $this->extract_callerid($caller_id);
            $data = array('status' => 1, 'created' => date('Y-m-d H:i:s'), 'caller_id' => $caller_id);
            $this->db->trans_start();
            $this->db->insert('gkpos_caller', $data);
            $this->db->trans_complete();
            echo json_encode(array('status' => $this->db->trans_status()));
        } else {
            echo json_encode(array('status' => false));
        }
    }

    private function extract_callerid($string) {
        $result = filter_var($string, FILTER_SANITIZE_NUMBER_INT);
        return $result;
    }

    public function register() {
        $success = false;
        $message = null;
        $data = $this->input->post();
        if ($data['password'] && $data['password'] != null) {
            $data['password'] = md5($data['password']);
        } else {
            unset($data['password']);
        }
        if ($data['action'] && $data['action'] == 'update') {
            $phone = $data['phone'];
            $email = $data['email'];
            unset($data['email']);
            unset($data['phone']);
            unset($data['action']);
            $data['is_verified'] = 1;
            $success = $this->db->update('gkpos_customer', $data, array('phone' => $phone, 'email' => $email));
            $message = "Your Account updated Successfully";
        } else {
            $data['status'] = 1;
            $data['is_verified'] = 0;
            $data['is_online'] = 1;
            $doesExist = $this->Printer_Model->get_single('gkpos_customer', array('phone' => $data['phone']));
            $success_message = "Your registration done successfully at " . $this->config->item('gk_name');
            if ($doesExist != null && !empty($doesExist)) {
                if ($doesExist->email != null && $doesExist->password != '') {
                    $success = false;
                    $message = 'User already exists with that email or/and phone';
                } else {
                    $success = $this->db->update('gkpos_customer', $data, array('phone' => $doesExist->phone));
                    $message = $success_message;
                }
            } else {
                $success = $this->db->insert('gkpos_customer', $data);
                $message = $success_message;
            }
        }
        echo json_encode(array('status' => $success, 'message' => $message));
    }

    public function validate() {
        $data = $this->input->post();
        if ($data['email'] != null && $data['password'] != null) {
            $user = $this->Printer_Model->get_single('gkpos_customer', array('email' => $data['email'], 'password' => md5($data['password'])));
            if ($user && !empty($user)) {
                echo json_encode(array('status' => true, 'message' => 'ok', 'userInfo' => $user));
            } else {
                echo json_encode(array('status' => false, 'message' => 'Invalid username or password'));
            }
        } else {
            echo json_encode(array('status' => false, 'message' => 'No Data Posted'));
        }
    }

    public function appdata() {
        $data = $this->Printer_Model->appsdata();
        echo json_encode($data); // OK 
    }

    public function appcheckout() {
        $this->db->trans_start();
        $checkoutInfo = $this->input->post('checkoutInfo');
        $cart = $this->input->post('cart');
        $discount = $this->input->post('discount');
        $vat = $this->input->post('vat');
        if ($checkoutInfo['order_type'] != null && $checkoutInfo['online_type'] != null && $checkoutInfo['online_method'] != null && $checkoutInfo['phone'] != null && $checkoutInfo['name'] != null && $checkoutInfo['email'] != null) {
            $order = $this->save_app_order($checkoutInfo);
            if (!empty($order) && !empty($cart)) {
                $this->save_app_order_detail($cart, $order->id);
            }
            if (!empty($discount)) {
                $this->save_app_order_discount($discount, $order->id);
            }
            if (!empty($vat)) {
                $this->save_app_order_vat($vat, $order->id);
            }
            $this->db->trans_complete();
            $success = $this->db->trans_status();
            $order_id = !empty($order) ? $order->id : false;
            if ($success && $order_id) {
                $thisOrder = $this->Printer_Model->get_single('gkpos_order', array('id' => $order_id));
                $items = $this->Printer_Model->get_list('gkpos_order_detail', array('order_id' => $order_id));
                $discount[$order_id] = $this->Printer_Model->get_single('gkpos_order_discount', array('order_id' => $order->id));
                $vat[$order_id] = $this->Printer_Model->get_single('gkpos_order_vat', array('order_id' => $order->id));
                $payments[$order_id] = $this->Printer_Model->get_list('gkpos_order_payment`', array('order_id' => $order->id));
                echo json_encode(array('status' => $success, 'orders' => $thisOrder, 'items' => $items, 'discount' => $discount, 'vat' => $vat, 'payments' => $payments)); // OK
            } else {
                echo json_encode(array('status' => false)); // OK 
            }
        } else {
            echo json_encode(array('status' => false)); // OK 
        }
    }

    private function save_app_order($data) {
        $data['id'] = $this->Printer_Model->get_key();
        if ($data['online_method'] != 'cod') {
            $data['online_status'] = 3;
        }
        $data['created'] = date('Y-m-d H:i:s');
        if ($this->db->insert("gkpos_order", $data)) {
            return $this->Printer_Model->get_single('gkpos_order', array('id' => $data['id'], 'phone' => $data['phone'], 'email' => $data['email']));
        } else {
            return array();
        }
    }

    private function save_app_order_detail($cart, $order_id) {
        foreach ($cart as $item) {
            $item['order_id'] = $order_id;
            $this->db->insert('gkpos_order_detail', $item);
        }
    }

    private function save_app_order_discount($discount, $order_id) {
        $discount_data = $discount;
        if (!empty($discount_data)) {
            $discount_data['order_id'] = $order_id;
            return $this->db->insert('gkpos_order_discount', $discount_data);
        }
    }

    private function save_app_order_vat($vat, $order_id) {
        $vat_data = $vat;
        $vat_data['order_id'] = $order_id;
        return $this->db->insert('gkpos_order_vat', $vat_data);
    }

    public function appcustomerorders() {
        $email = $this->input->post('email');
        $phone = $this->input->post('phone');
        $orders = $this->Printer_Model->get_list('gkpos_order', array('email' => $email, 'phone' => $phone, 'order_type' => 'online'), null, 5, 0, 'created', 'DESC');
        $items = array();
        $discount = array();
        $vat = array();
        $payments = array();
        $status = false;
        if (!empty($orders)) {
            $status = true;
            foreach ($orders as $order) {
                $items[$order->id] = $this->Printer_Model->get_list('gkpos_order_detail', array('order_id' => $order->id));
                $discount[$order->id] = $this->Printer_Model->get_single('gkpos_order_discount', array('order_id' => $order->id));
                $vat[$order->id] = $this->Printer_Model->get_single('gkpos_order_vat', array('order_id' => $order->id));
                $payments[$order->id] = $this->Printer_Model->get_list('gkpos_order_payment`', array('order_id' => $order->id));
            }
        }
        echo json_encode(array('status' => $status, 'orders' => $orders, 'items' => $items, 'discount' => $discount, 'vat' => $vat, 'payments' => $payments)); // OK
    }

    public function bluetooth() {
        $data = $this->Printer_Model->bluetooth_pendingOrder();
        echo json_encode($data);
    }

    public function bluetoothreaction() {
        $id = $this->input->post('order_id');
        $online_status = $this->input->post('online_status');
        $success = false;
        $s1 = false;
        $s2 = false;
        if ($this->Printer_Model->exists('gkpos_order', 'id', $id)) {
            $order = $this->Printer_Model->get_single('gkpos_order', array('id' => $id), array('delivery_time'));
            if ((int) $online_status == 1) {
                $oldTime = date('H:i a', strtotime($order->delivery_time));
                $additionalMinutes = $this->post('delivery_time');
                if ($additionalMinutes != null) {
                    $oldHourMinMer = explode(' ', $oldTime);
                    $oldMer = $oldHourMinMer[1];
                    $oldHourMin = explode(':', $oldHourMinMer[0]);
                    $oldHour = $oldHourMin[0];
                    $oldMin = $oldHourMin[1];
                    $TotalMinutes = (int) $oldMin + (int) +$additionalMinutes;
                    $totalHour = (int) ($TotalMinutes / 60) + $oldHour;
                    $newHour = null;
                    $newMinutes = $TotalMinutes % 60;
                    if ($totalHour >= 24) {
                        $newHour = $totalHour % 12;
                        $newMer = 'am';
                    } else if ($totalHour >= 12 && $totalHour < 24) {
                        $newHour = $totalHour % 12;
                        $newMer = 'pm';
                    } else {
                        $newHour = $totalHour;
                        $newMer = 'am';
                    }
                    if ($newHour <= 9) {
                        $newHour = '0' . $newHour;
                    }
                    if ($newMinutes <= 9) {
                        $newMinutes = '0' . $newMinutes;
                    }
                    $newDeliveryTimeString = $newHour . ':' . $newMinutes . ' ' . $newMer;
                    $success = $this->db->update('gkpos_order', array('online_status' => 1, 'delivery_time' => $newDeliveryTimeString, 'has_print' => 1, 'is_printed' => 0, 'sent_option' => 'all', 'message' => NULL), array('id' => $id));
                } else {
                    $success = $this->db->update('gkpos_order', array('online_status' => 1, 'has_print' => 1, 'is_printed' => 0, 'sent_option' => 'all', 'message' => NULL), array('id' => $id));
                }
                if ($success) {
                    if ($this->notify_customer($id)) {
                        $s1 = true;
                    }
                }
            }
            if ((int) $online_status == 2) {
                $success = $this->db->update('gkpos_order', array('online_status' => 2, 'message' => $this->post('message'), 'has_print' => null, 'is_printed' => null, 'sent_option' => null), array('id' => $id));
                if ($success) {
                    if ($this->notify_customer($id)) {
                        $s1 = true;
                    }
                }
            }
            if ((int) $online_status == 0) {
                $success = $this->db->update('gkpos_order', array('online_status' => 0, 'has_print' => null, 'is_printed' => null, 'sent_option' => null, 'message' => null), array('id' => $id));
            }
        }
        $message = "Failed to update. Please try again";
        if ($success) {
            $message = "Status Updated succesfully.";
            if ($s1 && $s1) {
                $message .= ' Notification mail sent to customer and admin';
            } else {
                if ($online_status != 0) {
                    $message .= ' But failed to send notification mail to customer and admin';
                }
            }
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    private function notify_customer($id) {
        if ($this->Printer_Model->exists('gkpos_order', 'id', $id)) {
            $order = $this->Printer_Model->get_single('gkpos_order', array('id' => $id));
            $data['recipent'] = $order->name;
            $data['to'] = $order->email;
            $data['from'] = $this->config->item('gk_email');
            $data['from_title'] = $this->config->item('gk_name');
            if ($order->online_status == 1) {
                $data['subject'] = "Order confirmation from " . $this->config->item('gk_name');
                $data['txt'] = $order->online_type == "collection" ? "You are requested to collect your order #" . strtoupper($order->id) . " from  us at " . $order->delivery_time : ". Your order #" . strtoupper($order->id) . " will be delivered at your order delivery address around " . $order->delivery_time;
            }
            if ($order->online_status == 2) {
                $data['subject'] = "Order Rejection from " . $this->config->item('gk_name');
                $data['txt'] = "Your order # " . strtoupper($order->id) . " has been rejected from " . $this->config->item('gk_name') . ' Restaurant';
                if ($order->message != null) {
                    $data['txt'] .= "<br/> Rejected Reason: " . $order->message;
                }
            }
            $data['verify_link'] = null;
            $data['message'] = $this->load->view('email_template/common', $data, true);
            if ($this->send_email($data)) {
                return true;
            } else {
                return false;
            }
        }
    }

    private function notify_admin($id) {
        if ($this->Printer_Model->exists('gkpos_order', 'id', $id)) {
            $order = $this->Printer_Model->get_single('gkpos_order', array('id' => $id));
            $data['recipent'] = 'Admin';
            $data['to'] = $this->config->item('gk_email');
            $data['from'] = 'info@website';
            $data['from_title'] = $this->config->item('gk_name');
            if ($order->online_status == 1) {
                $data['subject'] = "Customer order confirmation from " . $this->config->item('gk_name');
                $data['txt'] = $order->online_type == "collection" ? "Please ensure that the customer can collect order #" . strtoupper($order->id) . " from " . $this->config->item('gk_name') . ' Restaurant at around ' . $order->delivery_time : "Please ensure that the order #" . strtoupper($order->id) . " delivered at customer delivery address around " . $order->delivery_time;
            }
            if ($order->online_status == 2) {
                $data['subject'] = "Order Rejection from " . $this->config->item('gk_name');
                $data['txt'] = "Customer order # " . strtoupper($order->id) . " has been rejected from Your restaurant";
                if ($order->message != null) {
                    $data['txt'] .= "<br/> Reject Reason " . $order->message;
                }
            }
            $data['verify_link'] = null;
            $data['message'] = $this->load->view('email_template/common', $data, true);
            if ($this->send_email($data)) {
                return true;
            } else {
                return false;
            }
        }
    }

    public function send_email($data = null) {
        if ($data != null || !empty($data)) {
            $this->load->library('email');
            $config['mailtype'] = 'html';
            $config['send_multipart'] = FALSE;
            $config['wordwrap'] = TRUE;
            $this->email->initialize($config);
            $this->email->from($data['from'], $data['from_title']);
            $this->email->to($data['to']);
            $this->email->subject($data['subject']);
            $this->email->message($data['message']);
            $this->email->reply_to($data['from'], $data['from_title']);
            if ($this->email->send()) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
    }

}
