<?php

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

class Orders extends MY_Controller {

    var $cats;
    var $thispage;
    var $call_center = 0;
    var $type = 0;

    public function __construct() {
        parent::__construct();
        $this->load->model('booking');
        $this->thispage = "orders";
        $this->db->from('bills_orders');
        $this->db->where("start_date_t  IS NULL");
        $data['all_groups'] = $this->db->get()->result_array();
        $this->operator_id = $this->session->userdata('operator_id');
        if (!get_license_per('sales')) {
            redirect("", "refresh");
        }
//        if (get_ap('accountant', $this->operator_id) == 1) {
//            
//        } else {
//            redirect("", "refresh");
//        }
        foreach ($data['all_groups'] as $row) {
            $datearsh1 = explode("/", $row['start_date']);
            $day1 = $datearsh1[0];
            $month1 = $datearsh1[1];
            $year1 = $datearsh1[2];
            $start_date = strtotime("$year1-$month1-$day1");

            $datearsh1 = explode("/", $row['expiry_date']);
            $day1 = $datearsh1[0];
            $month1 = $datearsh1[1];
            $year1 = $datearsh1[2];
            $expiry_date = strtotime("$year1-$month1-$day1");


            $datearsh1 = explode("/", $row['date_now']);
            $day1 = $datearsh1[0];
            $month1 = $datearsh1[1];
            $year1 = $datearsh1[2];
            $date_now = strtotime("$year1-$month1-$day1");
            $edit_data = array(
                'start_date_t' => $start_date,
                'expiry_date_t' => $expiry_date,
                'date_now_t' => $date_now,
            );
            $edit_data = $this->security->xss_clean($edit_data);
            $result = $this->db->where('id', $row['id'])->update('bills_orders', $edit_data);
        }
        $edit_data = array(
            'active' => '0',
        );
        $edit_data = $this->security->xss_clean($edit_data);
        $result = $this->db->update('bills_orders', $edit_data);

        $edit_data = array(
            'active' => '1',);
        $edit_data = $this->security->xss_clean($edit_data);
        $result = $this->db->where("expiry_date_t<" . $this->booking->tissme_now())->update('bills_orders', $edit_data);



        $edit_data = array(
            'stop' => '1',
        );
        $edit_data = $this->security->xss_clean($edit_data);
        $result = $this->db->update('bills_user', $edit_data);
        $this->db->from('bills_orders');
        $this->db->where("active='0'");
        $data['all_groups'] = $this->db->get()->result_array();
        foreach ($data['all_groups'] as $row) {

            $edit_data = array(
                'stop' => '2',
            );
            $edit_data = $this->security->xss_clean($edit_data);
            $result = $this->db->where('id', $row['id_user'])->update('bills_user', $edit_data);
        }
    }

    public function index($cats = 1, $call_center = 0, $type = 0, $order_status = -1) {
        if ((!$call_center && !get_ap('invoices', $this->operator_id)) ||
                ($call_center && !get_ap('call_show_orders', $this->operator_id))) {
            redirect("", "refresh");
        }
        $this->cats = $cats;
        $this->call_center = $call_center;
        $this->type = $type;
        $this->order_status = $order_status;
        $this->all($cats);
    }

    public function all($page = 1, $id_producer = '', $active = '') {
//        $searchfor = $this->security->xss_clean($this->input->get('search'));
//        $whr = '';
//        $data['id_producer'] = $id_producer;
//        $data['active'] = $active;
//        if (($id_producer))
//            $whr = " id_producer=$id_producer";
//        if (($active))
//            $whr = "$whr and active=" . str_replace("2", "0", $active);
//        $this->db->from('bills_orders');
//        if ($whr)
//            $this->db->where($whr);
//        $max = 40;
//        $data['all_count'] = ceil($this->db->count_all_results() / $max);
//        $this->db->from('bills_orders');
//        $this->db->order_by('orders.timestamp', 'desc');
//        if ($whr)
//            $this->db->where($whr);
//        // $this->db->limit($max, ($max * $page) - $max);
//        $this->db->select('bills_orders.*,sum(bills_orders.discount_remainder) as total_price,user.name as created_name,orders.order_status,orders.order_status,orders.delivery_type,'
//                . 'orders.payment_method,bills_user.username,bills_user.phone,bills_user.phone_code,bills_user.email,orders.delivery_type,orders.expected_delivery_time,orders.timestamp');
//        $this->db->group_by('id_orders');
//        if ($this->input->post('start_expiry')) {
//            $date_arr = explode(' - ', $this->input->post('start_expiry'));
//            $from = date('Y-m-d', strtotime($date_arr[0]));
//            $to = date('Y-m-d', strtotime($date_arr[1]));
//            $this->db->where(array('bills_orders.start_date >=' => $from, 'bills_orders.start_date <=' => $to));
//        }
//        if (!empty($this->input->post('products'))) {
//            $this->db->where_in('bills_orders.name_order', $this->input->post('products'));
//        }
//        if (!empty($this->input->post('username'))) {
//            $this->db->where_in('bills_orders.name', $this->input->post('username'));
//        }
//        if (!empty($this->input->post('order_status'))) {
//            $this->db->where_in('orders.order_status', $this->input->post('order_status'));
//        }
//        if (!empty($this->input->post('admins'))) {
//            $this->db->where_in('orders.created_by', $this->input->post('admins'));
//        }
//
//        $this->db->join('orders', 'orders.id=bills_orders.id_orders');
//        $this->db->join('user', 'user.id=orders.created_by', 'left');
//        $this->db->join('bills_user', 'bills_user.id=bills_orders.id_user', 'left');
//        if ($this->type) {
//            $this->db->where('type', 1);
//        } else {
//            $this->db->where('type', 0);
//            if ($this->call_center) {
//                $this->db->where('call_center', 1);
//            } else {
//                $this->db->group_start();
//                $this->db->group_start();
//                $this->db->where('call_center', 1);
//                $this->db->where('order_status !=', 0);
//                $this->db->where('order_status !=', 5);
//                $this->db->group_end();
//                $this->db->or_where('call_center', 0);
//                $this->db->group_end();
//            }
//            if ($this->order_status != -1) {
//                $this->db->where('order_status', $this->order_status);
//            }
//        }
//
//        $data['all_groups'] = $this->db->get()->result_array();
//        //echo $this->db->last_query();die;
//        if ($searchfor) {
//            $this->booking->add_rep_user("  البحث عن    " . $searchfor);
//            $split_stemmed = explode(" ", $searchfor);
//            $whr = " (";
//            while (list($key, $val) = @each($split_stemmed)) {
//                if ($val <> " " and strlen($val) > 0) {
//
//                    $whr .= " ( BINARY name LIKE '%" . $val . "%'   ) and";
//                }
//            }
//            $whr = substr($whr, 0, (strLen($whr) - 4));
//            $whr .= " )or     cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";
//
//            if (!$this->session->userdata('group'))
//                $whr = " cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";
//            $this->db->select('bills_orders.*,sum(bills_orders.payment) as total_price');
//            $this->db->group_by('id_orders');
//            $this->db->where($whr);
//            $query = $this->db->get('bills_orders');
//            $data['all_count'] = 0;
//            $whr = '';
//            $data['all_groups'] = $query->result_array();
//            $data['all_count'] = count($data['all_groups']);
//            // echo print_r($this->db->last_query());
//        }
//        /// $whr=" cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";
//        // foreach ($data['all_groups'] as $row) {
//        //$data['all_groups']['allcat']=$this->db->from('cat')->where("parentcatid=".$row['catid'])->count_all_results();
//        //}
        $data['title'] = $this->call_center ? $this->lang->line('orders') : $this->lang->line('bills');
        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
        $data['thispage'] = $this->thispage;
        $data['products'] = $this->db->get('bills_producer')->result();
        $data['username'] = $this->db->get('bills_user')->result();
        $data['admins'] = $this->db->get('user')->result();
//        if (get_license_per('order_status')) {
//            $data['order_status_counts'] = $this->get_order_status_counts($this->call_center);
//        }
        $this->load->view('site/' . $this->thispage . '/all', $data);
    }

