<?php

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

class Report 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('Report_Model');
        $this->load->model('Orders_Model');
        $this->db->cache_delete('gkpos', 'report');
    }

    public function index($segment = 0) {
        $is_by_closing = isset($_POST['is_by_closing']) ? 'yes' : 'no';
        $start_date_value = '';
        $end_date_value = '';
        $limit = $this->config->item('gk_report_line_page');
        if ($is_by_closing == 'yes') {
            $start_date = DateTime::createFromFormat($this->config->item('dateformat'), $this->input->post('start_date') != null ? $this->input->post('start_date') : date($this->config->item('dateformat'), strtotime('today')));
            $end_date = DateTime::createFromFormat($this->config->item('dateformat'), $this->input->post('end_date') != null ? $this->input->post('end_date') : date($this->config->item('dateformat'), strtotime('today')));
            $start_date_value = $start_date->format('Y-m-d');
            $end_date_value = $end_date->format('Y-m-d');
        } else {
            $today_start = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(0, 0, 0));
            $today_end = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(23, 59, 59));
            $start_date = $this->input->post('start_date') != null ? $this->input->post('start_date') . ' ' . date($this->config->item('timeformat'), mktime(0, 0, 0)) : $today_start;
            $start_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $start_date);
            $end_date = $this->input->post('end_date') != null ? $this->input->post('end_date') . ' ' . date($this->config->item('timeformat'), mktime(23, 59, 59)) : $today_end;
            $end_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $end_date);
            $start_date_value = $start_date_formatter->format('Y-m-d H:i:s');
            $end_date_value = $end_date_formatter->format('Y-m-d H:i:s');
        }
        $order_type = $this->input->post('order_type');
        $pos_method = $this->input->post('pos_method');
        $online_method = $this->input->post('online_method');
        $filters = array(
            'order_type' => $order_type,
            'start_date' => $start_date_value,
            'end_date' => $end_date_value,
            'method' => $order_type != 'online' ? $pos_method : $online_method,
            'is_by_closing' => $is_by_closing
        );
        $records = $this->Report_Model->count_report_rows('gkpos_order', $filters);
        $maxCounter = $records > $limit ? ceil($records / $limit) : 0;
        $offset = $segment > 0 ? $segment * $limit : 0;


        $data['current_page'] = "report";
        $data['orderList'] = $this->Report_Model->search($filters, $offset, $limit)->result();
        $data['expense'] = $this->Report_Model->get_expense($filters);
        $data['start_date'] = date($this->config->item('dateformat'), strtotime($start_date_value)); // $start_date_formatter->format($this->config->item('dateformat'));
        $data['end_date'] = date($this->config->item('dateformat'), strtotime($end_date_value));
        $data['payment_options'] = $this->Report_Model->get_payment_options();
        $data['ordertype_options'] = $this->Report_Model->get_ordertype_options();
        $data['maxCounter'] = $maxCounter;
        $data['segment'] = $segment;
        $this->load->view('gkpos/report/index', $data, false);
    }

    public function filter($segment = 0) {
        $is_by_closing = isset($_POST['is_by_closing']) ? 'yes' : 'no';
        $start_date_value = '';
        $end_date_value = '';
        $limit = $this->config->item('gk_report_line_page');
        if ($is_by_closing == 'yes') {
            $start_date = DateTime::createFromFormat($this->config->item('dateformat'), $this->input->post('start_date') != null ? $this->input->post('start_date') : date($this->config->item('dateformat'), strtotime('today')));
            $end_date = DateTime::createFromFormat($this->config->item('dateformat'), $this->input->post('end_date') != null ? $this->input->post('end_date') : date($this->config->item('dateformat'), strtotime('today')));
            $start_date_value = $start_date->format('Y-m-d');
            $end_date_value = $end_date->format('Y-m-d');
        } else {
            $today_start = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(0, 0, 0));
            $today_end = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(23, 59, 59));
            $start_date = $this->input->post('start_date') != null ? $this->input->post('start_date') . ' ' . date($this->config->item('timeformat'), mktime(0, 0, 0)) : $today_start;
            $start_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $start_date);
            $end_date = $this->input->post('end_date') != null ? $this->input->post('end_date') . ' ' . date($this->config->item('timeformat'), mktime(23, 59, 59)) : $today_end;
            $end_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $end_date);
            $start_date_value = $start_date_formatter->format('Y-m-d H:i:s');
            $end_date_value = $end_date_formatter->format('Y-m-d H:i:s');
        }
        $order_type = $this->input->post('order_type');
        $pos_method = $this->input->post('pos_method');
        $online_method = $this->input->post('online_method');
        $filters = array(
            'order_type' => $order_type,
            'start_date' => $start_date_value,
            'end_date' => $end_date_value,
            'method' => $order_type != 'online' ? $pos_method : $online_method,
            'is_by_closing' => $is_by_closing
        );
        $records = $this->Report_Model->count_report_rows('gkpos_order', $filters);
        $maxCounter = $records > $limit ? ceil($records / $limit) : 0;
        $offset = $segment > 0 ? $segment * $limit : 0;
        $data['current_page'] = "report";
        $data['orderList'] = $this->Report_Model->search($filters, $offset, $limit)->result();
        $data['expense'] = $this->Report_Model->get_expense($filters);
        $data['start_date'] = date($this->config->item('dateformat'), strtotime($start_date_value)); // $start_date_formatter->format($this->config->item('dateformat'));
        $data['end_date'] = date($this->config->item('dateformat'), strtotime($end_date_value));
        $data['payment_options'] = $this->Report_Model->get_payment_options();
        $data['ordertype_options'] = $this->Report_Model->get_ordertype_options();
        $data['maxCounter'] = $maxCounter;
        $data['segment'] = $segment;
        $this->load->view('gkpos/report/filtered', $data, false);
    }

    public function deleteReportRow() {
        $order_id = $this->input->post('id');
        $status = $this->Report_Model->delete_order($order_id);
        echo json_encode(array('status' => $status));
    }

    public function closeday() {
        $date = DateTime::createFromFormat($this->config->item('dateformat'), $this->input->post('closing_date'));
        $givenClosingDate = $date->format('Y-m-d');
        $BaseClosingDate = $this->_getmaxclosingday();
        $date2 = DateTime::createFromFormat($this->config->item('dateformat'), $BaseClosingDate);
        $BaseClosingDateFormatted = $date2->format('Y-m-d');
        $givenClosingDateObj = new DateTime($givenClosingDate);
        $BaseClosingDateObj = new DateTime($BaseClosingDateFormatted);
        $interval = $BaseClosingDateObj->diff($givenClosingDateObj);
        if ($interval->format('%a') > 1) {
            echo json_encode(array('success' => false, 'message' => 'Invalid closing date:' . $this->input->post('closing_date')));
        } else {
            $closing_date = array(
                'closing_date' => $givenClosingDate
            );
            if ($this->db->update('gkpos_order', $closing_date, array('closing_date' => NULL))) {
                echo json_encode(array('success' => true, 'message' => 'Days Closed for ' . $this->input->post('closing_date')));
            }
        }
    }

    public function getmaxclosingday() {
        $todayMinOrderDateTime = $this->db->select_min('created')->where('closing_date', NULL)->get('gkpos_order')->row()->created;
        $todayMaxOrderDateTime = $this->db->select_max('created')->where('closing_date', NULL)->get('gkpos_order')->row()->created;
        if ($todayMinOrderDateTime != null && $todayMaxOrderDateTime != null) {
            $todayMinOrderDateTimeObj = new DateTime($todayMinOrderDateTime);
            $todayMaxOrderDateTimeObj = new DateTime($todayMaxOrderDateTime);
            $intervalBetMinAndMaxOrder = $todayMinOrderDateTimeObj->diff($todayMaxOrderDateTimeObj);
            $closingDate = null;
            $hour1 = 0;
            $hour2 = 0;
            if ($intervalBetMinAndMaxOrder->format('%a') > 0) {
                $hour1 = $intervalBetMinAndMaxOrder->format('%a') * 24;
            }
            if ($intervalBetMinAndMaxOrder->format('%h') > 0) {
                $hour2 = $intervalBetMinAndMaxOrder->format('%h');
            }
            $total_hour = $hour1 + $hour2;

            if ($total_hour <= 30) {
                $closingDate = $todayMinOrderDateTimeObj->format($this->config->item('dateformat'));
            } else {
                $closingDate = $todayMaxOrderDateTimeObj->format($this->config->item('dateformat'));
            }
            echo json_encode(array('success' => true, 'availableClosingDate' => $closingDate));
        } else {
            echo json_encode(array('success' => true, 'availableClosingDate' => date($this->config->item('dateformat'))));
        }
    }

    private function _getmaxclosingday() {
        $todayMinOrderDateTime = $this->db->select_min('created')->where('closing_date', NULL)->get('gkpos_order')->row()->created;
        $todayMaxOrderDateTime = $this->db->select_max('created')->where('closing_date', NULL)->get('gkpos_order')->row()->created;
        $closingDate = null;
        if ($todayMinOrderDateTime != null && $todayMaxOrderDateTime != null) {
            $todayMinOrderDateTimeObj = new DateTime($todayMinOrderDateTime);
            $todayMaxOrderDateTimeObj = new DateTime($todayMaxOrderDateTime);
            $intervalBetMinAndMaxOrder = $todayMinOrderDateTimeObj->diff($todayMaxOrderDateTimeObj);
            $hour1 = 0;
            $hour2 = 0;
            if ($intervalBetMinAndMaxOrder->format('%a') > 0) {
                $hour1 = $intervalBetMinAndMaxOrder->format('%a') * 24;
            }
            if ($intervalBetMinAndMaxOrder->format('%h') > 0) {
                $hour2 = $intervalBetMinAndMaxOrder->format('%h');
            }
            $total_hour = $hour1 + $hour2;
            if ($total_hour <= 30) {
                $closingDate = $todayMinOrderDateTimeObj->format($this->config->item('dateformat'));
            } else {
                $closingDate = $todayMaxOrderDateTimeObj->format($this->config->item('dateformat'));
            }
        } else {
            $closingDate = date($this->config->item('dateformat'));
        }
        return $closingDate;
    }

    public function online($segment = 0) {
        $today_start = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(0, 0, 0));
        $today_end = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(23, 59, 59));
        $start_date = $this->input->post('start_date') != null ? $this->input->post('start_date') . ' ' . date($this->config->item('timeformat'), mktime(0, 0, 0)) : $today_start;
        $start_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $start_date);
        $end_date = $this->input->post('end_date') != null ? $this->input->post('end_date') . ' ' . date($this->config->item('timeformat'), mktime(23, 59, 59)) : $today_end;
        $end_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $end_date);
        $start_date_value = $start_date_formatter->format('Y-m-d H:i:s');
        $end_date_value = $end_date_formatter->format('Y-m-d H:i:s');
        $order_type = $this->input->post('order_type');
        $limit = $this->config->item('gk_report_line_page');
        $filters = array(
            'order_type' => $order_type,
            'start_date' => $start_date_value,
            'end_date' => $end_date_value,
            'name' => trim($this->input->post('name')),
            'phone' => trim($this->input->post('phone')),
            'id' => trim($this->input->post('id')),
        );

        $records = $this->Report_Model->count_report_rows_online('gkpos_order', $filters);
        $maxCounter = $records > $limit ? ceil($records / $limit) : 0;
        $offset = $segment > 0 ? $segment * $limit : 0;
        $data['current_page'] = "report";
        $data['orderList'] = $this->Report_Model->search_online($filters, $offset, $limit)->result();
        $data['start_date'] = $start_date_formatter->format($this->config->item('dateformat'));
        $data['end_date'] = $end_date_formatter->format($this->config->item('dateformat'));
        $data['ordertype_options'] = $this->Report_Model->get_onlineordertype_options();
        $data['maxCounter'] = $maxCounter;
        $data['segment'] = $segment;
        $data['payments_option'] = $this->Report_Model->get_payment_options();
        $this->load->view('gkpos/report/online', $data, false);
    }

    public function onlinefilter($segment = 0) {
        $today_start = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(0, 0, 0));
        $today_end = date($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), mktime(23, 59, 59));
        $start_date = $this->input->post('start_date') != null ? $this->input->post('start_date') . ' ' . date($this->config->item('timeformat'), mktime(0, 0, 0)) : $today_start;
        $start_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $start_date);
        $end_date = $this->input->post('end_date') != null ? $this->input->post('end_date') . ' ' . date($this->config->item('timeformat'), mktime(23, 59, 59)) : $today_end;
        $end_date_formatter = DateTime::createFromFormat($this->config->item('dateformat') . ' ' . $this->config->item('timeformat'), $end_date);
        $start_date_value = $start_date_formatter->format('Y-m-d H:i:s');
        $end_date_value = $end_date_formatter->format('Y-m-d H:i:s');
        $order_type = $this->input->post('order_type');
        $limit = $this->config->item('gk_report_line_page');
        $filters = array(
            'order_type' => $order_type,
            'start_date' => $start_date_value,
            'end_date' => $end_date_value,
            'name' => trim($this->input->post('name')),
            'phone' => trim($this->input->post('phone')),
            'id' => trim($this->input->post('id')),
        );

        $records = $this->Report_Model->count_report_rows_online('gkpos_order', $filters);
        $maxCounter = $records > $limit ? ceil($records / $limit) : 0;
        $offset = $segment > 0 ? $segment * $limit : 0;
        $data['current_page'] = "report";
        $data['orderList'] = $this->Report_Model->search_online($filters, $offset, $limit)->result();
        $data['start_date'] = $start_date_formatter->format($this->config->item('dateformat'));
        $data['end_date'] = $end_date_formatter->format($this->config->item('dateformat'));
        $data['ordertype_options'] = $this->Report_Model->get_onlineordertype_options();
        $data['maxCounter'] = $maxCounter;
        $data['segment'] = $segment;
        $data['payments_option'] = $this->Report_Model->get_payment_options();
        $this->load->view('gkpos/report/onlinefiltered', $data, false);
    }

    public function viewdetail($id) {
        if ($this->Report_Model->exists('gkpos_order', 'id', $id)) {
            $data['order'] = $order = $this->Report_Model->get_list('gkpos_order', array('id' => $id));
            $data['items'] = $this->Report_Model->get_list('gkpos_order_detail', array('order_id' => $order[0]->id));
            $discount = $this->Report_Model->get_single('gkpos_order_discount', array('order_id' => $order[0]->id));
            $data['discount'] = !empty($discount) ? $discount->amount : 0;
            $vat = $this->Report_Model->get_single('gkpos_order_vat', array('order_id' => $order[0]->id));
            $data['vat'] = !empty($vat) ? $vat->amount : 0;
            $this->load->view('gkpos/report/order_detail', $data, false);
        }
    }

    function get_delivery_time() {
        $id = $this->input->post('id');
        $delivery_time = $this->Report_Model->get_single('gkpos_order', array('id' => $id), array('delivery_time'));
        echo json_encode(array('delivery_time' => $delivery_time->delivery_time));
    }

    public function update() {
        $id = $this->input->post('id');
        $online_status = $this->input->post('online_status');
        $success = false;
        $s1 = false;
        $s2 = false;
        if ($this->Report_Model->exists('gkpos_order', 'id', $id)) {
            $order = $this->Report_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->input->post('delivery_time');
                if ($additionalMinutes != null) {
                    $nowDate = new DateTime($oldTime);
                    $nowDate->add(new DateInterval('PT' . $additionalMinutes . 'M'));
                    $nowTime = $nowDate->format('h:i a');
                    $success = $this->db->update('gkpos_order', array('online_status' => 1, 'delivery_time' => $nowTime, '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;
                        //sleep(1);
                        //$s2 = $this->notify_admin($id);
                    }
                }
            }
            if ((int) $online_status == 2) {
                $success = $this->db->update('gkpos_order', array('online_status' => 2, 'message' => $this->input->post('message'), 'has_print' => null, 'is_printed' => null, 'sent_option' => null), array('id' => $id));
                if ($success) {
                    if ($this->notify_customer($id)) {
                        $s1 = true;
                        //sleep(1);
                        //$s2 = $this->notify_admin($id);
                    }
                }
            }
            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));
    }

    public function notify_customer($id) {
        if ($this->Report_Model->exists('gkpos_order', 'id', $id)) {
            $order = $this->Report_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;
            }
        }
    }

    public function notify_admin($id) {
        if ($this->Report_Model->exists('gkpos_order', 'id', $id)) {
            $order = $this->Report_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 payopen() {
        $id = $this->input->post('id');
        $data = array();
        if ($this->Report_Model->exists('gkpos_order', 'id', $id)) {
            $data['order'] = $order = $this->Report_Model->get_list('gkpos_order', array('id' => $id));
            $this->Orders_Model->set_current_orderid($order[0]->id);
            $this->Orders_Model->set_total($id, $order[0]->grand_total);
            $data['payments_option'] = $this->Report_Model->get_payment_options();
        }
        $this->load->view('gkpos/report/payopener', $data, false);
    }

    public function get_browser_bill_copy() {
        $id = $this->input->post('id');
        $status = (int) $this->input->post('status');
        if ($this->Report_Model->exists('gkpos_order', 'id', $id)) {
            if ($this->db->update('gkpos_order', array('status' => $status, 'bill_printed' => 1, 'is_printed' => 1, 'has_print' => 0, 'sent_option' => NULL), array('id' => $id))) {
                $this->db->update('gkpos_order_detail', array('changed' => NULL), array('order_id' => $id));
                $doesExist = $this->Orders_Model->exists('gkpos_billcopy', 'order_id', $id);
                $esxistingBillCopy = $doesExist ? $this->db->where('order_id', $id)->get('gkpos_billcopy')->row() : null;
                if ($esxistingBillCopy != null) {
                    $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' => $id,
                        'created' => date('Y-m-d H:i:s'),
                        'created_by' => $this->session->userdata('gkpos_userid'),
                        'status' => 1,
                        'print_count' => 1
                    );
                    $this->db->insert('gkpos_billcopy', $data);
                }
            }
            $data['billOrder'] = $billOrder = $this->Report_Model->get_list('gkpos_order', array('id' => $id));
            $data['billItems'] = $this->Report_Model->get_list('gkpos_order_detail', array('order_id' => $billOrder[0]->id));
            $data['billDiscount'] = $this->Report_Model->get_list('gkpos_order_discount', array('order_id' => $billOrder[0]->id));
            $data['billVat'] = $this->Report_Model->get_list('gkpos_order_vat', array('order_id' => $billOrder[0]->id));
            $data['payments'] = $this->Report_Model->get_list('gkpos_order_payment', array('order_id' => $billOrder[0]->id));
            $this->load->view('gkpos/report/bill_copy', $data, false);
        }
    }

    public function customers() {
        $segment = intval($this->uri->segment(4));
        $offset = $segment ? $segment : 0;
        $limit = $this->config->item('gk_report_line_page');
        if ($offset > 0) {
            $offset *= $limit;
        }
        $result = $this->Report_Model->get_paged_list('gkpos_customer', array(), $url = 'gkpos/report/customer', 4, $offset, 'name', 'DESC');
        $data['customers'] = $result['rows'];
        $pages = $result['total_rows'] / $limit;
        $data['pages'] = round($pages) - 1;
        $data['pagination'] = $result['pagination'];
        $data['count'] = $offset;
        $data['current_page'] = "customers";
        $data['segment'] = $segment > 0 ? $segment : null;
        $this->load->view('gkpos/report/customers', $data, false);
    }

    public function customersfiltered() {
        $filters = array(
            'name' => $this->input->post('name'),
            'phone' => $this->input->post('phone'),
            'email' => $this->input->post('email'),
            'postcode' => $this->input->post('postcode'),
            'city' => $this->input->post('city'),
        );
        $data['customers'] = $this->Report_Model->customers($filters)->result();
        $this->load->view('gkpos/report/customersfiltered', $data, false);
    }

    function update_customer() {
        $name = $this->input->post('name');
        $id = $this->input->post('pk');
        $value = $this->input->post('value');
        $result = $this->db->update('gkpos_customer', array($name => $value), array('phone' => $id));
        echo json_encode(array('status' => $result));
    }

    function add_customer($id = null) {
        $data = array();
        $phone = $this->input->post('phone');
        if ($phone && $phone != 0 && $phone != null) {
            $data['customerInfo'] = $this->Report_Model->get_list('gkpos_customer', array('phone' => $phone));
        }
        $this->load->view('gkpos/report/add_customer', $data, false);
    }

    public function save_customer() {
        $success = false;
        $msg = '';
        $data = $this->input->post();
        if ($data['password'] == null or $data['password'] == '') {
            unset($data['password']);
        }
        $doesExist = $this->Report_Model->get_single('gkpos_customer', array('phone' => $data['phone']));
        if (isset($data['id']) && $data['id'] != null) {
            $id = $data['id'];
            $preparedData = $this->prepareGkposData($data);
            if (array_key_exists('password', $preparedData)) {
                $preparedData['password'] = md5($preparedData['password']);
            }
            if ($id == $data['phone'] && $doesExist) {
                unset($preparedData['phone']);
                $success = $this->db->update('gkpos_customer', $preparedData, array('phone' => $id));
                $msg = 'Customer data updated successfully';
            } else {
                if ($data['id'] != $data['phone'] && !$doesExist) {
                    $success = $this->db->update('gkpos_customer', $preparedData, array('phone' => $id));
                    $msg = 'Customer data updated successfully';
                } else {
                    $success = false;
                    $msg = 'This phone number/email already belogns to someone else';
                }
            }
        } else {
            $preparedData = $this->prepareData();
            if ($doesExist) {
                echo json_encode(array('success' => $success, 'message' => 'Customer already exists with that phone number'));
                exit();
            }
            if ($doesExist && $doesExist->email == $preparedData['email']) {
                echo json_encode(array('success' => $success, 'message' => 'Customer already exists with that email address'));
                exit();
            }
            $preparedData['status'] = 1;
            $preparedData['is_verified'] = 1;
            if (array_key_exists('password', $preparedData)) {
                $preparedData['password'] = md5($preparedData['password']);
            }
            if ($data['email'] != '') {
                $preparedData['is_online'] = 1;
            }
            $success = $this->db->insert('gkpos_customer', $preparedData);
            $msg = $success ? 'Customer data saved Successfully' : 'Save failed please try again';
        }
        echo json_encode(array('success' => $success, 'message' => $msg));
    }

    public function emptyuseless() {
        $table = $this->input->post('table');
        $success = false;
        if ($this->db->table_exists($table)) {
            if ($table == 'gkpos_billcopy' || $table == 'gkpos_caller' || $table == 'gkpos_table' || $table == 'gkpos_log' || $table == 'gkpos_order_lookup') {
                $success = $this->db->truncate($table);
            }
            if ($success) {
                if ($table == 'gkpos_order_lookup') {
                    $subject = 'locks';
                } else {
                    $subject = str_replace('gkpos_', '', $table);
                }
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has cleard all ' . $subject
                );
                $this->Report_Model->posactivity($activity);
            }
        }
        $msg = $success ? 'Clear successfully' : 'Clear failed';
        echo json_encode(array('success' => $success, 'message' => $msg));
    }

    public function release_all_locks() {
        $table = $this->input->post('table');
        $success = false;
        if ($this->db->table_exists($table)) {
            if ($table == 'gkpos_order_lookup') {
                $success = $this->db->update($table, array('is_locked' => 0), array('is_locked' => 1));
            }
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has released all locks on orders'
                );
                $this->Report_Model->posactivity($activity);
            }
        }
        $msg = $success ? 'All locks released successfully' : 'lock releasing failed';
        echo json_encode(array('success' => $success, 'message' => $msg));
    }

    public function vacant_table() {
        $table = $this->input->post('table');
        $id = $this->input->post('id');
        $success = false;
        if ($this->db->table_exists($table)) {
            if ((int) $id > 0) {
                $success = $this->db->update($table, array('is_vacant' => 1), array('id' => $id));
            } else {
                $success = $this->db->update($table, array('is_vacant' => 1), array('is_vacant' => 2));
            }
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has vacated table ' . $id > 0 ? $id : ''
                );
                $this->Report_Model->posactivity($activity);
            }
        }
        $msg = $success ? 'Table released successfully' : 'Operation Failed';
        echo json_encode(array('success' => $success, 'message' => $msg));
    }

}
