\!/ KyuuKazami \!/

Path : /home/kohli/public_html/application/controllers/admin/
Upload :
Current File : /home/kohli/public_html/application/controllers/admin/ajax.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax extends CI_Controller {
    public function __construct()
    {
        parent::__construct();        
        $this->load->library("common_lib");
        $this->load->model("productm");
        $this->load->model("categorym");
        $this->load->model("contentm");
        $this->load->model("commonm");
        $this->load->model("reportsm");
        $this->load->model('userm');
    }
    
    public function get_collection_list(){
        $collections = $this->categorym->get_all_collections();
        $collection_list = "<option value=''>--Collections--</option>";
        foreach($collections as $collection){
            $collection_list .= "<option value='{$collection->collection_id}'>{$collection->collection_name}</option>";
        }
        echo json_encode(array("content" => $collection_list));
        exit;
    }
    
    public function get_category_list(){
        $categories = $this->categorym->get_all_categories();
        $category_list = "<option value=''>--Categories--</option>";
        foreach($categories as $category){
            $category_list .= "<option value='{$category->category_id}'>{$collection->category_name}</option>";
        }
        echo json_encode(array("content" => $category_list));
        exit;
    }
    
    public function get_brand_list(){
        $manufacturers = $this->commonm->get_all("manufacturers",array(),array(),"manufacturer_name");
        $manufacturer_list = "<option value=''>--Manufacturers--</option>";
        foreach($manufacturers as $manufacturer){
            $manufacturer_list .= "<option value='{$manufacturer->manufacturer_id}'>{$manufacturer->manufacturer_name}</option>";
        }
        echo json_encode(array("content" => $manufacturer_list));
        exit;        
    }
    
    public function get_content_list(){
        $matters = $this->commonm->get_all("matter",array(),array(),"title");
        $matter_list = "<option value=''>--Contents--</option>";
        foreach($matters as $matter){
            $matter_list .= "<option value='{$matter->matter_id}'>{$matter->title}</option>";
        }
        echo json_encode(array("content" => $matter_list));
        exit;         
    }
    
    public function save_navigation(){
        $form_data = $this->common_lib->get_post("form_data");        
        $form_data_fields = explode("&",$form_data);
        foreach($form_data_fields as $field_pair){
            $field_pair_data = explode("=",$field_pair);
            $field_name = urldecode($field_pair_data[0]);
            $$field_name = urldecode($field_pair_data[1]);
        }
        $this->commonm->_delete_rows("main_navigation",array("menu_id < " => 9999999999));
        for($nav = 1;$nav <= 10;$nav++){
            $menu_label = "menu_label_$nav";
            $menu_type = "menu_type_$nav";
            $collection_id = "collection_id_$nav";
            $category_id = "category_id_$nav";
            $brand_id = "brand_id_$nav";
            $content_id = "content_id_$nav";
            $show_auto_dropdown = "show_auto_dropdown_$nav";                        
            if($this->common_lib->fSafeChar($$menu_label) != ""){
                $menu_data = array();
                $menu_data['menu_id'] = $nav;
                $menu_data['menu_label'] = $this->common_lib->fSafeChar($$menu_label);
                $menu_data['menu_type'] = $this->common_lib->fSafeChar($$menu_type);
                $menu_data['collection_id'] = $this->common_lib->fSafeNum($$collection_id);
                $menu_data['category_id'] = $this->common_lib->fSafeNum($$category_id);
                $menu_data['brand_id'] = $this->common_lib->fSafeNum($$brand_id);
                $menu_data['content_id'] = $this->common_lib->fSafeNum($$content_id);
                $menu_data['show_auto_dropdown'] = $this->common_lib->fSafeNum($$show_auto_dropdown);
                $this->commonm->db_insert($menu_data,"main_navigation");                
            }
        }
        echo "A";
        exit;
    }
    
    public function get_order_notes(){
        $order_id = $this->common_lib->get_get("token");
        $order_id = $this->common_lib->decode($order_id);
        
        $order_detail = $this->commonm->get_all("orders",array("order_id" => $order_id));
        if(count($order_detail) == 0){
            echo json_encode(array("error" => 'Sorry, Order notes not found!'));
            exit;
        }
    }
    
    public function save_order_notes(){
        $order_id = $this->common_lib->get_get("token");
        $order_id = $this->common_lib->decode($order_id);
        
        $notes = $this->common_lib->get_get("notes");
        
        if($notes == ""){
            echo json_encode(array("error" => "Notes can't be left empty!"));
            exit;
        }
        
        $order_detail = $this->commonm->get_all("orders",array("order_id" => $order_id));
        if(count($order_detail) == 0){
            echo json_encode(array("error" => 'Order notes not saved successfully!'));
            exit;
        }
        
        $added_date = date("Y-m-d h:i:s");
        $order_notes['order_id'] = $order_id;
        $order_notes['notes'] = $notes;
        $order_notes['added_by'] = 0;
        $order_notes['added_date'] = $added_date;
        
        $this->commonm->db_insert($order_notes,"order_notes");
        
        $notes_html = '<tr>
							<td>                                                                        
                                <span class="date">'.$this->common_lib->date_detail_format($added_date,false).'</span>
                                <p><strong>'.$notes.'</strong></p>
                            </td>
						</tr>';
        
        echo json_encode(array("html" => $notes_html,"message" => "Order Notes added successfully"));
        exit;
        
    }
    
    public function change_order_status(){
        $order_id = $this->common_lib->get_post("token");
        $order_id = $this->common_lib->decode($order_id);
        
        $order_detail = $this->commonm->get_all("orders",array("order_id" => $order_id));
        if(count($order_detail) == 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, Record not found!</strong></div>'));
            exit;
        }
        
        $order_status = $this->common_lib->get_post("os");
        $order_status = $this->common_lib->decode($order_status);
        
        $status_mode = $this->common_lib->get_post("mode");
        
        $order_data['order_status'] = $order_status;        
        $this->commonm->db_update($order_data,"orders","order_id",$order_id);
        
        if($status_mode == "true"){
            $item_status['item_status'] = $order_status;
            $order_items = $this->commonm->get_all("order_items",array("order_id" => $order_id));
            foreach($order_items as $items){
                $old_status = $items->item_status;
                $this->commonm->db_update($item_status,"order_items","order_id",$order_id);
                    
                if($this->common_lib->is_restock_status($old_status)){
                    
                }
                                                
                if(!$this->common_lib->is_cancelled_status($old_status) && $this->common_lib->is_cancelled_status($order_status) && $items->is_live_inventory == 1){
                                                                
                    $product_size = $this->commonm->get_all("product_sizes",array("product_id"=>$items->product_id,"size_id"=>$items->size_id));                            
                    $stock_left = ($product_size[0]->stock_available + $items->quantity);
                    
                    $inventory_data['order_id'] = $order_id;
                    $inventory_data['stock_added'] = $items->quantity;
                    $inventory_data['description'] = "Order cancelled/deleted by admin";
                    $inventory_data['user_id'] = $order_detail[0]->user_id;
                    $inventory_data['product_id'] = $items->product_id;
                    $inventory_data['size_id'] = $items->size_id;
                    $inventory_data['stock_left'] = $stock_left;
                    $inventory_data['date_added'] = $this->common_lib->mysqlDateFormat();                
                    
                    
                    $this->common_lib->log_inventory_history($inventory_data);
                    $this->commonm->db_update(array("stock_available"=>$stock_left),"product_sizes","product_size_id",$product_size[0]->product_size_id);   
                }                                
            }             
        }
    }
    
    public function receive_vendor_order_form(){
        $v_order_id = $this->common_lib->get_get("token");
        $v_order_id = $this->common_lib->decode($v_order_id);
        $vendor_order = $this->commonm->get_all("vendor_orders",array("v_order_id" => $v_order_id));
        if(count($vendor_order) == 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, Record not found!</strong></div>'));
            exit;
        } 
        
        $data['quantity'] = $vendor_order[0]->stock_required;
        $data['token'] = $this->common_lib->get_get("token");
        echo json_encode(array("html" => $this->load->view("admin/ajax_form/_receive_vendor_quantity_form",$data,true)));
        exit;
    }
    
    public function receive_vendor_order(){
        $form_data = urldecode($this->common_lib->get_get("fdata"));
        $form_data_fields = explode("=",$form_data);        
        $token = $this->common_lib->decode($form_data_fields[1]);        
        $v_order_id = $token;        
        $vendor_order = $this->commonm->get_all("vendor_orders",array("v_order_id" => $v_order_id));
        if(count($vendor_order) == 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>'.$v_order_id.'Sorry, Record not found!</strong></div>'));
            exit;
        }
        
        $stock_required = $vendor_order[0]->stock_required;
        $product_id = $vendor_order[0]->product_id;
        $size_id = $vendor_order[0]->size_id; 
        
        $this->commonm->db_update(array("stock_required"=>0,"stock_received"=>$stock_required,"stock_remaining"=>0,"status"=>"D","received_date"=>$this->common_lib->mysqlDateFormat()),
                                  "vendor_orders","v_order_id",$v_order_id);
        
        $current_size = $this->commonm->get_all("product_sizes",array("product_id" => $product_id,"size_id"=>$size_id));
        
        if(count($current_size) > 0){
            $total_stock = $current_size[0]->stock_available + $stock_required;
            $this->commonm->db_update(array("stock_available"=>$total_stock),"product_sizes","product_size_id",$current_size[0]->product_size_id);
        }else{
            
            $total_stock = $stock_required;
            $this->commonm->db_insert(array("stock_available"=>$total_stock),"product_sizes");
        }
        
        $inventory_data['order_id'] = $v_order_id;
        $inventory_data['stock_added'] = $stock_required;
        $inventory_data['description'] = "Inventory received from Vendor";
        $inventory_data['user_id'] = 0;
        $inventory_data['product_id'] = $product_id;
        $inventory_data['size_id'] = $size_id;
        $inventory_data['stock_left'] = $total_stock;
        $inventory_data['date_added'] = $this->common_lib->mysqlDateFormat();                
        
        $this->common_lib->log_inventory_history($inventory_data);
                
        echo json_encode(array("message" => '<div class="alert alert-dismissable alert-success"><strong>Quantity recieved successfully</strong></div>'));
        exit;
    }
    
    public function update_order_item(){
        
        $form_data = $this->common_lib->get_get("fdata");
        $form_data_fields = explode("&",$form_data);
        $order_items = array();
        $order_id = 0;
        foreach($form_data_fields as $field_pair){
            $field_pair_data = explode("=",$field_pair);
            $field_name = urldecode($field_pair_data[0]);            
            if($field_name == "token"){
                $order_id = $this->common_lib->decode(urldecode($field_pair_data[1]));
            }else{
                $$field_name = urldecode($field_pair_data[1]);    
            }                        
        }
                                
        $result = $this->reportsm->get_order_item_detail_row(array("oi.order_item_id" => $order_id));
        if(count($result) == 0){
            echo json_encode(array("error" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, Record not found!</strong></div>'));
            exit;
        }else{
            $product_detail = $this->commonm->get_all("products",array("product_id" => $result[0]->product_id));
            $size_detail = $this->commonm->get_all("product_sizes",array("product_id" => $result[0]->product_id,"size_id" => $result[0]->size_id));
            
            $update_data['quantity'] = $quantity;
            $update_data['qty_remaining'] = $quantity - $result[0]->qty_shipped;
            $update_data['item_status'] = $order_status;
            
            $this->commonm->db_update($update_data,"order_items","order_item_id",$result[0]->order_item_id);                      
            
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-success"><strong>Item saved successfully!</strong></div>'));
            exit;   
        }
    }
    
    public function item_edit_layout(){
        
        $order_id = $this->common_lib->get_get("token");
        $order_id = $this->common_lib->decode($order_id);
        $result = $this->reportsm->get_order_item_detail_row(array("oi.order_item_id" => $order_id));
        if(count($result) == 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, Record not found!</strong></div>'));
            exit;
        }        
        $order_status_list = $this->commonm->get_all("order_status");
        //$order_status_list = $this->commonm->get_all("product_sizes");
        $data['token'] = $this->common_lib->get_get("token");
        $data['order_status_list'] = $order_status_list;
        $data['order_item_detail'] = $result;
        echo json_encode(array("html" => $this->load->view("admin/ajax_form/_edit_item_form",$data,true)));
        exit;
    }    
    
    public function add_order_item(){
        
        $form_data = urldecode($this->common_lib->get_get("fdata"));        
        $form_data_fields = explode("&",$form_data);
        $sizes = array();
        $order_id = 0;
        foreach($form_data_fields as $field_pair){
            $field_pair_data = explode("=",$field_pair);
            $field_name = urldecode($field_pair_data[0]);              
            if($field_name == "token"){
                $order_id = $this->common_lib->decode($field_pair_data[1]);            
            }elseif($field_name == "sizes[]"){
                $sizes[] = $field_pair_data[1];
            }else{
                $$field_name = $field_pair_data[1];
            }
        }                        
        
        $order_detail = $this->commonm->get_all("orders",array("order_id" => $order_id));
        if(count($order_detail) == 0){
            echo json_encode(array("error" => 'Sorry, no record found!'));
            exit;
        }
        
        $total_price = 0;
        
        foreach($sizes as $size_id){
            $size_quantity = "quantity_$size_id";        
            $size_quantity = $$size_quantity;
            $product_id = $this->common_lib->fSafeNum($product_id);
            $size_detail = $this->commonm->get_all("product_sizes",array("size_id" => $size_id,"product_id" => $product_id));
            
            $size_price = $size_detail[0]->stock_price;
            if($size_detail[0]->stock_discounted_price > 0){
                $size_price = 0;
            }
            
            $item_data = array();
            $item_data['order_id'] = $order_id;
            $item_data['product_id'] = $product_id;
            $item_data['size_id'] = $size_id;
            $item_data['quantity'] = $size_quantity;
            $item_data['price'] = $size_price;
            $item_data['qty_remaining'] = $size_quantity;
            $item_data['item_status'] = "P";
            $item_data['date_required'] = $this->common_lib->mysqlDateFormat($required_date,false);
            $item_data['promising_date'] = $this->common_lib->mysqlDateFormat($required_date,false);
            $item_data['performance_date'] = $this->common_lib->mysqlDateFormat($performance_date,false);
            
            $total_price += $this->common_lib->price_format($size_price * $size_quantity,false);
            
            $this->commonm->db_insert($item_data,"order_items");
            
        }
        
        $sub_total = $order_detail[0]->sub_total + $total_price;
        $order_amount = $order_detail[0]->order_amount + $total_price;
        $amount_remaining = $order_detail[0]->amount_remaining + $total_price;
        
        $order_data = array();
        
        $order_data['sub_total'] = $sub_total;
        $order_data['order_amount'] = $order_amount;
        $order_data['amount_remaining'] = $amount_remaining;
        
        $this->commonm->db_update($order_data,"orders","order_id",$order_id);
                                
        echo json_encode(array("message" => "Item added successfully"));
        exit;
    }
    
    public function add_order_item_form(){
        
        $order_id = $this->common_lib->get_get("token");
        $order_id = $this->common_lib->decode($order_id);                        
        
        $order_detail = $this->commonm->get_all("orders",array("order_id" => $order_id));
        
        if(count($order_detail) == 0){
            echo json_encode(array("error" => 'Sorry, no record found!'));
            exit;
        }
        
        $product_list = $this->commonm->get_all("products",array("active"=>1),array(),"product_name");
        $data['product_list'] = $product_list;
        $data['token'] = $this->common_lib->get_get("token");        
        echo json_encode(array("html" => $this->load->view("admin/ajax_form/_add_item_form",$data,true)));
        exit;
    }
    
    public function get_product_sizes_data(){
        $order_id = $this->common_lib->get_post("token");
        $order_id = $this->common_lib->decode($order_id);
        $result = $this->reportsm->get_order_item_detail_row(array("oi.order_id" => $order_id));
        if(count($result) == 0){
            echo '<div class="alert alert-dismissable alert-danger"><strong>Sorry, no record found!</div>';
            exit;
        }
        
        $size_list = array();
        foreach($result as $val){
            $size_list[] = $val->size_id;
        }
        $size_list = implode(",",$size_list);
        
        $product_id = $this->common_lib->get_n_post("pid");
        //$product_sizes = $this->productm->get_product_sizes($product_id,array("s.size_id not in ($size_list)"));
        $product_sizes = $this->productm->get_product_sizes($product_id);
                        
        $sizes_data = "";        
        foreach($product_sizes as $sizes){
            $sizes_data .= '
            <div class="form-group">
                <div class="col-md-1">
                    <div class="input-group">
                        <input type="checkbox" value="'.$sizes->size_id.'" name="sizes[]" class="checkbox_row">
                    </div>                                            
                </div>
                <div class="col-md-4">
                    <div class="input-group">                                                
                        <span class="input-group-addon">'.$sizes->size.'</span>
                        <input type="text" class="form-control" name="quantity_'.$sizes->size_id.'" placeholder="Quantity" value="">
                        <span class="input-group-addon">'.$sizes->stock_available.'</span>
                    </div>                                            
                </div>                
                <div class="clearfix"></div>
            </div>            
            ';
        }
        $general_settings = $this->common_lib->get_product_setting("show_required_date",true);
        if($general_settings->show_required_date == 1){
            $sizes_data .= '
            <div class="form-group">
                <div class="col-md-7">
                    <label>Required Date:</label>
                    <div class="input-group date datepicker-pastdisabled">
                        <input type="text" name="required_date" id="required_date" class="form-control" value="'.date("m/d/Y",strtotime("+15 days")).'" readonly="">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>                    
                    <script>$(".datepicker-pastdisabled").datepicker({startDate: "today"});</script>
                </div>
            </div>';
        }
        if($general_settings->show_promising_date == 1){
            $sizes_data .= '
            <div class="form-group">
                <div class="col-md-7">
                    <label>Performance Date:</label>
                    <div class="input-group date datepicker-pastdisabled">
                        <input type="text" name="performance_date" id="performance_date" class="form-control" value="'.date("m/d/Y",strtotime("+15 days")).'" readonly="">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>                    
                    <script>$(".datepicker-pastdisabled").datepicker({startDate: "today"});</script>
                </div>
            </div>';
        }
        echo $sizes_data;
        exit;
    }
    
    public function save_shipping_box(){
        $form_data = $this->common_lib->get_get("fdata");
        $form_data_fields = explode("&",$form_data);
        $order_items = array();
        $order_id = 0;
        foreach($form_data_fields as $field_pair){
            $field_pair_data = explode("=",$field_pair);
            $field_name = urldecode($field_pair_data[0]);
            if($field_name == "token"){
                $order_id = $this->common_lib->decode(urldecode($field_pair_data[1]));
            }elseif($field_name == "order_items[]"){
                $order_items[] = $this->common_lib->decode(urldecode($field_pair_data[1]));
            }else{
                $$field_name = urldecode($field_pair_data[1]);
            }
        }
        
        $tracking_id = rand(111111111,999999999);
        
        $current_mysql_date = $this->common_lib->mysqlDateFormat();
        
        $shipping_boxes = $this->common_lib->decode($shipping_boxes);                
        $shipping_boxes = explode("~~",$shipping_boxes);
        $shipping_cost = $shipping_boxes[1];
        $shipping_boxes = $shipping_boxes[0];
        
        $shipping_services = $this->commonm->get_all("shipping_services",array("shipping_service_id" => $shipping_service_id));
        
        $invoice_data['order_id'] = $order_id;
        $invoice_data['tracking_id'] = $tracking_id;
        $invoice_data['box_info'] = $shipping_boxes;
        $invoice_data['shipping_service_id'] = $shipping_service_id;
        $invoice_data['shipping_service'] = $shipping_services[0]->shipping_service;
        $invoice_data['shipping_sub_service'] = $shipping_sub_services;
        $invoice_data['service_cost'] = $shipping_cost;
        $invoice_data['total_weight'] = $total_weight;
        $invoice_data['invoice_date'] = $current_mysql_date;
        $invoice_data['expected_date'] = $this->common_lib->mysqlDateFormat(strtotime("+2 days"));
        $invoice_data['date_shipped'] = $current_mysql_date;
                                                   
        if(count($order_items) > 0){
            echo implode(",",$order_items);
            $result_items = $this->reportsm->get_order_item_row("order_item_id in (".  implode(",", $order_items).")");
        }else{            
            $result_items = $this->reportsm->get_order_item_row("order_id = $order_id");
        }
        
        $invoice_id = $this->commonm->db_insert($invoice_data,"invoices");
                       
        
        
        if($invoice_id > 0){
            foreach($result_items as $row_item){
                $invoice_items = array();
                $invoice_items['order_item_id'] = $row_item->order_item_id;
                $invoice_items['invoice_id'] =  $invoice_id;
                $invoice_items['order_id'] = $order_id;
                $invoice_items['qty_shipped'] = $row_item->qty_remaining;
                $invoice_items['size_id'] = $row_item->size_id;
                $this->commonm->db_insert($invoice_items,"invoice_items");


                $order_item_update = array();
                $order_item_update['item_status'] = "S";
                $order_item_update['qty_shipped'] = $row_item->quantity;
                $order_item_update['qty_remaining'] = 0;
                $this->commonm->db_update($order_item_update,"order_items","order_item_id",$row_item->order_item_id);               
                $this->db->query("update product_sizes set stock_available = stock_available - ".$row_item->quantity. " where product_id = {$row_item->product_id} and size_id = {$row_item->size_id}");
            }
            
            $order_update = array();
            $order_update['order_status'] = "I";
            $this->commonm->db_update($order_update,"orders","order_id",$order_id);
            
            
            
        }else{
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>There is some problem while saving shipping box, Please try again later.</strong></div>'));
        }        
        exit;
    }
    
    public function get_shipping_boxes(){
        $services_list_html = "";
        
        $shipping_packages = array("Overnight Air" => array("Box 3 x 4" => 35,"Box 3 x 5" => 37,"Box 4 x 4" => 38,"Box 4 x 5" => 39,"Box 5 x 5" => 40,"Box 5 x 6" => 41,"Box 6 x 6" => 42),
                                   "1 Day Air" => array("Box 3 x 4" => 25,"Box 3 x 5" => 26,"Box 4 x 4" => 28,"Box 4 x 5" => 29,"Box 5 x 5" => 30,"Box 5 x 6" => 31,"Box 6 x 6" => 32),
                                   "2 Day Air" => array("Box 3 x 4" => 15,"Box 3 x 5" => 16,"Box 4 x 4" => 18,"Box 4 x 5" => 19,"Box 5 x 5" => 20,"Box 5 x 6" => 21,"Box 6 x 6" => 22),
                                   "2 Day Mail" => array("Box 3 x 4" => 11,"Box 3 x 5" => 12,"Box 4 x 4" => 13,"Box 4 x 5" => 14,"Box 5 x 5" => 14,"Box 5 x 6" => 15,"Box 6 x 6" => 16),
                                   "3 Day Mail" => array("Box 3 x 4" => 8,"Box 3 x 5" => 9,"Box 4 x 4" => 10,"Box 4 x 5" => 11,"Box 5 x 5" => 12,"Box 5 x 6" => 13,"Box 6 x 6" => 14)
                                  );
        $shipping_services = $this->common_lib->get_n_get("ss");                
        
        if(!array_key_exists($shipping_services, $shipping_packages)){            
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>Please select service to continue</strong></div>'));
            exit;
        }
        
        $shipping_boxes = $shipping_packages[$shipping_services];                        
        $select_price = 0;
        $services_list_html .= "
        <div class='form-group'>
            <label for='shipping_sub_services' class='col-lg-2 control-label'>Boxes</label>
            <div class='col-lg-7'>";
                $services_list_html .= "<select class='form-control' id='shipping_boxes' name='shipping_boxes'>";                
                foreach($shipping_boxes as $service_box => $service_price){
                    if($select_price == 0){
                        $select_price = $service_price;                        
                    }
                    $services_list_html .= "<option value='".$this->common_lib->encode($service_box."~~".$service_price)."' data-price='{$service_price}'>{$service_box} - {".$this->common_lib->currency_price($service_price)."}</option>";
                }                    
                $services_list_html .= "
                </select>
            </div>
            
        </div>
        <div class='form-group highlight'>
            <label class='col-lg-2 control-label'>Cost</label>
            <div class='col-lg-7'>
                <div class='input-group'>
                    <span class='input-group-addon'>$</span>                        
                    <input type='text' class='form-control' disabled value='".$select_price."' />
                </div>
            </div>
        </div>
        ";
        echo json_encode(array("html" => $services_list_html));
        exit;
    }
    
    public function get_shipping_options(){
                
        $total_weight = $this->common_lib->get_n_get("wt");
        $box_length = $this->common_lib->get_n_get("l");
        $box_width = $this->common_lib->get_n_get("w");
        $box_height = $this->common_lib->get_n_get("h");
        
        if($total_weight == 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>Please enter Weight!</strong></div>'));
            exit;
        }
        
        if($box_length == 0 || $box_width == 0 || $box_height == 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>Please enter valid box dimensions!</strong></div>'));
            exit;
        }
        
        $shipping_service_id = $this->common_lib->get_n_get("shipping_service_id");
        $shipping_services = $this->commonm->get_all("shipping_services",array("shipping_service_id" => $shipping_service_id));
        if(count($shipping_services) == 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, no services found for this shipping!</strong></div>'));
            exit;
        }
        
        $service_array = array(
							   '03' => 'UPS Ground',
							   '12' => 'UPS Three-Day Select',
							   '02' => 'UPS Second Day Air',
							   '13' => 'UPS Next Day Air Saver',
							   '01' => 'UPS Next Day Air',
							   '14' => 'UPS Next Day Air Early A.M.',
							   '59' => 'UPS Second Day Air A.M.',
							   '65' => 'UPS Saver'
							   );
		
		$this->load->library('upsrate');
		$this->upsrate->setCredentials(UPS_ACCESSLICENSENUMBER, UPS_USERID, UPS_PASSWORD, UPS_SHIPPERNUMBER);
        $services_list_html = "";
        $services_list_html .= "
        <div class='form-group'>
            <label for='shipping_sub_services' class='col-lg-2 control-label'>Services</label>
            <div class='col-lg-9'>";
                $services_list_html .= "<select class='form-control' id='shipping_sub_services' name='shipping_sub_services'>";
                $services_list_html .= "<option value=''>Select Service</option>";
                        
        		foreach($service_array as $key => $value){
        			$result[$key] = $this->upsrate->getRate(UPS_POSTALCODE, 60450, $key, $box_length, $box_width, $box_height, $total_weight);                    
                    if(!in_array('FALSE', $result)){                
                        if(true){
                            $ups_error	= array();
                            $ups_error_des	= '';                                                        
                            
                            if(isset($result[$key]['RESPONSE']['ERROR'])){
                                $ups_error[] = '0';
                                $ups_error_des	= 'Error: '.$result[$key]['RESPONSE']['ERROR']['ERRORDESCRIPTION'].'<br />';
                            }
    				        else{
    				            $service_price = $this->common_lib->currency_price($result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE']);
                                $services_list_html .= "<option data-price='".$result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE']."' data-service='$value' data-days='".$result[$key]['RATEDSHIPMENT']['GUARANTEEDDAYSTODELIVERY']."' value='{$key}'>{$value} - ".$service_price."</option>";
                                        
                                /*                                                                 
            					$ups_error[] = '1';
            					$checked = '';
    					        if($i == 0) $checked = 'checked="checked" ';
                                $rate_reply .= '<label><input type="radio" '.$checked.'name="ups_service" value="'.$value.'" id="ups_service_'.$i.'" /> <strong>'.$value.'</strong> -  '.((empty($result[$key]['RATEDSHIPMENT']['GUARANTEEDDAYSTODELIVERY']))? '' : '<strong>Days:</strong> '.$result[$key]['RATEDSHIPMENT']['GUARANTEEDDAYSTODELIVERY'].'; ').'<strong>Price:</strong> $ '.$result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE'].'</label>';
                                $rate_reply .= '<input name="ups_price_'.$i.'" id="ups_price_'.$i.'" readonly="true" type="hidden" value="'.$result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE'].'" />';
                                $session_array[] = array('service_name'=>'ups_'.$value, 'service_time'=>$result[$key]['RATEDSHIPMENT']['GUARANTEEDDAYSTODELIVERY'], 'service_price'=>$result[$key]['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE']);
                                */
    				        }
        				        
                            
                            //$rate_reply .= '</div></div>';                    
        			
                            ///if(!in_array('1',$ups_error)){
                            	//$rate_reply .= '<p class="warning icon_warn">We were not able to fetch UPS rate for the following reason:<br />'.$ups_error_des.'</p>';
                            //}else $ups_flag = TRUE;
                        }
                    }
                }
                $services_list_html .= "
                </select>
            </div>   
            <!--div class='col-lg-2'><button type='button' class='btn btn-default search_shipping_boxes pull-right'><i class='fa fa-search'></i></button></div-->
        </div>";
        
         /*                      
        $shipping_packages = array("Overnight Air" => array("Box 3 x 4" => 35,"Box 3 x 5" => 37,"Box 4 x 4" => 38,"Box 4 x 5" => 39,"Box 5 x 5" => 40,"Box 5 x 6" => 41,"Box 6 x 6" => 42),
                                   "1 Day Air" => array("Box 3 x 4" => 25,"Box 3 x 5" => 26,"Box 4 x 4" => 28,"Box 4 x 5" => 29,"Box 5 x 5" => 30,"Box 5 x 6" => 31,"Box 6 x 6" => 32),
                                   "2 Day Air" => array("Box 3 x 4" => 15,"Box 3 x 5" => 16,"Box 4 x 4" => 18,"Box 4 x 5" => 19,"Box 5 x 5" => 20,"Box 5 x 6" => 21,"Box 6 x 6" => 22),
                                   "2 Day Mail" => array("Box 3 x 4" => 11,"Box 3 x 5" => 12,"Box 4 x 4" => 13,"Box 4 x 5" => 14,"Box 5 x 5" => 14,"Box 5 x 6" => 15,"Box 6 x 6" => 16),
                                   "3 Day Mail" => array("Box 3 x 4" => 8,"Box 3 x 5" => 9,"Box 4 x 4" => 10,"Box 4 x 5" => 11,"Box 5 x 5" => 12,"Box 5 x 6" => 13,"Box 6 x 6" => 14)
                                  );
        $services_list_html = "";
        $services_list_html .= "
        <div class='form-group'>
            <label for='shipping_sub_services' class='col-lg-2 control-label'>Services</label>
            <div class='col-lg-7'>";
                $services_list_html .= "<select class='form-control' id='shipping_sub_services' name='shipping_sub_services'>";
                $services_list_html .= "<option value=''>Select Service</option>";
                foreach($shipping_packages as $service_name => $service_options){
                    $services_list_html .= "<option value='{$service_name}'>{$service_name}</option>";
                }
                $services_list_html .= "
                </select>
            </div>   
            <div class='col-lg-3'><button type='button' class='btn btn-default search_shipping_boxes'><i class='fa fa-search'></i></button></div>
        </div>";
        */        
        echo json_encode(array("html" => $services_list_html));
        exit;
                
    }
    
    public function add_order_shipment(){
        $order_id = $this->common_lib->get_get("token");            
        $order_id = $this->common_lib->decode($order_id);
        $result = $this->reportsm->get_inventory_report("o.order_id  = $order_id and (oi.item_status = 'P')");
        if(count($result) == 0){
            echo json_encode(array("html" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, Record not found!</strong></div>'));
            exit;
        }
        $shipping_services = $this->commonm->get_all("shipping_services");
        
        $data['token'] = $this->common_lib->get_get("token");
        $data['result'] = $result;
        $data['shipping_services'] = $shipping_services;
        echo json_encode(array("html" => $this->load->view("admin/ajax_form/_order_shipments",$data,true)));
        exit;
    }
    
    public function get_order_shipping_detail(){
        $order_id = $this->common_lib->get_post("token");            
        $order_id = $this->common_lib->decode($order_id);            
        $order_data = $this->reportsm->get_customer_orders(array("o.order_id" => $order_id));
        $return_data = '
        <h4>Delivery Detail</h4>
        <div class="login_user_name"><b>'.$order_data[0]->ship_first_name." ".$order_data[0]->ship_last_name.'</b></div>
        <div class="login_user_address"><i>'.$order_data[0]->ship_address.'</i></div>
        <div class="login_user_address"><i>'.$order_data[0]->ship_address1.'</i></div>
        <div class="login_user_address"><i>'.$order_data[0]->ship_city.', '.$order_data[0]->ship_state .' - '.$this->common_lib->get_country_by_id($order_data[0]->ship_country).', '.$order_data[0]->ship_zipcode.'</i></div>
        <div class="login_user_phone"><b>Ph:</b> '.$order_data[0]->ship_mobile.'</div>
        <a href="#order_shipping_form" data-id="'.$this->common_lib->encode($order_data[0]->order_id).'" type="button" class="btn btn-danger btn-sm order_shipping_form" >Edit Address</a>';       
        echo $return_data;
    }
    
    public function save_shipping_detail(){
        $form_data = $this->common_lib->get_get("fdata");
        $form_data_fields = explode("&",$form_data);
        foreach($form_data_fields as $field_pair){
            $field_pair = explode("=",$field_pair);
            $_POST[$field_pair[0]] = urldecode($field_pair[1]);
        }
        if($this->common_lib->run_shipping_validation()){
            $user_data = array();
            $user_data = $this->common_lib->user_form_shipping_fields(true);
            $order_id = $this->common_lib->get_post("token");            
            $order_id = $this->common_lib->decode($order_id);            
            $result = $this->reportsm->get_customer_orders(array("o.order_id" => $order_id));
            $this->commonm->db_update($user_data,'orders','order_id',$order_id);
            
            if($this->common_lib->get_n_post("save_perm") == 1){                
                $user_data = $this->common_lib->user_form_shipping_fields();
                $this->userm->_up_profile($result[0]->user_id,$user_data);
            }
            
            echo json_encode(array("message" => 'done'));
            exit;
        }else{
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><b>'.validation_errors().'</b></div>'));
            exit;
        }
    }
    
    public function order_shipping_form(){
        $order_id = $this->common_lib->get_get("token");
        $order_id = $this->common_lib->decode($order_id);
        $result = $this->reportsm->get_customer_orders(array("o.order_id" => $order_id));
        if(count($result) == 0){
            echo json_encode(array("html" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, Record not found!</strong></div>'));
            exit;
        }
        $country_list = $this->commonm->get_all("countries");
        $data['country_list'] = $country_list;
        $data['token'] = $this->common_lib->get_get("token");
        $data['user_profile'] = $result;        
        echo json_encode(array("html" => $this->load->view("admin/ajax_form/_shipping_order_form",$data,true)));
        exit;
    }
    
    public function vendor_order_form(){
        $order_item_id = $this->common_lib->get_get("token");
        $order_item_id = $this->common_lib->decode($order_item_id);
        $order_item_id = explode("~",$order_item_id);
        $result = $this->reportsm->get_order_item_detail_row(array("oi.product_id" => $order_item_id[1],"oi.size_id"=>$order_item_id[0]));
        if(count($result) == 0){
            echo json_encode(array("html" => '<div class="alert alert-dismissable alert-danger"><strong>Sorry, Record not found!</strong></div>'));
            exit;
        }
        
        $vendor_list = $this->commonm->get_all("manufacturers");
        
        $data['token'] = $this->common_lib->get_get("token");
        $data['vendor_list'] = $vendor_list;
        $data['item_sku'] = $result[0]->sku;
        $data['item_size'] = $result[0]->size;
        echo json_encode(array("html" => $this->load->view("admin/ajax_form/_vendor_order_add_form",$data,true)));
        exit;
    }
    
    function save_vendor_order(){
        $form_data = $this->common_lib->get_get("fdata");
        $form_data_fields = explode("&",$form_data);
        foreach($form_data_fields as $field_pair){
            $field_pair = explode("=",$field_pair);
            $$field_pair[0] = $field_pair[1];
        }
        $error_msg = array();
        if($this->common_lib->fSafeNum($stock_required) == 0){
            $error_msg[] = "Valid value for Stock";
        }
        if($this->common_lib->fSafeNum($vendor_id) == 0){
            $error_msg[] = "Choose Vendor";
        }
        
        if(count($error_msg) > 0){
            echo json_encode(array("message" => '<div class="alert alert-dismissable alert-danger"><b>Please fix the following issues:</b><br/>'.  implode("<br />", $error_msg)."</div>"));
            exit;
        }
        
        $order_item_id = urldecode($token);
        $order_item_id = $this->common_lib->decode($order_item_id);
        $order_item_id = explode("~",$order_item_id);        
        $result = $this->reportsm->get_order_item_detail_row(array("oi.product_id" => $order_item_id[1],"oi.size_id"=>$order_item_id[0]));
                
        
        $vendor_data['vendor_id'] = $vendor_id;
        $vendor_data['stock_required'] = $stock_required;
        $vendor_data['stock_remaining'] = $stock_required;
        $vendor_data['size_id'] = $result[0]->size_id;
        $vendor_data['product_id'] = $result[0]->product_id;
        $vendor_data['required_date'] = $this->common_lib->mysqlDateFormat(urldecode($required_date),false);
        
        $this->commonm->db_insert($vendor_data,"vendor_orders");
        echo json_encode(array("message" => '<div class="alert alert-dismissable alert-success"><b>Vendor order inserted successfully</div>'));
        exit;
    }
    
}

@KyuuKazami