    function get_order_status_counts($call_center = 0) {
        $filter = json_decode($this->input->post('data'));
//        $this->db->select("SUM(CASE WHEN t.order_status = '0' THEN 1 ELSE 0 END) AS waiting");
//        $this->db->select("SUM(CASE WHEN t.order_status = '1' THEN 1 ELSE 0 END) AS preparing");
//        $this->db->select("SUM(CASE WHEN t.order_status = '2' THEN 1 ELSE 0 END) AS ready_for_deliver");
//        $this->db->select("SUM(CASE WHEN t.order_status = '3' THEN 1 ELSE 0 END) AS delivering");
//        $this->db->select("SUM(CASE WHEN t.order_status = '4' THEN 1 ELSE 0 END) AS delivered");
//        $this->db->select("SUM(CASE WHEN t.order_status = '5' THEN 1 ELSE 0 END) AS canceled");
        $order_status = array('waiting', 'preparing', 'ready_for_deliver', 'delivering', 'delivered', 'canceled');
        for ($i = 0; $i < 7; $i++) {
            $this->db->select('t.id');
            $this->check_filters($filter);
            if ($i != 6) {
                $this->db->where('t.order_status', $i);
            }
            $this->db->where('type', 0);
            if ($call_center) {
                $this->db->where('call_center', 1);
            } else {
                $this->db->group_start();
                $this->db->group_start();
                $this->db->where('call_center', 1);
                $this->db->where('order_status !=', 0);
                $this->db->where('order_status !=', 5);
                $this->db->group_end();
                $this->db->or_where('call_center', 0);
                $this->db->group_end();
            }
            $this->db->join('bills_orders', 'bills_orders.id_orders = t.id');
            $this->db->group_by('bills_orders.id_orders');
//        $this->db->where('bills_orders.id', '(select min(o2.id)
//              from bills_orders o2
//              where o2.id_orders = bills_orders.id_orders
//             )', FALSE);
            if ($i != 6) {
                $order_status[$order_status[$i]] = $this->db->get('orders t')->num_rows();
            } else {
                $order_status['all_data'] = $this->db->get('orders t')->num_rows();
            }
        }
        echo json_encode($order_status);
    }

    function check_filters($filter) {
        if (isset($filter->start_expiry) && $filter->start_expiry) {
            $date_arr = explode(' - ', $filter->start_expiry);
            $from = date('Y-m-d', strtotime($date_arr[0]));
            $to = date('Y-m-d', strtotime($date_arr[1]));
            $this->db->where(array('t.timestamp >=' => $from, 't.timestamp <=' => $to));
        }
        if (!empty($filter->products)) {
            $this->db->where_in('bills_orders.name_order', $filter->products);
        }
        if (!empty($filter->username)) {
            $this->db->where_in('bills_orders.name', $filter->username);
        }
        if (!empty($filter->order_status)) {
            $this->db->where_in('t.order_status', $filter->order_status);
        }
        if (isset($filter->payment_status) && $filter->payment_status != 0) {
            $this->db->where_in('bills_orders.paid', $filter->payment_status);
        }
    }

    function membership($page = 1, $id_producer = '', $active = '') {
        if (get_ap('subscription', $this->operator_id) != 1) {
            redirect("", "refresh");
        }
        $searchfor = $this->security->xss_clean($this->input->get('search'));
        $whr = '';
        $data['id_producer'] = $id_producer;
        $data['active'] = $active;
        if (($id_producer))
            $whr = " id_producer=$id_producer";
        if (($active))
            $whr = "$whr and active=" . str_replace("2", "0", $active);
        $this->db->from('bills_orders');
        if ($whr)
            $this->db->where($whr);
        $max = 40;
        $data['all_count'] = ceil($this->db->count_all_results() / $max);
        $this->db->from('bills_orders');
        $this->db->order_by('bills_orders.id', 'desc');
        if ($whr)
            $this->db->where($whr);
        $this->db->select('bills_orders.*');
        //$this->db->limit($max, ($max * $page) - $max);
        $this->db->join('bills_producer', 'bills_producer.id=bills_orders.id_producer and bills_producer.type=2');
        if ($this->input->post('start_expiry')) {
            $date_arr = explode(' - ', $this->input->post('start_expiry'));
            $from = date('Y-m-d', strtotime($date_arr[0]));
            $to = date('Y-m-d', strtotime($date_arr[1]));
            $this->db->where(array('bills_orders.start_date >=' => $from, 'bills_orders.start_date <=' => $to));
        }
        if (!empty($this->input->post('products'))) {
            $this->db->where_in('bills_orders.name_order', $this->input->post('products'));
        }
        if (!empty($this->input->post('username'))) {
            $this->db->where_in('bills_orders.name', $this->input->post('username'));
        }
        $this->db->join('orders', 'orders.id=bills_orders.id_orders');
        $this->db->where('call_center', 0);
        $data['all_groups'] = $this->db->get()->result_array();
        if ($searchfor) {
            $this->booking->add_rep_user("  البحث عن    " . $searchfor);
            $split_stemmed = explode(" ", $searchfor);
            $whr = " (";
            while (list($key, $val) = @each($split_stemmed)) {
                if ($val <> " " and strlen($val) > 0) {

                    $whr .= " ( BINARY name LIKE '%" . $val . "%'   ) and";
                }
            }
            $whr = substr($whr, 0, (strLen($whr) - 4));
            $whr .= " )or     cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";

            if (!$this->session->userdata('group'))
                $whr = " cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";
            $this->db->group_by('id_orders');
            $this->db->join('bills_producer', 'bills_producer.id=bills_orders.id_producer and bills_producer.type=2');
            $this->db->where($whr);
            $this->db->from('bills_orders');
            $query = $this->db->get();
            $data['all_count'] = 0;
            $whr = '';
            $data['all_groups'] = $query->result_array();
            $data['all_count'] = count($data['all_groups']);
            // echo print_r($this->db->last_query());
        }
        /// $whr=" cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";
        foreach ($data['all_groups'] as $row) {
            //$data['all_groups']['allcat']=$this->db->from('cat')->where("parentcatid=".$row['catid'])->count_all_results();
        }
        $data['title'] = $this->lang->line('subscription');
        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
        $data['thispage'] = $this->thispage;
        $data['products'] = $this->db->get('bills_producer')->result();
        $data['username'] = $this->db->get('bills_user')->result();
        $this->load->view('site/' . $this->thispage . '/membership', $data);
    }

    function additions_check() {
        $products = $this->input->post('id_producer');
        $error_msg = '';
        foreach ($products as $product) {
            $product_name = $this->db->get_where('bills_producer', array('id' => $product))->row();
            if (!$product_name) {
                continue;
            }
            $product_name = $this->lang->line('language') == 'english' ? $product_name->name : $product_name->arabic_name;
            $required = $this->db->get_where('product_additions', array('product_id' => $product, 'required' => 1))->result();
            foreach ($required as $req) {
                if (!($this->input->post('addition_id[' . $product . ']') !== '' &&
                        is_array($this->input->post('addition_id[' . $product . ']')) &&
                        in_array($req->id, $this->input->post('addition_id[' . $product . ']')))) {
                    $error_msg .= $this->lang->line('language') == 'english' ? $req->title_en : $req->title_ar . $this->lang->line('for_product') . ' ' . $product_name . ' , ';
                }
            }
        }
        if ($error_msg == '') {
            return TRUE;
        }
        $this->form_validation->set_message('additions_check', $this->lang->line('have_to_choose') . ' ' . $error_msg);
        return FALSE;
    }

