<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
   
class Order_Administration extends CI_Controller
{
    var $main_menu_name = "order_administration";
    var $sub_menu_name = "order_administration";
    
   
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Colombo");
        $this->load->model('Common_Model');
        $this->load->model('Order_Model');
        $this->load->model('User_Model');
        $this->load->model('Customer_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Product_Models');
        $this->load->model('Stock_Counter_Model');
        
    }
    public function index()
    {
       show_404();
    }
       
    function order_panning(){
        
	    $data['main_menu_name'] = 'administrator';
		$data['sub_menu_name'] = 'order_panning';
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['order_type_list'] = $this->Order_Model->get_order_type();
	    $this->load->view('administration/order/order_planning',$data);
	}
	
	
		public function get_order_aproved_pending_pickup_list(){
        $values = $this->Order_Model->get_order_approved_pending_pickup_list();
        $item_list = $this->Order_Model->get_order_approved_pending_pickup_item_list();
        $product_list = $this->Order_Model->get_order_approved_pending_pickup_products();
        $product_stock=array();
        foreach($product_list as $pi){
	        $stock=$this->Stock_Counter_Model->get_availble_stock_for_invoicing_and_order('',$pi['product_id']); 
	        $nested_data=array(
	            'product_id'=>$pi['product_id'],
	            'stock'=>$stock,
	            );
	            $product_stock[]=$nested_data;
	    }
        
        $data          = array();
        if (!empty($values)) {
           
            foreach ($values as $products) {
                $row=array();
                $order_status=1;
               
               
                $table_start='<table  class="table" id="tbl_'.$products->odr_id.'">';
	            $table_head_start='<thead >';
	            $table_head_end='</thead>';
	            $table_end='</table>';
	            $table_body=' <tr><th>PD CODE </th><th>PD NAME </th><th data-toggle="tooltip" data-placement="top" title="UNIT OF MEASUREMENTS">UOM</th><th data-toggle="tooltip" data-placement="top" title="APPROVED QUANTITY">A.QTY</th><th data-toggle="tooltip" data-placement="top" title="CURRANT STOCK">C.STOCK</th><th data-toggle="tooltip" data-placement="top" title="REQUIRED QUANTITY">R.QTY</th><th data-toggle="tooltip" data-placement="top" title="CARRY FORWORD STOCK">C/F STOCK</th><td></td></tr>';
	            
	            
	            foreach($item_list as $it){
	                $order_item_status=1;
	                
	                if($it['odr_id']!=$products->odr_id){
	                   continue; 
	                }
	                 $currant_stock=0;
	            foreach($product_stock as $key => $value)
                        {
                            if($value['product_id']==$it['product_id']){
                             $currant_stock=$value['stock'];
                             $product_stock[$key]['stock'] = $value['stock']-$it['request_qty'];
                             
                             if($product_stock[$key]['stock']<0){
                                 $order_item_status=0;
                                 $order_status=0;
                             }
                             
                             if($order_item_status==0){
                                $warning_tr='style="background-color:#FFCCCB;"';
                             }else{
                                 $warning_tr='';
                             }
                              $table_body.='<tr '.$warning_tr.'><td>'.$it['product_code'].'</td><td>'.$it['product_name'].'</td><td>'.$it['unit_code'].'</td><td>'.$it['approved_qty'].'</td><td>'.$currant_stock.'</td><td>'.$it['request_qty'].'</td><td>'.$product_stock[$key]['stock'].'</td><td><button class="btn btn-xs btn-primary" onclick="update_aloacted_qty('.$it['odri_id'].')"><i class="fa fa-pencil-square-o"></i></button></td></tr>';
	                       }else{
                            continue;
                            }
                        }
	            }
	            $complete_table=$table_start.$table_body.$table_end;
                $row[]               = date("Y-m-d", strtotime($products->added_date_time));
                $row[]               = $products->odr_ref_no;
                $row[]               = $products->cus_code;
                $row[]               = $products->cus_name;
                $row[]               = $complete_table;
               
                $actdes = '';
                if($order_status==1){
                    $check_box='<div class="form-check text-center"><br>
  <input class="form-check-input" type="checkbox" id="check_'.$products->odr_id.'" name="order[]" value="'.$products->odr_id.'" checked>
  
</div>';
                }else{
                    $check_box='<br>';
                }
                $order_priority='custom';
                if($products->odr_priority==1){
                   $order_priority='High';
                }
                if($products->odr_priority==5){
                   $order_priority='Default';
                }
                if($products->odr_priority==10){
                   $order_priority='Low';
                }
                
             
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            
                            <li><a style="cursor: pointer;" onclick="set_priority('. $products->odr_id .',1)"><i class="glyphicon fa fa-level-up"></i> SET PRIORITY HIGH</a></li>
                             <li><a style="cursor: pointer;" onclick="set_priority('. $products->odr_id .',5)"><i class="glyphicon fa fa-medium"></i> SET PRIORITY DEFAULT</a></li>
                              <li><a style="cursor: pointer;" onclick="set_priority('. $products->odr_id .',10)"><i class="glyphicon fa fa-level-down"></i> SET PRIORITY LOW </a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->odr_id .')"><i class="glyphicon fa fa-ban"></i> REJECT ORDER</a></li>
                            </ul>  </div>'.$check_box.'<br> PRIORITY <br>'.$order_priority;
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	
	
	public function update_order_product_qty(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'trim|required|xss_clean');
		$this->form_validation->set_rules('result', 'QTY ', 'trim|required|greater_than[-1]|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $id=$this->input->post('id');
	    	$result=$this->input->post('result');
	    	
	    	$batch_validation=$this->Order_Model->check_batch_validation($id);
	    	if($batch_validation>0){
	    	   $max_qty= $this->Order_Model->get_order_approved_qty($id);
	    	   if($max_qty<$result){
	    	      $st = array('status' =>0,'validation' =>'Cannot Exceed Already Reserved Quantity! ');
                  echo json_encode($st); 
                  return;
	    	   }
	    	}
	    	
            $data=array(
			'request_qty'=>$result,
		);	
         $result=$this->Order_Model->update_order_item($id,$data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	
		public function set_priority(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'trim|required|xss_clean');
		$this->form_validation->set_rules('status', 'STATUS', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $id=$this->input->post('id');
	    	$result=$this->input->post('status');
            $data=array(
			'odr_priority'=>$result,
		);	
         $result=$this->Order_Model->update_order_master($id,$data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	
     public function save_order_plan()
    {
		$this->load->library('form_validation');	
		$this->form_validation->set_rules('order', 'ORDER', 'required');
	
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        $order=$this->input->post('order');
        $data=array(
			'opm_ref_no'=>$this->Common_Model->gen_ref_number('opm_id','order_plan_master','OPM'),
			'added_user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);	
          $last_id = $this->Order_Model->save_order_plan($data);
          foreach($order as $o){
            $data=array(
			'opm_id'=>$last_id,
			'order_id'=>$o
		);	
          $this->Order_Model->save_order_plan_item($data);   
          }
          
          foreach($order as $o){
            $data=array(
			'pickup_status'=>1,
			'pickup_by'=>$this->session->userdata('ss_user_id'),
			'pickup_date_time'=>date("Y-m-d H:i:s"),
			
		);	
          $this->Order_Model->update_order_master($o,$data);   
          }
         $st = array('status' =>1,'validation' => 'SAVED');
           echo json_encode($st);
		}
	}	
	
	 function order_plan_approval(){
	    $data['main_menu_name'] = 'management';
		$data['sub_menu_name'] = 'order_plan_approval';
	    $this->load->view('management/order_plan_approval_list',$data);
	}
	
	
	public function get_order_plan_approval_list($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Order_Model->get_order_plan_list($start, $length, $search_key_val);
        $value_count    = $this->Order_Model->get_order_plan_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Order_Model->get_order_plan_list('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                
                $row[]               = $products->added_date_time;
                $row[]               = $products->opm_ref_no;
                $row[]               = $products->mas_name;
                $row[]               = $products->added_user_first_name." ".$products->added_user_last_name;
                $row[]               = $products->approval_user_first_name." ".$products->approval_user_last_name;
                $row[]               = $products->approval_date_time;//$products->brm_note;
                $actdes = '';
                
                
             
                   $update_action='<li><a href="' . base_url('order_administration/order_panning_managemet') . '?id=' . $products->opm_id . '"><i class="fa fa-pencil-square-o"></i> VIEW AND APPROVAL</a></li>';
              
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            '.$update_action.'
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->opm_id .')"><i class="glyphicon fa fa-check"></i> APPROVAL</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->opm_id .')"><i class="glyphicon fa fa-ban"></i> REJECT</a></li>-->
                            ';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	
	
	 function order_panning_managemet(){
        
	    $data['main_menu_name'] = 'management';
		$data['sub_menu_name']  = 'order_plan_approval';
		$data['id']             =$this->input->get('id'); 
		$data['details'] =$this->Order_Model->get_order_plan_details($this->input->get('id'));
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['order_type_list'] = $this->Order_Model->get_order_type();
	    $this->load->view('administration/order/order_planning_managemnt',$data);
	}
	
	
		public function get_order_aproved_pickup_list(){
		$id=$this->input->get('id');    
		    
        $values = $this->Order_Model->get_order_approved_completed_pickup_list($id);
        $item_list = $this->Order_Model->get_order_approved_completed_pickup_item_list($id);
        $data          = array();
        if (!empty($values)) {
           
            foreach ($values as $products) {
                $row=array();
                $order_status=1;
               
               
                $table_start='<table  class="table" id="tbl_'.$products->odr_id.'">';
	            $table_head_start='<thead >';
	            $table_head_end='</thead>';
	            $table_end='</table>';
	            $table_body=' <tr><th>PD CODE </th><th>PD NAME </th><th data-toggle="tooltip" data-placement="top" title="UNIT OF MEASUREMENTS">UOM</th><th data-toggle="tooltip" data-placement="top" title="APPROVED QUANTITY">A.QTY</th><th data-toggle="tooltip" data-placement="top" title="REQUIRED QUANTITY">R.QTY</th></tr>';
	            
	            
	            foreach($item_list as $it){
	                $order_item_status=1;
	                
	                if($it['odr_id']!=$products->odr_id){
	                   continue; 
	                }
	                
	            $table_body.='<tr><td>'.$it['product_code'].'</td><td>'.$it['product_name'].'</td><td>'.$it['unit_code'].'</td><td>'.$it['approved_qty'].'</td><td>'.$it['request_qty'].'</td></tr>';
	                
	           
	            }
	            $complete_table=$table_start.$table_body.$table_end;
                $row[]               = date("Y-m-d", strtotime($products->added_date_time));
                $row[]               = $products->odr_ref_no;
                $row[]               = $products->cus_code;
                $row[]               = $products->cus_name;
                $row[]               = $complete_table;
               
             
                $actdes='';
                $order_priority='custom';
                if($products->odr_priority==1){
                   $order_priority='High';
                }
                if($products->odr_priority==5){
                   $order_priority='Default';
                }
                if($products->odr_priority==10){
                   $order_priority='Low';
                }
            
             
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a style="cursor: pointer;" onclick="remove_from_list('. $products->odr_id .')"><i class="glyphicon fa fa-ban"></i> REMOVE FROM PLAN</a></li>
                            </ul>  </div><br> <br> PRIORITY <br>'.$order_priority;
                            
                if($products->opm_approval_status==1){
                $actdes='PRIORITY : '.$order_priority;
            }
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	
	public function remove_planed_item(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $id=$this->input->post('id');
            $data=array(
			'pickup_status'=>0,
		);	
         $result=$this->Order_Model->update_order_master($id,$data);
         $result=$this->Order_Model->delete_order_plan_item($id,$data);
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	
		public function approval_order_plan(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $id=$this->input->post('id');
            $data=array(
			'opm_approval_status'=>1,
			'approval_by'=>$this->session->userdata('ss_user_id'),
			'approval_date_time'=>date("Y-m-d H:i:s"),
		);	
         $result=$this->Order_Model->update_order_plan_master($id,$data);
         $order_list=$this->Order_Model->get_planned_order_list($id);
         
         foreach($order_list as $ol){
        //------------------------------------all planed order foreach 
           $data=array(
             'order_id'=>$ol['odr_id'],
			'dpn_warehouse_id'=>$ol['odr_warehouse_id'],
			'dpn_sale_rep_id'=>$ol['odr_sale_rep_id'],
			'dpn_customer_id'=>$ol['odr_customer_id'],
			'dpn_manual_ref_no'=>$ol['odr_manual_ref_no'],
			'dpn_note'=>$ol['odr_note'],	
			'dpn_type_id'=>$ol['odr_type_id'],
			'dpn_price_type_id'=>$ol['price_type_id'],
			'dpn_ref_no'=>$this->Common_Model->gen_ref_number('dpn_id','dispatch_note_master','INV'),
			'added_user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);  
		$last_id=$this->Order_Model->save_dispach_note($data);
		$order_item_list=$this->Order_Model->get_planned_order_item_list($ol['odr_id']);
		$total_waight=0;
		$total_cost=0;
		$total_price=0;
		foreach($order_item_list as $oil){
		    if($oil['request_qty']<=0){
		        continue;
		    }
		 $price=0;
	    	if($oil['price_type_id']==1){
	    	   $price= $oil['product_price'];
	    	}
	    	if($oil['price_type_id']==2){
	    	   $price= $oil['credit_salling_price'];
	    	}
	    	if($oil['price_type_id']==3){
	    	   $price= $oil['wholesale_price'];
	    	}
	    	$cost= $oil['product_cost'];
	    	
	    	if($oil['price_important']==1){
	    	    $price=$oil['uom_price'];
	    	}
	    	$total_waight+=$oil['product_weight']*$oil['request_qty'];
	    	$total_price+=$price*$oil['request_qty'];
	    	$total_cost+=$price*$oil['request_qty'];
            $data=array(
            'dnm_id'=>$last_id,
			'odri_id'=>$oil['odri_id'],
			'product_id'=>$oil['product_id'],
			'issued_qty'=>$oil['request_qty'],	
			'uom_price'=>$price,
			'uom_cost'=>$cost,
			'total_price'=>$price*$oil['request_qty'],
			'total_cost'=>$cost*$oil['request_qty'],
			'price_important'=>$oil['price_important'],
			'total_weight'=>$oil['product_weight']*$oil['request_qty'],
			'batch_id'=>$oil['batch_id'],
			'is_batch_validate'=>$oil['is_batch_validate'],
		);	
		$this->Order_Model->save_dispach_note_item($data);
		}
		$charge = $this->Order_Model->get_loading_unloading_charge();
		$loading_unloading_charge=($total_waight/$charge['unit_qty'])*$charge['charge'];
		$data=array(
		    'dpn_total_weight'=>$total_waight,
		    'total_dpn_cost'=>$total_price,
		    'total_dpn_price'=>$total_cost,
		    'loading_unloading_charge'=>$loading_unloading_charge,
		    'total_dpn_value'=>$total_price+$loading_unloading_charge
		    );
		$this->Order_Model->update_dispatch_note($last_id,$data);
		
          //------------------------------------all planed order foreach   
         }
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}

    



























	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function get_customer_dynamic(){
        $str = $this->input->post('search_string');
		$result=$this->Customer_Model->get_customer_for_ajex($str);
        echo json_encode($result);
    }
    public function get_user_dynamic(){
        $str = $this->input->post('search_string');
		$result=$this->User_Model->get_user_for_ajex($str,4);
        echo json_encode($result);
    }
    public function save_order_master()
    {
		$this->load->library('form_validation');	
		$this->form_validation->set_rules('warehouse_id', 'WAREHOUSE', 'required|xss_clean');
		$this->form_validation->set_rules('sale_rep_id', 'SALES REPRESENTATIVE', 'required|xss_clean');
		$this->form_validation->set_rules('customer_id', 'CUSTOMER', 'required|xss_clean');
		$this->form_validation->set_rules('ref_no', 'Ref No', 'xss_clean');
		$this->form_validation->set_rules('odr_type', 'ORDER TYPE', 'required|xss_clean');
		$this->form_validation->set_rules('note', 'Quntity', 'max_length[500]|xss_clean');
		$this->form_validation->set_rules('odr_price_type_id', 'PRICE TYPE', 'required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        $warehouse_id=$this->input->post('warehouse_id');
		$sale_rep_id=$this->input->post('sale_rep_id');
		$customer_id=$this->input->post('customer_id');
		$odr_price_type_id=$this->input->post('odr_price_type_id');
		$ref_no=$this->input->post('ref_no');
		$note=$this->input->post('note');
		$odr_type=$this->input->post('odr_type');
        $data=array(
			'odr_warehouse_id'=>$warehouse_id,
			'odr_sale_rep_id'=>$sale_rep_id,
			'odr_customer_id'=>$customer_id,
			'odr_manual_ref_no'=>$ref_no,
			'odr_note'=>$note,	
			'odr_type_id'=>$odr_type,
			'price_type_id'=>$odr_price_type_id,
			'odr_ref_no'=>$this->Common_Model->gen_ref_number('odr_id','order_master','ODR'),
			'added_user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);	
          $result = $this->Order_Model->save_order($data);
        $status=0;
        if($result>0){
           $status=1; 
        }
        $retun_data=array(
            'result'=>$result,
            'status'=>$status,
            );
        echo json_encode($retun_data);
		}
	}
	function add_order_items(){
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['odr_id'] =$this->input->get('id');
		$data['details']=$this->Order_Model->get_order_info($data['odr_id']);
	    $this->load->view('order/add_order_items',$data);
	}
	
	public function get_product_dynamic(){
        $str = $this->input->post('search_string');
		$result=$this->Product_Models->get_search_products($str);
        echo json_encode($result);
    }
    
    public function get_order_price_type_dynamic(){
        $str = $this->input->post('search_string');
        $odr_type = $this->input->post('order_type');
        if(!$odr_type){
            $odr_type=0;
        }
		$result=$this->Order_Model->get_search_order_price_type($str,$odr_type);
        echo json_encode($result);
    }
	

	
	public function save_order_item(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('product_id', 'Product', 'trim|required|xss_clean');
		$this->form_validation->set_rules('odr_id', 'Main ', 'trim|required|xss_clean');
		$this->form_validation->set_rules('req_qty', 'Quntity', 'trim|required|greater_than[0]|xss_clean');
		$this->form_validation->set_rules('price_type', 'Price type', 'trim|required|greater_than[0]|xss_clean');
		
		
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $product_id=$this->input->post('product_id');
	    	$odr_id=$this->input->post('odr_id');
	    	$req_qty=$this->input->post('req_qty');
	    	$price_type=$this->input->post('price_type');
	    	$price_important=$this->input->post('price_important');
	    	$price_cost=$this->Order_Model->get_order_product_price_cost($product_id);
	    	
	    	$price=0;
	    	if($price_type==1){
	    	   $price= $price_cost['product_price'];
	    	}
	    	if($price_type==2){
	    	   $price= $price_cost['credit_salling_price'];
	    	}
	    	if($price_type==3){
	    	   $price= $price_cost['wholesale_price'];
	    	}
	    	$cost= $price_cost['product_cost'];
	    	
            $data=array(
			'odr_id'=>$odr_id,
			'product_id'=>$product_id,
			'request_qty'=>$req_qty,	
			'approved_qty'=>$req_qty,
			'uom_price'=>$price,
			'uom_cost'=>$cost,
			'total_price'=>$price*$req_qty,
			'total_cost'=>$cost*$req_qty,
			'price_important'=>$price_important,
		);	
         $result=$this->Order_Model->save_order_item($data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	
		public function get_order_item_list() {
        $id=$this->input->get('id');
        $values = $this->Order_Model->get_order_product_list($id);
        $totalData=count($values);
        $totalFiltered=$totalData;
         $data          = array();
	    foreach ($values as $row) {
	        if($row['price_important']==1){
	         $update_price='<button type="button" class="btn btn-warning btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit Product Price" onClick="update_product_price('.$row['odri_id'].','.$row['request_qty'].')" ><i class="fa fa-pencil-square-o" aria-hidden="true"> EDIT</i></button>';
	       }else{
	           $update_price='';
	       }
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	       
	        $nestad_data[]  = $row['unit_code'];
	        //$nestad_data[]  = $row['uom_cost'];
	        
	        $nestad_data[]  = $row['uom_price']." ".$update_price;
	        $nestad_data[]  = $row['request_qty'];
	       $nestad_data[]  =$row['total_price'];
	       
	       
	     $action='
	     <button type="button" class="btn btn-primary btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit Quantity" onClick="update_aloacted_qty('.$row['odri_id'].')" ><i class="fa fa-pencil-square-o" aria-hidden="true"> QTY</i></button>
	     <button type="button" class="btn btn-danger btn-xs" data-toggle="tooltip" data-placement="bottom" title="Remove This Item"  onClick="delete_item_block('.$row['odri_id'].')"><i class="fa fa-trash-o" aria-hidden="true"> REMOVE</i></button>
	     ';
	       $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
    }
    
    public function update_order_product_price(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'trim|required|xss_clean');
		$this->form_validation->set_rules('result', 'PRICE ', 'trim|required|greater_than[0]|xss_clean');
		$this->form_validation->set_rules('qty', 'QTY ', 'trim|required|greater_than[0]|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $id=$this->input->post('id');
	    	$result=$this->input->post('result');
            $qty=$this->input->post('qty');
            
            $data=array(
			'uom_price'=>$result,
			'total_price'=>$result*$qty,
		);	
         $result=$this->Order_Model->update_order_item($id,$data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	
    
    function delete_order_item(){
       	$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $id=$this->input->post('id');
             $result=$this->Order_Model->delete_order_item($id);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
        
    }
    
     function final_order(){
       	$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $id=$this->input->post('id');
             $result=$this->Order_Model->get_order_total_values($id);
             
             if($result['total_cost']==0){
                  $st = array('status' =>0,'validation' => 'ORDER IS INVALID');
                  echo json_encode($st);
                  return false;
             }
             
             $data=array(
			'total_odr_cost'=>$result['total_cost'],
			'total_odr_price'=>$result['total_price'],
	        'odr_status'=>1,
			'added_user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);
		
		$result=$this->Order_Model->update_order_master($id,$data);
             
          $st = array('status' =>1,'validation' =>'ORDER COMPLETED');
          echo json_encode($st);
		}
        
    }
    
     function list_orders(){
        
	    $data['main_menu_name'] = 'order';
		$data['sub_menu_name'] = 'list_orders';
	    $this->load->view('order/list_orders',$data);
	}
	
	public function get_order_list($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Order_Model->get_order_list($start, $length, $search_key_val);
        $value_count    = $this->Order_Model->get_order_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Order_Model->get_order_list('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $status='<span class=" btn btn-xs btn-primary"> DRAFT</sapn>';
                if($products->odr_status==1){
                   $status='<span class=" btn btn-xs btn-success"> COMPLETED</sapn>'; 
                }
                
                $row[]               = $products->added_date_time;
                $row[]               = $products->odr_ref_no;
                 $row[]               = $products->odr_manual_ref_no;
                $row[]               = $products->cus_code;
                $row[]               = $products->cus_name;
                $row[]               = $products->user_first_name." ".$products->user_last_name;
                $row[]               = $status;
                $row[]               = $products->mas_name;
                
                $row[]               = $products->approval_user_first_name." ".$products->approval_user_last_name;
                $row[]               = $products->approval_date_time;//$products->brm_note;
                $actdes = '';
                
                
              if($products->odr_approval_status==0){
                   $update_action='<li><a href="' . base_url('order/add_order_items') . '?id=' . $products->odr_id . '"><i class="fa fa-pencil-square-o"></i> UPDATE</a></li>';
                }else{
                    $update_action='';
                }
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            '.$update_action.'
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->odr_id .')"><i class="glyphicon fa fa-check"></i> APPROVAL</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->odr_id .')"><i class="glyphicon fa fa-ban"></i> REJECT</a></li>-->
                            ';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    
     function approval_orders(){
        
	    $data['main_menu_name'] = 'management';
		$data['sub_menu_name'] = 'approval_orders';
	    $this->load->view('order/approval_list_order',$data);
	}
	
		public function get_order_approval_pending_list($value = ''){
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Order_Model->get_order_approval_pending_list($start, $length, $search_key_val);
        $value_count    = $this->Order_Model->get_order_approval_pending_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Order_Model->get_order_approval_pending_list('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
     
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $status='<span class=" btn btn-xs btn-primary"> DRAFT</sapn>';
                if($products->odr_status==1){
                   $status='<span class=" btn btn-xs btn-success"> COMPLETED</sapn>'; 
                }
                
                $row[]               = $products->added_date_time;
                $row[]               = $products->odr_ref_no;
                 $row[]               = $products->odr_manual_ref_no;
                $row[]               = $products->cus_code;
                $row[]               = $products->cus_name;
                $row[]               = $products->user_first_name." ".$products->user_last_name;
                $row[]               = $status;
                $row[]               = $products->mas_name;
                
                $row[]               = $products->approval_user_first_name." ".$products->approval_user_last_name;
                $row[]               = $products->approval_date_time;//$products->brm_note;
                $actdes = '';
                
                
              if($products->odr_approval_status==0){
                   $update_action='<li><a href="' . base_url('order/add_order_items') . '?id=' . $products->odr_id . '"><i class="fa fa-pencil-square-o"></i> UPDATE</a></li>';
                }else{
                    $update_action='';
                }
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs  dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            '.$update_action.'
                            <li><a style="cursor: pointer;" onclick="approval_requste('. $products->odr_id .')"><i class="glyphicon fa fa-check"></i> APPROVAL</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->odr_id .')"><i class="glyphicon fa fa-ban"></i> REJECT</a></li>
                            ';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    
     function  grant_approval(){
       
        $this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else{
            $id= $this->input->post('id');
              $data=array(
                    'odr_approval_status'=>1,
                    'approval_by'=>$this->session->userdata('ss_user_id'),
                    'approval_date_time'=>date("Y-m-d H:i:s"),
                    );
                   $this->Order_Model->update_order_master($id,$data); 
                     $st = array('status' =>1,'validation' => 'Saved');
                echo json_encode($st);
        }
   }
   
   function  reject_approval(){
       
        $this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'ID', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else{
            $id= $this->input->post('id');
              $data=array(
                    'odr_approval_status'=>2,
                    'approval_by'=>$this->session->userdata('ss_user_id'),
                    'approval_date_time'=>date("Y-m-d H:i:s"),
                    );
                   $this->Order_Model->update_order_master($id,$data); 
                     $st = array('status' =>1,'validation' => 'Saved');
                echo json_encode($st);
        }
   }

   
  
}