<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Customer_Order_Process extends CI_Controller
{
    var $main_menu_name = "customer_order_process";
    var $sub_menu_name = "customer_order_process";
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Customer_Order_Process_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Common_Model');
        $this->load->model('User_Model');
        $this->load->model('Purchases_Model');
        $this->load->model('Transfer_Model');
        $this->load->model('Product_Damage_Model');
        $this->load->model('Sales_Return_Model');
        $this->load->model('Marketing_Delivery_Model');
        $this->load->model('In_Type_Model');
        $this->load->model('Product_Discount_Model');
        $this->load->model('Sales_Model');
        $this->load->model('Pos_Model');
    }
    //Sales list page load
    public function index()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = $this->sub_menu_name;
        $this->load->view('customer_orders/list_cus_order_pending', $data);
    }
    public function cus_loaded()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = "cus_loaded";
        $this->load->view('customer_orders/list_cus_order_loaded', $data);
    }
    public function manage()
    {
        $cus_order_id = $this->uri->segment(3);
        $this->load->model('Customer_Model');
        if ($cus_order_id == 0) {
            $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
            $data['sales_rep_list'] = $this->User_Model->get_all_sales_user_reps();
            $data['customer_list']  = $this->Customer_Model->get_all_customers();
            $data['in_type_list']   = $this->In_Type_Model->get_active_in_types();
            $data['type']           = 'A';
            $data['main_menu_name'] = $this->main_menu_name;
            $data['sub_menu_name']  = 'manage';
            $this->load->view('customer_orders/cus_order_manage', $data);
        }
    }
    public function get_product_suggestion()
    {
        $term    = $this->input->get('term');
        $product = $this->Customer_Order_Process_Model->get_product_suggestion($term);
        $in_type = $this->input->get('t');
        $json    = array();
        foreach ($product as $row) {
            $warehouse_id            = ""; // $this->session->userdata('ss_warehouse_id');
            //stock check    
            $transferd_qty           = $this->Transfer_Model->getTransferdQtyByWarehouseId($warehouse_id, $row['product_id']);
            $transfer_reseve_qty     = $this->Transfer_Model->getTransferResevedQtyByWarehouseId($warehouse_id, $row['product_id']);
            $purchased_qty           = $this->Purchases_Model->getPurchasedQtyByWarehouseId($warehouse_id, $row['product_id']);
            $product_damaged_qty     = $this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($warehouse_id, $row['product_id']);
            $sales_return_qty        = $this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($warehouse_id, $row['product_id']);
            $issue_qty               = $this->Customer_Order_Process_Model->get_all_cus_isued_item($warehouse_id, $row['product_id']);
            $return_qty              = $this->Customer_Order_Process_Model->get_all_cus_return_item($warehouse_id, $row['product_id']);
            $direct_sale_qty         = $this->Sales_Model->get_direct_sale_qty($warehouse_id, $row['product_id']);
            $hw_sale_qty             = $this->Pos_Model->get_hw_sale_qty($warehouse_id, $row['product_id'], "", "");
            $qty                     = $purchased_qty - $issue_qty + $return_qty - $product_damaged_qty + $transfer_reseve_qty - $transferd_qty - $direct_sale_qty - $hw_sale_qty;
            $product_id              = $row['product_id'];
            $product_code            = $row['product_code'];
            $product_name            = $row['product_name'];
            $product_oem_part_number = $row['product_oem_part_number'];
            $product_part_no         = $row['product_part_no'];
            $product_cost            = $row['product_cost'];
            $cash_price              = $row['product_price'];
            $wholesale_price         = $row['wholesale_price'];
            $credit_salling_price    = $row['credit_salling_price'];
            if ($in_type == 1) {
                $product_price = $cash_price;
            }
            if ($in_type == 2) {
                $product_price = $credit_salling_price;
            }
            if ($in_type == 3) {
                $product_price = $wholesale_price;
            }
            $sendParameters  = "$product_id,$product_name,$product_code,$product_price";
            $selling_R_price = " Selling Price: " . number_format($product_price, 2, '.', ',') . ' Cost Price:' . number_format($product_cost, 2, '.', ','); //RETAIL PRICE
            $selling_W_price = " Selling Price(Wholesale): " . number_format($wholesale_price, 2, '.', ','); //WHOLESALE PRICE
            $selling_C_price = " Selling Price(Credit): " . number_format($credit_salling_price, 2, '.', ','); //CREDIT PRICE
            if ($product_part_no)
                $selling_R_price .= ", Part No: $product_part_no";
            if ($product_oem_part_number)
                $selling_R_price .= ", OEM Part No: $product_oem_part_number";
            $json_itm = array(
                'id' => $row['product_id'],
                'product_id' => $row['product_id'],
                'product_code' => $row['product_code'],
                'product_name' => $row['product_name'],
                'product_price' => $product_price,
                'product_part_no' => $row['product_part_no'],
                'item_cost' => $row['product_cost'],
                'product_oem_part_number' => $row['product_oem_part_number'],
                'value' => $row['product_name'] . " (" . $row['product_code'] . ")",
                'label' => $row['product_name'] . " (" . $row['product_code'] . ") / $selling_R_price" . " / IN SROCK : " . $qty . " / " . $row['batch_ref_number'],
                'qty' => $qty
            );
            array_push($json, $json_itm);
        }
        echo json_encode($json);
    }
    public function cus_order_details()
    {
        $data['main_menu_name']          = $this->main_menu_name;
        $data['sub_menu_name']           = '';
        $order_id                        = $this->uri->segment(3);
        $data['sm_or_det']               = $this->Customer_Order_Process_Model->get_cus_order_master_details($order_id);
        $data['cus_order_items_details'] = $this->Customer_Order_Process_Model->get_cus_order_item_details($order_id);
        $data['SMPID']                   = $order_id;
        $this->load->view('customer_orders/cus_order_details', $data);
    }
    public function cus_order_details_print()
    {
        $this->load->model('Customer_Model');
        $data['main_menu_name']          = $this->main_menu_name;
        $data['sub_menu_name']           = '';
        $order_id                        = $this->uri->segment(3);
        $data['sm_or_det']               = $this->Customer_Order_Process_Model->get_cus_order_master_details($order_id);
        $data['customer_info']           = $this->Customer_Model->get_customer_info($data['sm_or_det']['customer_id']);
        $data['cus_order_items_details'] = $this->Customer_Order_Process_Model->get_cus_order_item_details($order_id);
        $data['SMPID']                   = $order_id;
        $this->load->view('customer_orders/cus_order_issue_details_print', $data);
    }
    function bill()
    {
        $this->load->model('Customer_Model');
        $data['main_menu_name']          = $this->main_menu_name;
        $data['sub_menu_name']           = '';
        $order_id                        = $this->uri->segment(3);
        $data['order_details']           = $this->Customer_Order_Process_Model->get_cus_order_master_details($order_id);
        $wh                              = array(
            'name' => $data['order_details']['name'],
            'address' => $data['order_details']['address'],
            'phone' => $data['order_details']['phone'],
            'email' => $data['order_details']['email']
        );
        $data['delivery_details']        = $this->Customer_Order_Process_Model->get_cus_order_delivery_details($order_id);
        $data['warehouse_details']       = $wh;
        $data['customer_details']        = $this->Customer_Model->get_customer_info($data['order_details']['customer_id']);
        $data['cus_order_items_details'] = $this->Customer_Order_Process_Model->get_cus_order_item_details($order_id);
        $data['SMPID']                   = $order_id;
        $this->load->view('customer_orders/delivery_print', $data);
    }
    public function list_cus_order_list()
    {
        $this->load->model('Customer_Model');
        $data            = array();
        $sales_rep_issue = $this->Customer_Order_Process_Model->get_cus_order_master_list();
        foreach ($sales_rep_issue as $row) {
            $cus_master_id    = $row['cus_order_master_id'];
            $customer_details = $this->Customer_Model->get_customer_info($row['customer_id']);
            $pay_st           = '<span class="label label-danger">Error</span>';
            if ($row['status'] == 1) {
                $pay_st = '<span class="label label-success">Completed</span>';
                $action = '<div class="btn-group text-left">                      
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url() . 'customer_order_process/cus_order_details/' . $cus_master_id . '"><i class="fa fa-file-text-o"></i> Sale Rep Issue Details</a></li>                            
                            </ul></div>';
            } else {
                if ($row['status'] == 0) {
                    $pay_st = '<span class="label label-warning">Pending</span>';
                    $action = '<div class="btn-group text-left">
                      
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url() . 'customer_order_process/cus_order_details/' . $cus_master_id . '"><i class="fa fa-file-text-o"></i> Customer Order Details Details</a></li>
                                    
                            </ul></div>';
                } else {
                    $pay_st = '<span class="label label-danger">Error</span>';
                }
            }
            $nestedData   = array();
            //print_r($sales_rep_issue_id);
            //print_r($row['cus_order_ref_no'])." - ".$row['cus_order_ref_no']."<br>";
            $nestedData[] = $row['customer_order_date'];
            $nestedData[] = $row['cus_order_ref_no'];
            $nestedData[] = $row['user_first_name'];
            $nestedData[] = $customer_details['cus_name'];
            $nestedData[] = $row['route_name'];
            $nestedData[] = $row['total_amount'];
            $nestedData[] = $pay_st;
            $nestedData[] = $action;
            $data[]       = $nestedData;
        }
        $json_data = array(
            "data" => $data
        );
        echo json_encode($json_data);
    }
    function save_cus_order()
    {
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('in_type', 'Invoice Type', 'required|trim|xss_clean');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|trim|xss_clean');
        $this->form_validation->set_rules('sales_rep_id', 'Salse Rep', 'required|trim|xss_clean');
        $this->form_validation->set_rules('route_id', 'Route', 'required|trim|xss_clean');
        $this->form_validation->set_rules('sales_rep_issue_datetime', 'Date', 'required|trim|xss_clean');
        $this->form_validation->set_rules('sale_inv_discount', 'Date', 'trim|xss_clean| greater_than[-1]');
        if ($this->form_validation->run() == FALSE) {
            echo json_encode(array(
                'id' => 0,
                'error' => 1,
                'disMsg' => validation_errors()
            ));
        } else {
            //get data
            $in_type                             = $this->input->post('in_type');
            $warehouse_id                        = $this->input->post('warehouse_id');
            $sales_rep_id                        = $this->input->post('sales_rep_id');
            $route_id                            = $this->input->post('route_id');
            $temp_date                           = $this->input->post('sales_rep_issue_datetime');
            $add_sales_excess_price              = $this->input->post('item_price_p_1');
            $add_sales_discount_price            = $this->input->post('discount_1');
            $sales_rep_issue_date                = date('Y-m-d', strtotime($temp_date));
            $added_date_time                     = date('Y-m-d H:i:s');
            $last_modified_date_time             = date('Y-m-d H:i:s');
            $total_amount                        = $this->input->post('sale_total');
            $route_id                            = $this->input->post('route_id');
            $customer_id                         = $this->input->post('customer_id');
            $order_discount                      = $this->input->post('sale_inv_discount');
            //initial variable    
            $order_status                        = 0;
            $total_order_value                   = 0;
            $total_order_cost                    = 0;
            $total_added_items_discount          = 0;
            $total_default_items_discount        = 0;
            $total_order_value_with_all_descount = 0;
            //---------------------------------------------------    
            $order_discount_type                 = 0; //value - 0 , precentage 1
            $order_discount_availble             = 0;
            $order_dis_val                       = 0;
            $needle                              = "%";
            if (strpos($order_discount, $needle) !== false) {
                $order_discount_in = 0;
                $order_dis_val     = preg_replace('/[^0-9.]/', '', $order_discount);
                if (is_numeric($order_dis_val)) {
                    $order_discount_type     = 1;
                    $order_discount_availble = 1;
                } else {
                    $order_dis_val = 0;
                }
            } else {
                if (is_numeric($order_discount)) {
                    $order_discount_type     = 0;
                    $order_discount_availble = 1;
                    $order_dis_val           = $order_discount;
                } else {
                    $order_dis_val = 0;
                }
            }
            //-----------------------------------------------
            $ref_code = $this->Common_Model->gen_ref_number('cus_order_master_id', 'customer_order_master', 'COB');
            $data     = array(
                'cus_order_ref_no' => $ref_code,
                'route_id' => $route_id,
                'wharehouse_id' => $warehouse_id,
                'order_rep_id' => $sales_rep_id,
                'customer_order_date' => $sales_rep_issue_date,
                'added_date_time' => $added_date_time,
                'total_amount' => $total_amount,
                'status' => $order_status,
                'customer_id' => $customer_id,
                'invoice_type' => $in_type,
                'entered_user_id' => $this->session->userdata('ss_user_id')
            );
            $_insert  = $this->Customer_Order_Process_Model->insert_update_master_table($data, '');
            $lastid   = $this->db->insert_id();
            //insert user activity
            $this->Common_Model->add_user_activitie("Added cus Order, (cus Order:$ref_code)");
            $disMsg     = 'cus successfully added';
            $row        = $this->input->post('row');
            $rowCount   = $this->input->post('rowCount');
            $data_items = array();
            for ($i = 1; $i <= $rowCount; $i++) {
                if (isset($row[$i]['product_id'][0])) {
                    //initioate variable
                    $after_product_discounted_price       = 0;
                    $after_total_product_discounted_price = 0;
                    $after_discount_price                 = 0;
                    $item_one_default_discount            = 0;
                    $item_total_default_discount          = 0;
                    $added_price                          = 0;
                    $added_discount                       = 0;
                    $discount                             = "";
                    $discount_defualt                     = "";
                    $product_dis_id                       = null;
                    //assingn variable
                    if ($row[$i]['item_price_p'][0]) {
                        $added_price = $row[$i]['item_price_p'][0];
                    }
                    if ($row[$i]['discount_val'][0]) {
                        $added_discount = $row[$i]['discount_val'][0];
                    }
                    $product_id        = $row[$i]['product_id'][0];
                    $product_price     = $row[$i]['unit_price'][0];
                    $product_cost      = $row[$i]['item_cost'][0];
                    $qty               = $row[$i]['qty'][0];
                    //calculation -----------------------------------
                    $new_product_price = $product_price + $added_price;
                    $total_order_value += ($new_product_price * $qty);
                    $total_order_cost += ($product_cost * $qty);
                    $total_added_items_discount += ($added_discount);
                    //get relevent discount item    
                    $default_discount = $this->Product_Discount_Model->get_relevent_discount($product_id, $in_type, $qty, $warehouse_id);
                    if (!$default_discount) {
                        $after_total_product_discounted_price = ($new_product_price * $qty) - $added_discount;
                        $discount                             = $added_discount / $qty;
                    } else {
                        $default_discount_val  = $default_discount['discount_value'];
                        $default_discount_type = $default_discount['is_precentage'];
                        $product_dis_id        = $default_discount['pd_discount_id'];
                        if ($default_discount_type == 0) {
                            //if not presentage
                            $item_one_default_discount            = $default_discount_val;
                            $item_total_default_discount          = $item_one_default_discount * $qty;
                            $after_discount_price                 = $new_product_price - $item_one_default_discount - ($added_discount / $qty);
                            $after_total_product_discounted_price = ($after_discount_price * $qty);
                            $discount_defualt                     = $item_one_default_discount;
                            if ($added_discount) {
                                $discount = $row[$i]['discount'][0];
                            }
                        } else {
                            //if precentage
                            $item_one_default_discount            = $default_discount_val;
                            $item_total_default_discount          = (($new_product_price / 100) * $default_discount_val) * $qty;
                            $after_discount_price                 = $new_product_price - $item_one_default_discount - ($added_discount / $qty);
                            $after_total_product_discounted_price = ($after_discount_price * $qty);
                            $discount_defualt                     = $item_one_default_discount . " %";
                            if ($added_discount) {
                                $discount = $row[$i]['discount'][0];
                            }
                        }
                    }
                    //calculation end
                    //assing db value    
                    $total_default_items_discount += $item_total_default_discount;
                    $data_item = array(
                        'cus_order_master_id' => $lastid,
                        'product_id' => $product_id,
                        'order_qty' => $qty,
                        'product_price' => $new_product_price,
                        'product_cost' => $product_cost,
                        'add_sales_excess_price' => $added_price,
                        'add_sales_discount_price' => $added_discount / $qty,
                        'after_discount_added_price' => $after_discount_price,
                        'total_price' => $after_total_product_discounted_price,
                        'total_cost' => $product_cost * $qty,
                        'issue_qty' => $qty,
                        'pd_discount_id' => $product_dis_id,
                        'discount' => $discount,
                        'default_discount_price' => $item_one_default_discount,
                        'discount_defualt' => $discount_defualt,
                        'total_item_discount' => $item_total_default_discount + $added_discount
                    );
                    $this->Customer_Order_Process_Model->insert_update_item_table($data_item, '');
                    $itemid = $this->db->insert_id();
                }
            }
        }
        $final_order_amount           = $total_order_value - $total_added_items_discount - $total_default_items_discount;
        $customer_credit_limit        = $this->Customer_Order_Process_Model->get_customer_credit_limit($customer_id);
        $customer_sale_total          = $this->Customer_Order_Process_Model->get_customer_sale_total($customer_id);
        $customer_payment_total       = $this->Customer_Order_Process_Model->get_customer_payment_total($customer_id);
        $customer_pending_order_total = $this->Customer_Order_Process_Model->get_customer_pending_order_total($customer_id);
        $cus_credit_balance           = $customer_credit_limit - ($customer_sale_total - $customer_payment_total + $customer_pending_order_total);
        $credit_approval              = 3;
        if ($cus_credit_balance >= $final_order_amount) {
            $credit_approval = 1;
        }
        //---------------------------------------
        $net_amount = $final_order_amount;
        if ($order_discount_availble) {
            if ($order_discount_type == 1) {
                $order_dis_val      = ($final_order_amount / 100) * $order_dis_val;
                $final_order_amount = $final_order_amount - $order_dis_val;
            }
            if ($order_discount_type == 0) {
                $final_order_amount = $final_order_amount - $order_dis_val;
            }
        }
        //--------------------------------------    
        if ($credit_approval == 1) {
            $this->load->model('Customer_Model');
            $cus_credit_status = $this->Customer_Model->get_credit_status_by_customer_id($customer_id);
            $credit_approval   = $cus_credit_status;
        }
        $data_final = array(
            'total_amount' => $final_order_amount,
            'bd_amount' => $total_order_value,
            'item_total_added_discount' => $total_added_items_discount,
            'item_total_default_discount' => $total_default_items_discount,
            'credit_approval_status' => $credit_approval,
            'discount_val' => $order_dis_val,
            'order_discount' => $order_discount,
            'net_amount' => $net_amount
        );
        $_insert    = $this->Customer_Order_Process_Model->insert_update_master_table($data_final, $lastid);
        if ($lastid) {
            $disMsg = 'Order Successfully Saved';
        } else {
            $disMsg = 'Error!, Not saved . Please contact System Administrator';
        }
        $this->session->set_flashdata('message', 'cus Order Successfully added!');
        echo json_encode(array(
            'id' => $lastid,
            'error' => 0,
            'disMsg' => $disMsg
        ));
    }
    public function list_cus_order_loaeded_list()
    {
        $data            = array();
        $sales_rep_issue = $this->Customer_Order_Process_Model->get_cus_order_master_loaded_list();
        foreach ($sales_rep_issue as $row) {
            $cus_master_id = $row['cus_order_master_id'];
            $pay_st        = '<span class="label label-danger">Error</span>';
            if ($row['status'] == 1) {
                $pay_st = '<span class="label label-success">Completed</span>';
                $action = '<div class="btn-group text-left">                      
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url() . 'customer_order_process/cus_order_details/' . $cus_master_id . '"><i class="fa fa-file-text-o"></i> Customer Order Details</a></li>                            
                            </ul></div>';
            } else {
                if ($row['status'] == 0) {
                    $pay_st = '<span class="label label-warning">Pending</span>';
                    $action = '<div class="btn-group text-left">                      
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url() . 'customer_order_process/cus_order_details/' . $cus_master_id . '"><i class="fa fa-file-text-o"></i>Customer Order Details</a></li>
                                                    
                            </ul></div>';
                } else {
                    $pay_st = '<span class="label label-danger">Error</span>';
                }
            }
            $nestedData   = array();
            //print_r($sales_rep_issue_id);
            $nestedData[] = $row['customer_order_date'];
            $nestedData[] = $row['cus_order_ref_no'];
            $nestedData[] = $row['user_first_name'];
            $nestedData[] = $row['cus_name'];
            $nestedData[] = $row['route_name'];
            $nestedData[] = $row['total_amount'];
            $nestedData[] = $pay_st;
            $nestedData[] = $action;
            $data[]       = $nestedData;
        }
        $json_data = array(
            "data" => $data
        );
        echo json_encode($json_data);
    }
    //change credit bill as cash bill on 2020-02-06
    function turn_credit_order_as_cash_order()
    {
        $order_id                             = $this->input->get('id');
        $order_master_details                 = $this->Customer_Order_Process_Model->get_cus_order_master_details($order_id);
        $order_items_list                     = $this->Customer_Order_Process_Model->get_cus_order_item_details($order_id);
        //value for master table 
        $order_status                         = 0;
        $total_order_value                    = 0;
        $total_order_cost                     = 0;
        $total_order_added_items_discount     = 0;
        $total_order_default_items_discount   = 0;
        $total_order_value_with_all_descount  = 0;
        $total_value_with_after_aded_discount = 0;
        foreach ($order_items_list as $itm) {
            $cus_order_item_id               = $itm['cus_order_item_id'];
            $product_id                      = $itm['product_id'];
            $order_qty                       = $itm['order_qty'];
            $issue_qty                       = $itm['issue_qty'];
            $discount                        = $itm['discount'];
            $add_extra                       = $itm['add_sales_excess_price'];
            $warehouse_id                    = "";
            $save_default_discount           = "";
            $save_default_discount_val       = 0;
            $save_added_discount             = "";
            $save_added_discount_val         = 0;
            $save_item_added_discount_total  = 0;
            $save_item_defult_discount_total = 0;
            $save_item_total_final_value     = 0;
            $product_dis_id                  = 0;
            //---------------------------------------------------get product price
            $p_cash_price                    = $this->Customer_Order_Process_Model->get_product_cash_price($product_id);
            $item_product_total_value        = ($add_extra + $p_cash_price) * $issue_qty;
            $save_after_added_discount       = $add_extra + $p_cash_price;
            //---------------------------------------------------calculate added discout total    
            $order_discount_type             = 0; //value - 0 , precentage 1
            $order_discount_availble         = 0;
            $order_dis_val                   = 0;
            $needle                          = "%";
            if (strpos($discount, $needle) !== false) {
                $order_dis_val = preg_replace('/[^0-9.]/', '', $discount);
                print_r($order_dis_val);
                if (is_numeric($order_dis_val)) {
                    $order_discount_type     = 1;
                    $order_discount_availble = 1;
                } else {
                    $order_dis_val = 0;
                }
            } else {
                if (is_numeric($discount)) {
                    $order_discount_type     = 0;
                    $order_discount_availble = 1;
                    $order_dis_val           = $discount;
                } else {
                    $order_dis_val = 0;
                }
            }
            if ($order_discount_availble) {
                if ($order_discount_type == 1) {
                    $save_item_added_discount_total = ($item_product_total_value / 100) * $order_dis_val;
                    $save_added_discount            = $order_dis_val . "%";
                    $save_added_discount_val        = $save_item_added_discount_total / $issue_qty;
                    $save_after_added_discount      = ($add_extra + $p_cash_price) - $save_added_discount_val;
                }
                if ($order_discount_type == 0) {
                    $save_item_added_discount_total = $order_dis_val * $issue_qty;
                    $save_added_discount            = $order_dis_val;
                    $save_added_discount_val        = $order_dis_val;
                    $save_after_added_discount      = ($add_extra + $p_cash_price) - $save_added_discount_val;
                }
            }
            //----------------------------------------------------calculate default discount total
            $default_discount = $this->Product_Discount_Model->get_relevent_discount($product_id, 1, $issue_qty, $warehouse_id);
            //calculation -----------------------------------                            
            if (!$default_discount) {
                //nothing happen        
            } else {
                $default_discount_val  = $default_discount['discount_value'];
                $default_discount_type = $default_discount['is_precentage'];
                $product_dis_id        = $default_discount['pd_discount_id'];
                if ($default_discount_type == 0) {
                    //if not presentage
                    $save_item_defult_discount_total = $issue_qty * $default_discount_val;
                    $save_default_discount           = $default_discount_val;
                    $save_default_discount_val       = $default_discount_val;
                } else {
                    //if precentage                        
                    $save_item_defult_discount_total = ($item_product_total_value / 100) * $default_discount_val;
                    $save_default_discount           = $default_discount_val . "%";
                    $save_default_discount_val       = $save_item_defult_discount_total / $issue_qty;
                }
            }
            $total_order_added_items_discount += $save_item_added_discount_total;
            $total_order_default_items_discount += $save_item_defult_discount_total;
            $save_item_total_final_value = $item_product_total_value - $save_item_added_discount_total - $save_item_defult_discount_total;
            $total_order_value += $save_item_total_final_value;
            $total_value_with_after_aded_discount += $item_product_total_value - $save_item_added_discount_total;
            //calculation end        
            $data_item = array(
                'pd_discount_id' => $product_dis_id,
                'product_price' => $add_extra + $p_cash_price,
                'discount' => $save_added_discount,
                'add_sales_discount_price' => $save_added_discount_val,
                'total_added_discount_value' => $save_item_added_discount_total,
                'discount_defualt' => $save_default_discount,
                'default_discount_price' => $save_default_discount_val,
                'total_default_discount_value' => $save_item_defult_discount_total,
                'after_discount_added_price' => $save_after_added_discount,
                'total_item_discount' => $save_item_added_discount_total + $save_item_defult_discount_total,
                'total_price' => $save_item_total_final_value
            );
            $this->Customer_Order_Process_Model->insert_update_item_table($data_item, $cus_order_item_id);
            /*
            echo " product value : ".$item_product_total_value." |----|";            
            echo " default discount : ".$save_default_discount." |----|";
            echo " default discount value : ".$save_default_discount_val." |----|";
            echo " default total discount value : ".$save_item_defult_discount_total." |----|";
            echo " added discount : ".$save_added_discount." |----|";
            echo " added discount value : ".$save_added_discount_val." |----|";
            echo " added after discount price : ".$save_after_added_discount." |----|";            
            echo " default total added discount value : ".$save_item_added_discount_total." |----|";
            echo " ";        
            echo "-------------------------------------------------------------------------------------------------------------";
            echo "#########################";
            echo "-------------------------------------------------------------------------------------------------------------";    
            echo " ";    */
        }
        //---------------------------------------------------    
        $order_discount          = $order_master_details['order_discount'];
        $order_discount_type     = 0; //value - 0 , precentage 1
        $order_discount_availble = 0;
        $order_dis_val           = 0;
        $needle                  = "%";
        if (strpos($order_discount, $needle) !== false) {
            $order_discount_in = 0;
            $order_dis_val     = preg_replace('/[^0-9.]/', '', $order_discount);
            if (is_numeric($order_dis_val)) {
                $order_discount_type     = 1;
                $order_discount_availble = 1;
            } else {
                $order_dis_val = 0;
            }
        } else {
            if (is_numeric($order_discount)) {
                $order_discount_type     = 0;
                $order_discount_availble = 1;
                $order_dis_val           = $order_discount;
            } else {
                $order_dis_val = 0;
            }
        }
        //-----------------------------------------------
        //---------------------------------------
        $final_order_amount = $total_order_value;
        if ($order_discount_availble) {
            if ($order_discount_type == 1) {
                $order_dis_val      = ($total_order_value / 100) * $order_dis_val;
                $final_order_amount = $total_order_value - $order_dis_val;
            }
            if ($order_discount_type == 0) {
                $final_order_amount = $total_order_value - $order_dis_val;
            }
        }
        //--------------------------------------    
        $data_final = array(
            'total_amount' => $final_order_amount,
            'bd_amount' => $total_value_with_after_aded_discount,
            'item_total_added_discount' => $total_order_added_items_discount,
            'item_total_default_discount' => $total_order_default_items_discount,
            'discount_val' => $order_dis_val,
            'net_amount' => $total_order_value,
            'invoice_type' => 1
        );
        $_insert    = $this->Customer_Order_Process_Model->insert_update_master_table($data_final, $order_id);
        $this->session->set_flashdata('message', 'cus Order Successfully added!');
        echo json_encode(array(
            'id' => $order_id,
            'error' => 0,
            'disMsg' => 'Save succesfully',
            'status' => 1
        ));
    }
    //roll back order on 2020-02-11
    function rollback_order()
    {
        $order_id    = $this->input->get('id');
        //value for master table 
        $data_item   = array(
            'delivery_id' => 0,
            'delivery_status' => 0
        );
        $data_master = array(
            'status' => 0,
            'delivery_id' => 0
        );
        $result      = false;
        if ($order_id > 0) {
            $result = $this->Customer_Order_Process_Model->insert_update_item_table($data_item, $order_id);
            $result = $this->Customer_Order_Process_Model->insert_update_master_table($data_master, $order_id);
        }
        if ($result == true) {
            $this->session->set_flashdata('message', 'cus Order Successfully added!');
            echo json_encode(array(
                'id' => $order_id,
                'error' => 0,
                'disMsg' => 'Save succesfully',
                'status' => 1
            ));
        } else {
            $this->session->set_flashdata('message', 'cus Order Successfully added!');
            echo json_encode(array(
                'id' => 0,
                'error' => 1,
                'disMsg' => 'Save succesfully',
                'status' => 0
            ));
        }
    }
}