    public function add($call_center = 0) {
        if ((!$call_center && !get_ap('invoice_add', $this->operator_id)) ||
                ($call_center && !get_ap('call_add_order', $this->operator_id))) {
            redirect("", "refresh");
        }
        $add = FALSE;
        $error_msg = '';
        $this->cats = 1;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('id_producer[]', 'products', 'trim|required|callback_additions_check');
            $this->form_validation->set_rules('id_user[]', 'user', 'trim|required');
            $this->form_validation->set_rules('quantity[]', 'quantity', 'trim|required');
            if ($call_center && $this->input->post('delivery_type') == 1) {
                // check if address not selected for a user
                $id_user = $this->input->post('id_user');
//                print_r($id_user);die;
                if ($id_user) {
                    foreach ($id_user as $selectedOption) {
                        $query = $this->db->get_where('bills_user', array('id' => $selectedOption))->row();
                        if ($query) {
                            $this->form_validation->set_rules('address_' . $selectedOption, $query->username . ' address', 'trim|required');
                        }
                    }
                }
            }
            //	$this->form_validation->set_rules('comment', '', 'trim|required'); 
            //	$this->form_validation->set_rules('comm', '', 'trim|required'); 
            if ($this->form_validation->run() === FALSE) {
                $add = FALSE;
            } else {
//                $start_expiry = $this->input->post('start_expiry');
//                $datearsh11 = explode("-", $start_expiry);
//                $datearsh1 = explode("/", trim($datearsh11[0]));
//                $start_date = "$datearsh1[0]/$datearsh1[1]/$datearsh1[2]";
//                $start_date_t = strtotime("$datearsh1[2]-$datearsh1[0]-$datearsh1[1]");
//                $datearsh1 = explode("/", trim($datearsh11[1]));
//                $expiry_date = "$datearsh1[0]/$datearsh1[1]/$datearsh1[2]";
//                $expiry_date_t = strtotime("$datearsh1[2]-$datearsh1[0]-$datearsh1[1]");
                $id_producer = $this->input->post('id_producer');
                $id_user = $this->input->post('id_user');
//                $discount = $this->input->post('discount');
                $discount_why = $this->input->post('discount_why');
                $paid = $this->input->post('paid');
                $type = $this->input->post('type') ? $this->input->post('type') : 0;
                $result = FALSE;
                if (empty($id_producer)) {
                    $add = FALSE;
                    $error_msg = $this->lang->line('order_must_have_items');
                } else {
                    foreach ($id_user as $selectedOption) {
                        $query = $this->db->get_where('bills_user', array('id' => $selectedOption));
                        $dataaa = $query->row_array();
                        $name = $dataaa['username'];
                        $user_id = $dataaa['id'];
                        $sex = $dataaa['sex'];
                        $add = TRUE;
                        $order_insert = array('timestamp' => date('Y-m-d H:i:s'), 'call_center' => $call_center,
                            'payment_method' => $this->input->post('payment_method'),
                            'created_by' => $this->session->userdata('admin_id'), 'address_id' => $this->input->post('address_' . $user_id) ? $this->input->post('address_' . $user_id) : 0,
                            'type' => $type, 'discount_type' => $this->input->post('discount_type'),
                            'delivery_type' => $this->input->post('delivery_type') ? $this->input->post('delivery_type') : 0);
                        if ($call_center) {
                            $order_insert['expected_delivery_time'] = $this->input->post('expected_delivery_time');
                        }
                        $this->db->insert('orders', $order_insert);
                        $order_id = $this->db->insert_id();
                        $i = 0;
                        foreach ($id_producer as $pro => $p_id) {

                            $query = $this->db->get_where('bills_producer', array('id' => $p_id));
                            $data['edit'] = $query->row_array();
                            $name_order = $data['edit']['name'];
                            if ($data['edit']['type'] == 1) {
                                $discount_remainder = $payment = $this->input->post('amount')[$i] * $this->input->post('quantity')[$i];
                            } else {
                                $discount_remainder = $payment = $this->input->post('amount')[$i];
                            }
                            $discount = $this->input->post('discount')[$i];
                            if ($discount == '')
                                $discount = 0;
                            $discount_amount = $discount;
                            if ($this->input->post('discount_type') == 1) {
                                $discount_amount = round(($payment * $discount) / 100, 2);
                            }
                            $discount_remainder = $payment - $discount_amount;


                            if ($paid == 4 OR $paid == 3) {
                                $payment = 0;
                                $discount = 0;
                                $discount_remainder = 0;
                            }
                            $dataadd['id_user'] = $user_id;
                            // foreach()
                            $dataadd['item_price'] = $data['edit']['valuess'];
                            $dataadd['start_date'] = $this->input->post('start_date')[$i];
                            $dataadd['id_producer'] = $p_id;
                            $dataadd['expiry_date'] = $this->input->post('end_date')[$i];
                            $dataadd['start_date_t'] = strtotime($this->input->post('start_date')[$i]);
                            $dataadd['expiry_date_t'] = strtotime($this->input->post('end_date')[$i]);
                            $dataadd['date_now'] = date("Y-m-d", $this->booking->tissme_now());
                            $dataadd['date_now_t'] = $this->booking->tissme_now();
                            $dataadd['payment'] = round($payment, 3);
                            $dataadd['discount'] = round($discount, 3);
                            $dataadd['discount_remainder'] = round($discount_remainder, 3);
                            $dataadd['discount_why'] = $discount_why;
                            $dataadd['name_order'] = $name_order;
                            $dataadd['since_time_register'] = $this->booking->tissme_now();
                            $dataadd['name'] = $name;
                            $dataadd['sex'] = $sex;
                            $dataadd['paid'] = $paid;
                            $dataadd['id_orders'] = $order_id;
                            $dataadd['active'] = "0";
                            $dataadd['note'] = $this->input->post('note');
                            $dataadd['quantity'] = $this->input->post('quantity')[$i];
                            $dataadd['comment'] = $this->input->post('comment')[$i];


                            $dataadd = $this->security->xss_clean($dataadd);
                            $result = $this->db->insert('bills_orders', $dataadd);
                            $bills_orders_id = $this->db->insert_id();
                            $index = 0;
                            if ($this->input->post('addition_id[' . $p_id . ']')) {
                                foreach ($this->input->post('addition_id[' . $p_id . ']') as $value) {
                                    $this->db->insert('order_products_additions', array('order_product_id' => $bills_orders_id,
                                        'product_addition_id' => $value,
                                        'choice_id' => $this->input->post('choice[' . $p_id . '][' . $index . ']')));
                                    $index++;
                                }
                            }
                            $i++;
                        }
                        // send payment sms if order_status not enabled
                        if (!get_license_per('order_status') && $this->input->post('payment_method') == 3) {
                            $this->User_model->send_sms($order_id, 'payment_msg');
                        }
                    }
                    if ($result) {
                        $this->load->model('admin/User_model');
                        $this->User_model->send_sms($order_id, 'new_order');
                        $this->session->set_flashdata('msg', 'تم اضافة الفاتورة بفضل الله!');
                        if ($type) {
                            redirect(base_url('' . $this->thispage . '/index/1/1/1'));
                        }
                        if (!$call_center) {
                            redirect(base_url('' . $this->thispage . '/index/'));
                        }
                        if ($this->input->post('submit') == 'edit_status') {
                            redirect(base_url('Orders/edit_order_status/' . $order_id));
                        }
                        redirect(base_url('call_center/CallCenter/show_orders'));
                    }
                }
            }
        }


        if (!$add) {

            $this->db->from('bills_user');
            $this->db->order_by('id', 'desc');
            $this->db->where("block !=", 1);
            $this->db->where('approve_status', 1);
            $data['bills_user'] = $this->db->get()->result_array();

            $this->db->from('bills_producer');
            $this->db->order_by('id', 'desc');
            $this->db->where(" active='1' ");
            $data['bills_producer'] = $this->db->get()->result_array();
            //$data['cats_select']  = $this->db->get()->result_array(); 
            $data['title'] = 'اضافة عميل';
            //$data['cats'] = $this->cats;
            $data['thispage'] = $this->thispage;
            // $data['view'] = '../controllers/views/' . $this->thispage . '/add';
            $data['fields_arr'] = array('username' => $this->lang->line('name'),
//                'name' => $this->lang->line('name'),
                'cid_user' => $this->lang->line('civil-no'), 'email' => $this->lang->line('e-mail'), 'password' => $this->lang->line('password'),
                'phone' => $this->lang->line('students') . ' ' . $this->lang->line('mobile'),
                'phone_father' => $this->lang->line('guardian') . ' ' . $this->lang->line('mobile'), 'country' => $this->lang->line('nationality'),
                'city' => $this->lang->line('region'), 'blocks' => $this->lang->line('block'), 'street' => $this->lang->line('street'), 'jadah' => $this->lang->line('jadah'),
                'building_num' => $this->lang->line('building_num'),
                'floor' => $this->lang->line('floor'), 'door_no' => $this->lang->line('door-number'), 'address_link' => $this->lang->line('address-link'), 'title' => $this->lang->line('title'),
                'age' => $this->lang->line('date-of-birth'), 'sex' => $this->lang->line('sex'), 'father_work' => $this->lang->line('father_work'), 'mother_work' => $this->lang->line('mother_work'),
                'social_status' => $this->lang->line('social_status'), 'note' => $this->lang->line('note'));
            $this->db->select('customer_fields,show_customer_fields');
            $sett = $this->db->get('setting')->row();
            $data['required_fields'] = explode(',', $sett->customer_fields);
            $data['show_fields'] = explode(',', $sett->show_customer_fields);

            $this->db->where('lable', 'nationality');
            $data['nationality'] = $this->db->get('datas')->result();
            $this->db->where('lable', 'region');
            $data['region'] = $this->db->get('datas')->result();
            $data['call_center'] = $call_center;
            $data['error_msg'] = $error_msg;

            $this->load->view('site/' . $this->thispage . '/add', $data);
        }
    }

    public function edit_invoice($order_id, $call_center = 0) {
        if ((!$call_center && !get_ap('invoice_edit', $this->operator_id)) ||
                ($call_center && !get_ap('call_edit_order', $this->operator_id))) {
            redirect("", "refresh");
        }
        $add = FALSE;
        $error_msg = '';
        $this->db->join('addresses', 'addresses.id=orders.address_id', 'left');
        $order = $this->db->get_where('orders', array('orders.id' => $order_id))->row();
        //$this->cats = $cats;
        //  print_R($this->input->post());die;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('id_producer[]', $this->lang->line('products'), 'trim|required|callback_additions_check');
            if ($this->form_validation->run() === FALSE) {
                $add = FALSE;
            } else {

                $id_producer = $this->input->post('id_producer');
                //                $discount = $this->input->post('discount');
                $discount_why = $this->input->post('discount_why');
                $paid = $this->input->post('paid');
                $type = $this->input->post('type');
                $result = FALSE;
                if (empty($id_producer)) {
                    $add = FALSE;
                    $error_msg = $this->lang->line('order_must_have_items');
                } else {
                    $add = TRUE;

                    $this->db->update('orders', array(
                        'payment_method' => $this->input->post('payment_method'),
                        'type' => $type,
                        'discount_type' => $this->input->post('discount_type'), 'delivery_type' => $this->input->post('delivery_type'),
                        'payment_method' => $this->input->post('payment_method')), array('id' => $order_id));
                    $order_items = $this->db->get_where('bills_orders', array('id_orders' => $order_id))->result();
                    $name = $order_items[0]->name;
                    $user_id = $order_items[0]->id_user;
                    $sex = $order_items[0]->sex;
                    $date_now = $order_items[0]->date_now;
                    $date_now_t = $order_items[0]->date_now_t;
                    $i = 0;
                    $this->db->delete('bills_orders', array('id_orders' => $order_id));

                    foreach ($id_producer as $pro => $p_id) {

                        $query = $this->db->get_where('bills_producer', array('id' => $p_id));
                        $data['edit'] = $query->row_array();
                        $name_order = $data['edit']['name'];
                        if ($data['edit']['type'] == 1) {
                            $discount_remainder = $payment = $this->input->post('amount')[$i] * $this->input->post('quantity')[$i];
                        } else {
                            $discount_remainder = $payment = $this->input->post('amount')[$i];
                        }
                        $discount = $this->input->post('discount')[$i];
                        if ($discount == '')
                            $discount = 0;

                        $discount_amount = $discount;
                        if ($this->input->post('discount_type') == 1) {
                            $discount_amount = round(($payment * $discount) / 100, 2);
                        }
                        $discount_remainder = $payment - $discount_amount;

                        if ($paid == 4 OR $paid == 3) {
                            $payment = 0;
                            $discount = 0;
                            $discount_remainder = 0;
                        }
                        $dataadd['id_user'] = $user_id;
                        // foreach()
                        $dataadd['item_price'] = $data['edit']['valuess'];
                        $dataadd['start_date'] = $this->input->post('start_date')[$i];
                        $dataadd['id_producer'] = $p_id;
                        $dataadd['expiry_date'] = $this->input->post('end_date')[$i];
                        $dataadd['start_date_t'] = strtotime($this->input->post('start_date')[$i]);
                        $dataadd['expiry_date_t'] = strtotime($this->input->post('end_date')[$i]);
                        $dataadd['date_now'] = $date_now;
                        $dataadd['date_now_t'] = $date_now_t;
                        $dataadd['payment'] = round($payment, 3);
                        $dataadd['discount'] = round($discount, 3);
                        $dataadd['discount_remainder'] = round($discount_remainder, 3);
                        $dataadd['discount_why'] = $discount_why;
                        $dataadd['name_order'] = $name_order;
                        $dataadd['since_time_register'] = $date_now_t;
                        $dataadd['name'] = $name;
                        $dataadd['sex'] = $sex;
                        $dataadd['paid'] = $paid;
                        $dataadd['id_orders'] = $order_id;
                        $dataadd['active'] = "0";
                        $dataadd['note'] = $this->input->post('note');
                        $dataadd['quantity'] = $this->input->post('quantity')[$i];
                        $dataadd['comment'] = $this->input->post('comment')[$i];


                        $dataadd = $this->security->xss_clean($dataadd);
                        $result = $this->db->insert('bills_orders', $dataadd);
                        $bills_orders_id = $this->db->insert_id();
                        $index = 0;
                        if ($this->input->post('addition_id[' . $p_id . ']')) {
                            foreach ($this->input->post('addition_id[' . $p_id . ']') as $value) {
                                $this->db->insert('order_products_additions', array('order_product_id' => $bills_orders_id,
                                    'product_addition_id' => $value,
                                    'choice_id' => $this->input->post('choice[' . $p_id . '][' . $index . ']')));
                                $index++;
                            }
                        }
                        $i++;
                    }

                    if ($result) {
                        $this->session->set_flashdata('msg', 'تم تعديل الفاتورة بفضل الله!');
                        if ($type) {
                            redirect(base_url('' . $this->thispage . '/index/1/1/1'));
                        }
                        if (!$call_center) {
                            redirect(base_url('' . $this->thispage . '/index/'));
                        }
                        if ($this->input->post('submit') == 'edit_status') {
                            redirect(base_url('Orders/edit_order_status/' . $order_id));
                        }
                        redirect(base_url('call_center/CallCenter/show_orders'));
                    }
                }
            }
        }


        if (!$add) {


            $this->db->from('bills_producer');
            $this->db->order_by('id', 'desc');
            $this->db->where(" active='1' ");
            $data['bills_producer'] = $this->db->get()->result_array();
            //$data['cats_select']  = $this->db->get()->result_array();
            $data['title'] = 'تعديل عميل';
            //$data['cats'] = $this->cats;
            $data['thispage'] = $this->thispage;
            // $data['view'] = '../controllers/views/' . $this->thispage . '/add';

            $data['order'] = $order;
            $this->load->model('admin/Orders_model');
            $data['order_items'] = $this->Orders_model->get_order_products($order_id);
            // $data['order_items'] = $this->db->get_where('bills_orders', array('id_orders' => $order_id))->result();
            $data['order_id'] = $order_id;
            $data['call_center'] = $call_center;
            $data['error_msg'] = $error_msg;

            $this->load->view('site/' . $this->thispage . '/edit_invoice', $data);
        }
    }

    public function printorder($id) {
        $this->db->select('bills_orders.paid,bills_orders.note,bills_orders.date_now,bills_orders.id_orders,bills_orders.date_now,bills_orders.name,'
                . 'bills_orders.id_user,addresses.*,bills_user.username,bills_user.phone,orders.timestamp as date');
        $this->db->join('orders', 'orders.id = bills_orders.id_orders');
        $this->db->join('addresses', 'addresses.id=orders.address_id', 'left');
        $this->db->join('bills_user', 'bills_user.id=bills_orders.id_user', 'left');
        $query = $this->db->get_where('bills_orders', array('bills_orders.id' => $id));
        $data['show'] = $query->row_array();
        $query = $this->db->get_where('bills_user', array('id' => $data['show']['id_user']));
        $data['show2'] = $query->row_array();
        //$query = $this->db->get_where('bills_producer', array('id' => $data['show']['id_producer']));
//        $this->db->select('name_order,bills_orders.start_date,bills_orders.expiry_date,payment,discount,quantity,bills_orders.comment,'
//                . 'bills_producer.name as prod_name_en,bills_producer.arabic_name as prod_name_ar,discount,discount_remainder,,bills_orders.item_price');
//        $this->db->join('bills_producer', 'bills_producer.id = bills_orders.id_producer');
//        $query = $this->db->get_where('bills_orders', array('id_orders' => $data['show']['id_orders']));
//        $data['producer'] = $query->result();

        $this->load->model('admin/Orders_model');
        $data['producer'] = $this->Orders_model->get_order_products($data['show']['id_orders']);

        //total_price
        $this->db->select('sum(discount_remainder) as total_price');
        $this->db->group_by('id_orders');
        $data['price'] = $this->db->get_where('bills_orders', array('id_orders' => $data['show']['id_orders']))->row();

        $this->db->select('inv_footer,inv_footer_ar,inv_currency,inv_lang,inv_type,inv_footer_thermal,inv_footer_thermal_ar');
        $data['sett'] = $this->db->get('setting')->row();

        $add = FALSE;
        $data['title'] = '  عرض عميل';
        $data['thispage'] = $this->thispage;
        //  $data['view'] = '../controllers/views/' . $this->thispage . '/show';
        if ($data['sett']->inv_type == 0) {
            $this->load->view('site/' . $this->thispage . '/show', $data);
        } else {
            $data['print'] = 1;
            $this->load->view('site/' . $this->thispage . '/thermal_bill', $data);
        }
    }

    public function show($id) {

        $query = $this->db->get_where('bills_orders', array('id' => $id));
        $data['show'] = $query->row_array();

        $query = $this->db->get_where('bills_user', array('id' => $data['show']['id_user']));
        $data['show2'] = $query->row_array();


        $this->db->select('inv_footer,inv_footer_ar');
        $data['sett'] = $this->db->get('setting')->row();

        $add = FALSE;


        $data['title'] = '  عرض عميل';
        $data['thispage'] = $this->thispage;
        $data['view'] = '../controllers/views/' . $this->thispage . '/show';
        $this->load->view('site/' . $this->thispage . '/show', $data);
    }

    public function del($id, $call_center = 0) {
        if ((!$call_center && !get_ap('invoice_del', $this->operator_id)) ||
                ($call_center && !get_ap('call_delete_order', $this->operator_id))) {
            redirect("", "refresh");
        }
//        $query = $this->db->get_where('bills_orders', array('id' => $id));
//        $data['edit'] = $query->row_array();


        $this->db->where('id_orders', $id);
        $result = $this->db->delete('bills_orders');
        $this->db->delete('orders', array('id' => $id));
        //if (count($result) > 0) {
        $this->session->set_flashdata('msg', 'تم حذف القسم بفضل الله!');
        if (!$call_center) {
            redirect(base_url('orders/index/'));
        }
        redirect(base_url('call_center/CallCenter/show_orders'));
        //}
    }

    public function edit($id, $call_center = 0) {

        $query = $this->db->get_where('bills_orders', array('id' => $id));
        $data['edit'] = $query->row_array();

        $data['edit']['checked'] = array('', '', '', '', '', '', '', '', '');


        $data['edit']['checked'][$data['edit']['active']] = 'checked';
        $add = FALSE;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('valuess', '', 'trim|required');
            $this->form_validation->set_rules('name', '', 'trim|required');
            //	$this->form_validation->set_rules('comment', '', 'trim|required'); 
            //	$this->form_validation->set_rules('comm', '', 'trim|required'); 


            if ($this->form_validation->run() === FALSE) {

                $add = FALSE;
            } else {

                $add = TRUE;
                $edit_data = array(
                    'valuess' => $this->input->post('valuess'),
                    'name' => $this->input->post('name'),
                    'active' => $this->input->post('active'),
                    'note' => $this->input->post('note'),
                );
                $edit_data = $this->security->xss_clean($edit_data);
                $result = $this->db->where('id', $id)->update('bills_orders', $edit_data);

                if ($result) {
                    $this->session->set_flashdata('msg', 'تم التعديل المنتج بفضل الله!');
                    if (!$call_center) {
                        redirect(base_url('' . $this->thispage . '/index/'));
                    }
                    redirect(base_url('call_center/CallCenter/show_orders'));
                }
            }
        }


        if (!$add) {

            $data['title'] = 'تعديل  شقة';
            $data['thispage'] = $this->thispage;
            $data['call_center'] = $call_center;
            $data['view'] = '../controllers/views/' . $this->thispage . '/edit';
            $this->load->view('../controllers/views/layout', $data);
        }
    }

    public function clint_blacklist($id) {

        $this->db->where('id', $id)->update('bills_orders', array('oky' => 'ok', 'comment' => $this->input->post('comment')));

        $this->session->set_flashdata('msg', 'تم عمل بلاك لست ');
        redirect(base_url() . 'dashboard');
    }

    function report() {
        $result = $this->db->get('bills_orders')->result();
        if ($result) {
            $array = array();
            foreach ($result as $key => $result_value) {
                $array[] = array(
                    'sno' => $result_value->id,
                    'order_id' => $result_value->id_orders,
                    'product_id' => $result_value->id_producer,
                    'user_id' => $result_value->id_user,
                    'name' => $result_value->name,
                    'start_date' => $result_value->start_date,
                    'expiry_date' => $result_value->expiry_date,
                    'create_now' => $result_value->date_now,
                    'payment' => $result_value->payment,
                    'discount' => $result_value->discount,
                    'time_register' => $result_value->since_time_register,
                    'payment_method' => $result_value->payment_method,
                    'paid' => $result_value->paid,
                    'active' => $result_value->active,
                );
            }
        }
        export_csv($array, "bills orders");
    }

    function get_product_price() {
        $product_id = $this->input->post('product_id');
        $this->db->select('valuess,type');
        $row = $this->db->get_where('bills_producer', array('id' => $product_id))->row();
        if ($row) {
            echo json_encode($row);
        } else {
            echo 0;
        }
    }

    public function add_student($call_center) {
        if ($this->input->post()) {
            $fields_arr = array('username' => $this->lang->line('name'),
                //'name' => $this->lang->line('name'),
                'cid_user' => $this->lang->line('civil-no'), 'email' => $this->lang->line('e-mail'), 'password' => $this->lang->line('password'),
                'phone' => $this->lang->line('students') . ' ' . $this->lang->line('mobile'),
                'phone_father' => $this->lang->line('guardian') . ' ' . $this->lang->line('mobile'), 'country' => $this->lang->line('nationality'),
                'city' => $this->lang->line('region'), 'blocks' => $this->lang->line('block'), 'street' => $this->lang->line('street'), 'jadah' => $this->lang->line('jadah'),
                'floor' => $this->lang->line('floor'), 'door_no' => $this->lang->line('door-number'), 'address_link' => $this->lang->line('address-link'), 'title' => $this->lang->line('title'),
                'age' => $this->lang->line('date-of-birth'), 'sex' => $this->lang->line('sex'), 'father_work' => $this->lang->line('father_work'), 'mother_work' => $this->lang->line('mother_work'),
                'social_status' => $this->lang->line('social_status'), 'note' => $this->lang->line('note'), 'building_num' => $this->lang->line('building_num'));
            $required_fields = explode(',', $this->db->get('setting')->row()->customer_fields);
            //$this->form_validation->set_rules('password', $this->lang->line('password'), 'trim|required');
            foreach ($fields_arr as $key => $val) {
                if (in_array($key, $required_fields)) {
                    $this->form_validation->set_rules($key, $val, 'trim|required');
                }
            }

            if ($this->input->post('email')) {
                $this->form_validation->set_rules('email', $this->lang->line('email'), 'trim|is_unique[bills_user.email]');
            }
//            if ($this->input->post('username')) {
//                $this->form_validation->set_rules('username', $this->lang->line('username'), 'trim|is_unique[bills_user.username]');
//            }
            if ($this->input->post('phone')) {
                $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|is_unique[bills_user.phone]');
            }

            if ($this->form_validation->run() === FALSE) {
                $this->session->set_flashdata('error', validation_errors());
                $this->add($call_center);
                //redirect(base_url('' . $this->thispage . '/add/' . $call_center));
            } else {

                $data = array(
                    'cid_user' => $this->input->post('cid_user'),
                    'username' => $this->input->post('username'),
                    'name' => $this->input->post('name'),
                    'email' => $this->input->post('email'),
                    'pass' => md5(md5($this->input->post('password'))),
                    'phone_code' => $this->input->post('phone_code'),
                    'phone' => $this->input->post('phone'),
                    'phone_father' => $this->input->post('phone_father'),
                    'nationality' => $this->input->post('country'),
                    'region' => $this->input->post('city'),
                    //'city3' => $this->input->post('city3'),
                    'age' => $this->input->post('age'),
                    'sex' => $this->input->post('sex'),
                    'note' => $this->input->post('note'),
                    'blocks' => $this->input->post('blocks'),
                    'floor' => $this->input->post('floor'),
                    'jadah' => $this->input->post('jadah'),
                    'street' => $this->input->post('street'),
                    'door_no' => $this->input->post('door_no'),
                    //'country' => $this->input->post('blocks') . ' ' . $this->input->post('floor') . ' ' . $this->input->post('jadah') . ' ' . $this->input->post('street') . ' ' . $this->input->post('door_no'),
                    'address_link' => $this->input->post('address_link'),
                    'create_on' => date('m-d-Y m:h:sa'),
                    // 'imageuser' => $imageuser,
                    'since_time_register' => $this->booking->tissme_now(),
                    'stop' => '0',
                    'approve_status' => 1,
                    'father_job' => $this->input->post('father_work'),
                    'mother_job' => $this->input->post('mother_work'),
                    'social_status' => $this->input->post('social_status'),
                    'block' => 0
                );
                $data = $this->security->xss_clean($data);
                $this->db->insert('bills_user', $data);
                $result = $this->db->insert_id();

                if ($result) {
                    $this->session->set_flashdata('success', 'تم اضافة الطالب بنجاح');
                    $this->session->set_flashdata('student_id', $result);
                    redirect(base_url('' . $this->thispage . '/add/' . $call_center));
                }
            }
        }
    }

    function add_address() {
        $data = array('region' => $this->input->post('city'),
            'blocks' => $this->input->post('blocks'),
            'floor' => $this->input->post('floor'),
            'jadah' => $this->input->post('jadah'),
            'street' => $this->input->post('street'),
            'door_no' => $this->input->post('door_no'),
            'building_num' => $this->input->post('building_num'),
            'address_link' => $this->input->post('address_link'),
            'user_id' => $this->input->post('user_id')
        );
        $this->db->insert('addresses', $data);
    }

    function show_invoice($id) {
        $this->db->select('bills_orders.paid,bills_orders.note,bills_orders.date_now,bills_orders.id_orders,bills_orders.date_now,bills_orders.name,'
                . 'bills_orders.id_user,addresses.*,bills_user.username,bills_user.phone,orders.timestamp as date,user.name as created_by_name,orders.order_status'
                . ',orders.payment_method,orders.payment_time,orders.delivery_type');
        $this->db->join('orders', 'orders.id = bills_orders.id_orders');
        $this->db->join('user', 'user.id = orders.created_by', 'left');
        $this->db->join('addresses', 'addresses.id=orders.address_id', 'left');
        $this->db->join('bills_user', 'bills_user.id=bills_orders.id_user', 'left');

        $query = $this->db->get_where('bills_orders', array('bills_orders.id' => $id));
        $data['show'] = $query->row_array();
        if (!empty($data['show']) && $data['show']['region'] != '') {
            $this->db->group_start();
            $this->db->where('arabic', $data['show']['region']);
            $this->db->or_where('english', $data['show']['region']);
            $this->db->group_end();
            $region = $this->db->get_where('datas', array('lable' => 'region'))->row();
            if ($region) {
                $data['show']['region_ar'] = $region->arabic;
                $data['show']['region_en'] = $region->english;
            }
        }
        $query = $this->db->get_where('bills_user', array('id' => $data['show']['id_user']));
        $data['show2'] = $query->row_array();
        //$query = $this->db->get_where('bills_producer', array('id' => $data['show']['id_producer']));
        //total_price
        $this->db->select('sum(discount_remainder) as total_price');
        $this->db->group_by('id_orders');
        $data['price'] = $this->db->get_where('bills_orders', array('id_orders' => $data['show']['id_orders']))->row();

        $this->db->select('inv_footer,inv_footer_ar,inv_currency,inv_lang,inv_type,inv_footer_thermal,inv_footer_thermal_ar');
        $data['sett'] = $this->db->get('setting')->row();

        $this->load->model('admin/Orders_model');
        $data['producer'] = $this->Orders_model->get_order_products($data['show']['id_orders']);

        $data['title'] = '  عرض فاتورة';
        $data['thispage'] = $this->thispage;
        // if ($data['sett']->inv_type == 0) {
        $this->load->view('site/' . $this->thispage . '/show_invoice', $data);
//        } else {
//            $this->load->view('site/' . $this->thispage . '/thermal_bill', $data);
//        }
    }

    function edit_order_status($order_id) {
        $data['order'] = $this->db->get_where('orders', array('id' => $order_id))->row();
        //was to prevent edit status if delivered
//        if (!($this->type == 0 &&
//                ( $this->call_center && get_ap('call_edit_order_status', $this->operator_id) &&
//                (($data['order']->order_status != 4 && get_ap('call_edit_order', $this->operator_id, 1) == 2) || get_ap('call_edit_order', $this->operator_id, 1) != 2)) ||
//                (!$this->call_center && get_ap('edit_order_status', $this->operator_id) &&
//                (($data['order']->order_status != 4 && get_ap('invoice_edit', $this->operator_id, 1) == 2) || get_ap('invoice_edit', $this->operator_id, 1) != 2)))) {
//            
        if (!($this->type == 0 &&
                ( $this->call_center && get_ap('call_edit_order_status', $this->operator_id) &&
                ((get_ap('call_edit_order', $this->operator_id, 1) == 2) || get_ap('call_edit_order', $this->operator_id, 1) != 2)) ||
                (!$this->call_center && get_ap('edit_order_status', $this->operator_id) &&
                ((get_ap('invoice_edit', $this->operator_id, 1) == 2) || get_ap('invoice_edit', $this->operator_id, 1) != 2)))) {
//        if (!get_ap('call_edit_order_status', $this->operator_id) || $data['order']->order_status == 3) {
            redirect("", "refresh");
        }
        if ($this->input->post('submit')) {
            $this->load->model('admin/User_model');

            $this->db->select('order_status,call_center');
            $old_order_row = $this->db->get_where('orders', array('id' => $order_id))->row();

            if ($this->input->post('paid')) {
                $this->db->update('bills_orders', array('paid' => $this->input->post('paid')), array('id_orders' => $order_id));
            }
            $updated_data = array('expected_delivery_time' => $this->input->post('expected_delivery_time') ? $this->input->post('expected_delivery_time') : NULL,
                'delivery_details' => $this->input->post('delivery_details'),
                'delivery_status' => $this->input->post('delivery_status'),
                'payment_method' => $this->input->post('payment_method'));
            if (get_license_per('order_status')) {
                $updated_data['order_status'] = $this->input->post('order_status');
            }
            if ($this->input->post('driver') || $this->input->post('driver') == 0) {
                $updated_data['driver'] = $this->input->post('driver');
            }
            $this->db->update('orders', $updated_data, array('id' => $order_id));

            if ($old_order_row->order_status != $this->input->post('order_status')) {
                $order_status = array('waiting', 'preparing', 'ready_for_deliver', 'delivering', 'delivered', 'canceled');
                rec_log('Change order status to : ' . $order_status[$this->input->post('order_status')] . ' order num. : ' . $order_id, 0, $order_id, $this->input->post('order_status'));
            }

            $order_after_updated = $this->db->get_where('orders', array('id' => $order_id))->row();
            //prepare
            if ($this->input->post('order_status') == 1 && $old_order_row->order_status != $this->input->post('order_status')) {
                $this->User_model->send_sms($order_id, 'preparing');
                if ($order_after_updated->payment_method == 3) {
                    $this->User_model->send_sms($order_id, 'payment_msg');
                }
            }
            //in delivery
            if ($this->input->post('order_status') == 3 && $old_order_row->order_status != $this->input->post('order_status')) {
                $this->User_model->send_sms($order_id, 'in_delivery');
            }
            //delivered
            if ($this->input->post('order_status') == 4 && $old_order_row->order_status != $this->input->post('order_status')) {
                $this->User_model->send_sms($order_id, 'delivered');
            }
            // order canceled
            if ($this->input->post('order_status') == 5 && $old_order_row->order_status != $this->input->post('order_status')) {
                $this->User_model->send_sms($order_id, 'order_canceled');
            }
            $this->session->set_flashdata('msg', $this->lang->line('op_success'));
            redirect(base_url('orders/index/1/' . $old_order_row->call_center));
        }

        $data['order_items'] = $this->db->get_where('bills_orders', array('id_orders' => $order_id))->result();
        $this->load->model('admin/Drivers_model');
        $data['drivers'] = $this->Drivers_model->get_active_drivers();
        $data['order_id'] = $order_id;
        $data['title'] = $this->lang->line('edit_order_status');
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/edit_order_status', $data);
    }

    function get_user_addresses() {
        $users = $this->input->post('users');
        if ($users) {
            $this->db->select('id,username');
            $this->db->where_in('id', $users);
            $users_ids = $this->db->get('bills_user')->result();
            foreach ($users_ids as $user) {
                $user->addresses = $this->db->get_where('addresses', array('user_id' => $user->id))->result();
            }
            echo json_encode($users_ids);
        } else {
            echo json_encode(array());
        }
    }

//    function adjust_item_price() {
//        $this->db->select('quantity,id,item_price,payment');
//        $invs = $this->db->get('bills_orders')->result();
//        foreach ($invs as $inv) {
//            if ($inv->quantity) {
//                $this->db->update('bills_orders', array('item_price' => round($inv->payment / $inv->quantity, 2)), array('id' => $inv->id));
//            } else {
//                $this->db->update('bills_orders', array('item_price' => $inv->payment), array('id' => $inv->id));
//            }
//        }
//    }
//
//    function adjust_order_status() {
//        $orders = $this->db->get('orders')->result();
//        foreach ($orders as $order) {
//            if ($order->order_status > 2) {
//                $this->db->update('orders', array('order_status' => $order->order_status - 1), array('id' => $order->id));
//            }
//        }
//    }
//
//    function adjust_username() {
//        $users = $this->db->get('bills_user')->result();
//        foreach ($users as $user) {
//            $this->db->update('bills_user', array('name' => $user->username), array('id' => $user->id));
//        }
//    }

    function sales_report() {
        if (!get_ap('sales_report', $this->operator_id)) {
            redirect('', 'refresh');
        }
        $this->load->model('admin/Orders_model');
        $data['title'] = $this->lang->line('sales_report');
        $data['admins'] = $this->db->get('user')->result();
        $this->filter_sales_report();
        $data['total_sales_amount'] = $this->Orders_model->get_total_sales_amount();
        $this->filter_sales_report();
        $data['payment_type_amounts'] = $this->Orders_model->get_amount_by_payment_types();
        $this->filter_sales_report();
        $data['best_selling_products'] = $this->Orders_model->get_best_selling_products();
        $this->filter_sales_report();
        $data['clients'] = $this->Orders_model->get_clients();
        $data['sett'] = $this->Orders_model->get_settings();
        $this->load->view('site/' . $this->thispage . '/sales_report', $data);
    }

    function filter_sales_report() {
        if ($this->input->post('start_expiry')) {
            $date_arr = explode(' - ', $this->input->post('start_expiry'));
            $from = date('Y-m-d', strtotime($date_arr[0]));
            $to = date('Y-m-d', strtotime($date_arr[1]));
            $this->db->where(array('orders.timestamp >=' => $from, 'orders.timestamp <=' => $to));
        }
        if ($this->input->post('admins') && !empty($this->input->post('admins'))) {
            $this->db->where_in('orders.created_by', $this->input->post('admins'));
        }
    }

    public function getOrder($call_center, $type, $order_status) {
        $this->load->model('admin/Orders_model');
        $search_val = isset($this->input->post('search')["value"]) ? $this->input->post('search')["value"] : 0;
        $order_col = isset($this->input->post('order')[0]['column']) ? $this->input->post('order')[0]['column'] : -1;
        $order_dir = isset($this->input->post('order')[0]['dir']) ? $this->input->post('order')[0]['dir'] : 0;

        $filter = json_decode($this->input->post('data'));
        $db_data = $this->Orders_model->get_order_ajax($this->input->post('length'), $this->input->post('start'), $search_val, $call_center, $filter, $type, $order_status, $order_col, $order_dir);

        $order_status_arr = array('waiting', 'preparing', 'ready_for_deliver', 'delivering', 'delivered', 'canceled');
        $payment_method = array('cash', 'Knit', 'Visa/Master', 'link');
        $arr = array();
        $count = 1;
        foreach ($db_data as $row) {
            $sub_array = array();
            $sub_array[] = $count++;
            $sub_array[] = str_replace(' ', '<br/>', adjust_timezone($row['timestamp']));
            if ($type == 0) {
                $sub_array[] = $row['id_orders'];
            }
            $sub_array[] = '<a  class="update" href="' . base_url('user/show/' . $row['id_user']) . '">' . $row['username'] . '</a>
                            <br/>' . $row['phone_code'] . $row['phone'] . '<br/>'
                    . $row['email'];
            $sub_array[] = round($row['total_price'], 3);
            $sub_array[] = $row['region'];
            if ($call_center) {
                $delivery_type = $row['delivery_type'] == 0 ? $this->lang->line('direct_recieve') : $this->lang->line('home_delivery');
                $expected_delivery_time = $row['expected_delivery_time'] ? $row['expected_delivery_time'] : '---';
                $sub_array[] = $delivery_type . '<br/>' . $expected_delivery_time;
            }
            if ($type == 0) {
                $pay_method_txt = $this->lang->line($payment_method[$row['payment_method']]) ? $this->lang->line($payment_method[$row['payment_method']]) : $payment_method[$row['payment_method']];
                if ($row['paid'] == '2') {
                    $sub_array[] = $pay_method_txt . '<br/>' . '<span class="label label-danger label-pill label-inline">' . $this->lang->line("not-paid") . '</span>';
                } else if ($row['paid'] == '1') {
                    $sub_array[] = $pay_method_txt . '<br/>' . '<span class="label label-success label-pill label-inline">' . $this->lang->line("payment-is-made") . '</span>';
                } else {
                    $sub_array[] = $pay_method_txt . '<br/>' . '<span class="label label-danger label-pill label-inline">' . $this->lang->line("not-paid") . '</span>';
                }
            }
            if ($call_center && $type == 0 && get_license_per('order_status')) {
                $sub_array[] = $this->lang->line($order_status_arr[$row['order_status']]);
            }
            $sub_array[] = $row['created_name'];

            // Actions 
            $print_link = '';
            if (get_ap('invoice_print', $this->operator_id)) {
                $print_link = '<a target="_block" href="' . base_url('' . $this->thispage . '/printorder/' . $row['id']) . '" class="btn btn-icon btn-facebook" title="Print">
                                    <i class="fa fa-print"></i>
                                </a>';
            }
            $edit_link = '';
            if ((!$call_center && get_ap('invoice_edit', $this->operator_id, 1) == 1) ||
                    ($call_center && get_ap('call_edit_order', $this->operator_id, 1) == 1) ||
                    ($call_center && $row['order_status'] != 4 && get_ap('call_edit_order', $this->operator_id, 1) == 2 ) ||
                    (!$call_center && $row['paid'] != 1 && get_ap('invoice_edit', $this->operator_id, 1) == 2)) {
                $edit_link = '<a href="' . base_url('Orders/edit_invoice/' . $row['id_orders'] . '/' . $call_center) . '"  class="btn btn-icon btn-warning" title="Edit">
                                    <i class="la la-edit"></i>
                                </a>';
            }
            $this->load->model('admin/Payment_model');
            $payment_sett = $this->Payment_model->get_payment_sett();
            $payment_link = '';
            if ($row['order_status'] != 5 && $row['paid'] == 2 && $payment_sett && $payment_sett->status && $row['payment_method'] == 3) {
                $code_encoded = "'" . urlencode(base64_encode($row['id_orders'])) . "'";
                $payment_link = '<a onclick="show_payment_link(' . $code_encoded . ')" class="btn btn-icon btn-success" title="' . $this->lang->line('copy') . ' ' . $this->lang->line('payment_link') . '">
                                    <i class="fas fa-copy"></i>
                                </a>';
            }
            $edit_order_status = '';
            //was to prevent edit status if delivered
//            $type == 0 &&
//                    ( $call_center && get_ap('call_edit_order_status', $this->operator_id) &&
//                    (($row['order_status'] != 4 && get_ap('call_edit_order', $this->operator_id, 1) == 2) || get_ap('call_edit_order', $this->operator_id, 1) != 2)) ||
//                    (!$call_center && get_ap('edit_order_status', $this->operator_id) &&
//                    (($row['order_status'] != 4 && get_ap('invoice_edit', $this->operator_id, 1) == 2) || get_ap('invoice_edit', $this->operator_id, 1) != 2)))
            if ($type == 0 &&
                    ( $call_center && get_ap('call_edit_order_status', $this->operator_id) &&
                    ((get_ap('call_edit_order', $this->operator_id, 1) == 2) || get_ap('call_edit_order', $this->operator_id, 1) != 2)) ||
                    (!$call_center && get_ap('edit_order_status', $this->operator_id) &&
                    ((get_ap('invoice_edit', $this->operator_id, 1) == 2) || get_ap('invoice_edit', $this->operator_id, 1) != 2))) {
                $edit_order_status = '<a href="' . base_url('Orders/edit_order_status/' . $row['id_orders']) . '"  class="btn btn-icon btn-info" title="' . $this->lang->line('edit_order_status') . '">
                                    <i class="far fa-check-circle"></i>
                                </a>';
            }
            $delete_link = '';
            if ((!$call_center && get_ap('invoice_del', $this->operator_id)) ||
                    ($call_center && get_ap('call_delete_order', $this->operator_id))) {
                $delete_link = '<a onclick="alert_box(' . $row['id_orders'] . ')" class="btn btn-icon btn-danger" title="Delete">
                                    <i class="fa fa-trash"></i>
                                </a>';
            }
            $payment_details_link = '';
            if ($row['paid'] == 1 && $row['payment_method'] == 3) {
                $payment_details_link = '<a href="' . base_url() . 'orders/show_receipt/' . $row['id_orders'] . '" class="btn btn-icon btn-success" title="Show Payment Details">
                                    <i class="fas fa-coins"></i>
                                </a>';
            }

            $sub_array[] = '<a href="' . base_url('' . $this->thispage . '/show_invoice/' . $row['id']) . '" class="btn btn-icon btn-primary">
                                <i class="fa fa-eye"></i>
                            </a>' . $payment_details_link . $print_link . $edit_link . $payment_link . $edit_order_status . $delete_link;


            $arr[] = $sub_array;
        }
        $count_all = $this->Orders_model->get_order_ajax(0, 0, $search_val, $call_center, $filter, $type, $order_status, -1, 0);
        $output = array(
            "draw" => intval($this->input->post("draw")),
            "recordsTotal" => $count_all,
            "recordsFiltered" => $count_all,
            "data" => $arr
        );
        echo json_encode($output);
    }

    function payment_report() {
        $this->load->model('admin/Orders_model');
        $filter = $this->input->post();
        if ($this->input->post()) {
            if ($this->input->post('start_expiry')) {
                $date_arr = explode(' - ', $this->input->post('start_expiry'));
                $filter['from'] = date('Y-m-d', strtotime($date_arr[0]));
                $filter['to'] = date('Y-m-d', strtotime($date_arr[1]));
                unset($filter['start_expiry']);
            }
        }
        $data['payment_details'] = $this->Orders_model->get_payment_data($filter);
        $data['title'] = $this->lang->line('payment_details');
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/payment_report', $data);
    }

    function show_receipt($order_id) {
        $this->load->model('admin/Orders_model');
        $data['sett'] = get_setting();
        $data['order'] = $this->Orders_model->get_order_details($order_id);
        $data['title'] = $this->lang->line('payment_receipt');
        if (!$data['order']) {
            $this->session->set_flashdata('error', $this->lang->line('data_not_found'));
            redirect(base_url('orders'));
        }
        $this->load->view('site/' . $this->thispage . '/receipt', $data);
    }

    function get_product_additions() {
        $product_id = $this->input->post('product_id');
        $col = $this->session->userdata('language') == 'english' ? 'title_en' : 'title_ar';
        $this->db->select("*,$col as qu");
        $product_adds = $this->db->get_where('product_additions', array('product_id' => $product_id))->result();
        foreach ($product_adds as $product_add) {
            $options_ids = explode(',', $product_add->options);
            $arr = array();
            foreach ($options_ids as $option_id) {
                $col = $this->session->userdata('language') == 'english' ? 'name_en' : 'name_ar';
                $this->db->select($col . ',price');
                $options_qu = $this->db->get_where('additions', array('id' => $option_id))->row();
                if ($options_qu) {
                    $arr[] = array($options_qu->$col, $option_id, $options_qu->price);
                }
            }
            $product_add->options = $arr;
        }
        echo json_encode($product_adds);
    }

}

?>