<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
   
class Delivery_Administration extends CI_Controller
{
    var $main_menu_name = "delivery_administration";
    var $sub_menu_name = "delivery_administration";
    
   
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Colombo");
        $this->load->model('Common_Model');
        $this->load->model('Delivery_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 delivery_panning(){
        
	    $data['main_menu_name'] = 'administrator';
		$data['sub_menu_name'] = 'delivery_panning';
	    $this->load->view('administration/delivery/delivery_planning',$data);
	}
	
	public function get_unallocated_invoice_list($value = ''){
        $values = $this->Delivery_Model->get_all_unallocated_dispatch_list();
        $p_app_delivery = $this->Delivery_Model->get_pending_approved_delivery();
        
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->added_date_time;
                $row[]               = $products->dpn_ref_no;
                $row[]               = $products->cus_code;
                $row[]               = $products->cus_name;
               $row[]               = $products->dpn_total_weight | 0;
                $actdes = '';
                $priority='CUSTOM';
                if($products->dpn_priority==1){
                   $priority='HIGH'; 
                }
                 if($products->dpn_priority==5){
                   $priority='DEFAULT'; 
                }
                if($products->dpn_priority==10){
                   $priority='LOW'; 
                }
                $row[]               = $priority;
                 
               $vehicle_list='';
        foreach($p_app_delivery as $pad){
            $vehicle_list.='<li> <a style="cursor: pointer;" onclick="allocate_delivery('. $pad->d_id .','.$products->dpn_id.')"> <i class="fa fa-link"> </i>  Link To '.$pad->vehicle_code.'  </a></li>
            ';
        }
           $option_split='';   
           $details_action='<li><a target="_blank" href="' . base_url('dispatch/dispatch_note_details') . '?id=' . $products->dpn_id . '"><i class="fa fa-file-text-o"></i> DETAILS</a></li>'; 
           
           if($products->split_status==0 ){
                $option_split='<li> <a style="cursor: pointer;" onclick="split_delivery('.$products->dpn_id.')"> <i class="fa fa-object-ungroup"> </i> Split Dispatch Note</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">
                           '.$details_action.$vehicle_list.$option_split.'
                          
                            ';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	
		public function allocate_delivery(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('delivery_id', 'DELIVERY', 'trim|required|xss_clean');
		$this->form_validation->set_rules('dispatch_id', 'DISPATCH', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $delivery_id=$this->input->post('delivery_id');
	    	$dispatch_id=$this->input->post('dispatch_id');
            $data=array(
			'delivery_id'=>$delivery_id,
			'pickup_status'=>1,
			'pickup_by'=>$this->session->userdata('ss_user_id'),
			'pickup_date_time'=>date("Y-m-d H:i:s"),
		);	
         $result=$this->Delivery_Model->update_dispatch_master($dispatch_id,$data);	   
          $st = array('status' =>1,'validation' =>'UPDATED');
          echo json_encode($st);
		}
	}
	
	
	
	public function get_pending_appoved_delivery_with_dispatch_notes(){
        $values = $this->Delivery_Model->get_pending_approved_delivery();
      
        $product_stock=array();
        
        $data          = array();
        if (!empty($values)) {
           
            foreach ($values as $products) {
                $row=array();
              
               
               
                $table_start='<table  class="table table-hover table-responsive" id="tbl_'.$products->d_id.'">';
	            $table_head_start='<thead >';
	            $table_head_end='</thead>';
	            $table_end='</table>';
	            $table_body=' <tr><th class="col-md-1" >DISPATCH NO</th><th class="col-md-9">CUS NAME</th><th class="col-md-1">WEIGHT</th><th  data-toggle="tooltip" data-placement="top" title="REMAINING CAPACITY" class="col-md-1">R.CAPACITY</th><th></th></tr>';
	            
	            $item_list=$this->Delivery_Model->get_delivery_allocated_dispatch_notes($products->d_id);
	            $capacity=$products->capacity;
	            foreach($item_list as $it){
	           
                     $capacity-=$it['dpn_total_weight'];      
                             if($capacity<0){
                                $warning_tr='style="background-color:#FFCCCB;"';
                             }else{
                                 $warning_tr='';
                             }
                             
                              $table_body.='<tr '.$warning_tr.'><td>'.$it['dpn_ref_no'].'</td><td>'.$it['cus_name'].'</td><td>'.$it['dpn_total_weight'].'</td><td>'.$capacity.'</td><td><button class="btn btn-xs btn-danger" data-toggle="tooltip" data-placement="top" title="Unlink From Delivery" onclick="rollback_dispach_note('.$it['dpn_id'].')"><i class="fa fa-chain-broken "></i></button></td></tr>';
	                
	            }
	            
	            $capacity_remainder_presentage=round((($capacity/$products->capacity)*100));
	            $loading_presentage=(100-$capacity_remainder_presentage);
	            
	            $p_bar_class='progress-bar-info';
	            if($loading_presentage>100){
	                $p_bar_class='progress-bar-danger';
	            }
	            
	            $progress_bar='<div class="progress" style="background-color:LightGray;">
    <div class="progress-bar '.$p_bar_class.' progress-bar-striped" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:'.$loading_presentage.'%">
      '.$loading_presentage.'% Capacity 
    </div>
  </div>';
	            $complete_table=$table_start.$table_body.$table_end;
                $row[]               = $products->added_date_time;
                $row[]               = $products->d_ref_no;
                $row[]               = $products->vehicle_code;
                $row[]               = $products->capacity | 0;
                $row[]               = $complete_table.$progress_bar;
               
                $actdes = '';
               
               
                
             
                $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_currant_delivery('. $products->d_id .')"><i class="fa fa-level-up"></i> SET FOR LOADING</a></li>-->
                            <li><a href="' . base_url('delivery_administration/dispatch_delivery_allocated_map').'?id=' . $products->d_id . '" target="_blank" ><i class="fa fa-map-marker"></i> SHOW ROAD MAP</a></li>
                            </ul>';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	
	
	public function unallocate_from_delivery(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'DISPATCH', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
	    	$dispatch_id=$this->input->post('id');
            $data=array(
			'delivery_id'=>0,
			'pickup_status'=>0,
			'pickup_by'=>$this->session->userdata('ss_user_id'),
			'pickup_date_time'=>date("Y-m-d H:i:s"),
		);	
         $result=$this->Delivery_Model->update_dispatch_master($dispatch_id,$data);	  
         if($result==1){
              $data=array(
			'allocated_dispatch_note'=>0,
		);	
         $result=$this->Delivery_Model->update_return_master_by_dispatch_note_id($dispatch_id,$data);	 
         }
          $st = array('status' =>1,'validation' =>'UPDATED');
          echo json_encode($st);
		}
	}
	
	
    function dispatch_pending_allocation_map(){
        
        $data['title']='PENDING ALLOCATION'; 
        $data['place_list'] = $this->Delivery_Model->get_all_unallocated_dispatch_customer_list();
	    $data['main_menu_name'] = 'administrator';
		$data['sub_menu_name'] = 'delivery_panning';
	    $this->load->view('map/map',$data);
	}

	 function dispatch_delivery_allocated_map(){
         $id=$this->input->get('id');
         
         
         $details = $this->Delivery_Model->get_delivery_master_details($id);
        $data['title']='DELIVERY ALLOCATED ROAD MAP ( '.$details['d_ref_no'] .' : '.$details['vehicle_code'].' ) '; 
        $data['place_list'] = $this->Delivery_Model->get_all_dilivery_allocated_dispatch_customer_list($id);
	    $data['main_menu_name'] = 'administrator';
		$data['sub_menu_name'] = 'delivery_panning';
	    $this->load->view('map/map',$data);
	}
	
		public function set_currant_delivery(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'DILIVERY', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
	    	$dispatch_id=$this->input->post('id');
            $data=array(
			'd_status'=>1,
		);	
         $result=$this->Delivery_Model->update_delivery_master($dispatch_id,$data);	   
          $st = array('status' =>1,'validation' =>'UPDATED');
          echo json_encode($st);
		}
	}
	
	public function get_pending_appoved_delivery_with_dispatch_customer_list(){
        $values = $this->Delivery_Model->get_pending_approved_delivery();
      
        $product_stock=array();
        
        $data          = array();
        if (!empty($values)) {
           
            foreach ($values as $products) {
                $row=array();
              
               
               
                $table_start='<table  class="table" id="tbl_'.$products->d_id.'">';
	            $table_head_start='<thead >';
	            $table_head_end='</thead>';
	            $table_end='</table>';
	            $table_body=' <tr><th  class="col-md-1" >CUS CODE</th><th class="col-md-3" >CUS NAME</th><th class="col-md-6"  >ADDRESS</th><th class="col-md-1">MAP LETTER</th><th class="col-md-1" data-toggle="tooltip" data-placement="top" title="DELIVERY PRIORITY">PRIORITY</th></tr>';
	            
	            $customer_list=$this->Delivery_Model->get_delivery_allocated_dispatch_customer_list($products->d_id);
	            $map_letter='A';
	            foreach($customer_list as $it){
	                $capacity=' <input required type="number" name="priority_input" value="'.$it['dpn_priority'].'" onchange="set_priority('.$it['delivery_id'].','.$it['dpn_customer_id'].',this.value)" >';
                              $table_body.='<tr><td>'.$it['cus_code'].'</td><td>'.$it['cus_name'].'</td><td>'.$it['cus_address'].'</td><td>'.$map_letter.'</td><td>'.$capacity.'</td></tr>';
	             $map_letter++;   
	            }
	            $complete_table=$table_start.$table_body.$table_end;
                $row[]               = $products->d_ref_no;
                $row[]               = $products->vehicle_code;
                $row[]               = $complete_table;
               
                $actdes = '';
               
               
                
             
                $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_currant_delivery('. $products->d_id .')"><i class="fa fa-send-o"></i> SEND TO LOADING</a></li>
                            <li><a href="' . base_url('delivery_administration/dispatch_delivery_allocated_map').'?id=' . $products->d_id . '" target="_blank" ><i class="fa fa-map-marker"></i> SHOW ROAD MAP</a></li>
                         
                            </ul>';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	
	
	
		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('cus_id', 'CUSTOMER', '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');
	    	$cus_id=$this->input->post('cus_id');
            $data=array(
			'dpn_priority'=>$result,
		);	
          $result=$this->Delivery_Model->update_dispath_priority($id,$cus_id,$data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	}
	
	
	public function get_return_list($value = ''){
        $values         = $this->Delivery_Model->get_return_list_for_currant_delivery();
        $return_list         = $this->Delivery_Model->get_approved_return_note_for_currant_delivery();
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->added_date_time;
                $row[]               = $products->rtn_ref_no;
                $row[]               = $products->rtn_manual_ref_no;
                $row[]               = $products->m_rtn_type_name;
                $row[]               = $products->cus_code;
                $row[]               = $products->cus_name;
                $row[]               = $products->return_note_amount;
                $row[]               = $products->mas_name;
                $actdes = '';
                
                
                 $option_return_note=''; 
                foreach($return_list as $r){
                   $option_return_note.='<li><a style="cursor: pointer;" onclick="set_delivery_note('. $products->rtn_id .','.$r->dpn_id.')"><i class="glyphicon fa fa-paperclip"> </i> ATTACH TO '.$r->dpn_ref_no.'</a></li>'; 
                }
                
                
                $option_order_details='<li><a target="_blank" href="' . base_url('invoice_return/return_details') .'?id=' . $products->rtn_id . '"><i class="fa fa-file-text-o"></i> DETAILS</a></li>';
                $action_option=$option_order_details.$option_return_note;
                $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">
                            '.$action_option.'</ul></div>                      ';
                $row[]               = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
               
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => $data=array(),
            );
            echo json_encode($output);
        }
    }
	
	public function set_delivery_note(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'RETURN NOTE', 'trim|required|xss_clean');
		$this->form_validation->set_rules('dispatch_id', 'DISPATCH NOTE', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $return_id=$this->input->post('id');
	    	$dispatch_id=$this->input->post('dispatch_id');
            $data=array(
			'allocated_dispatch_note'=>$dispatch_id,
		);	
         $result=$this->Delivery_Model->update_return_master($return_id,$data);	   
          $st = array('status' =>1,'validation' =>'UPDATED');
          echo json_encode($st);
		}
	}
	
		public function split_dispatch_note(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'DISPATCH NOTE', 'trim|required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $dispatch_id=$this->input->post('id');
	        $master=$this->Delivery_Model->get_dispatch_note_data($dispatch_id);
	        $item=$this->Delivery_Model->get_dispatch_note_item_data($dispatch_id);
	        $data=array(
			'dpn_id'=>$master['dpn_id'],
		    'order_id'=>$master['order_id'],
		    'dpn_ref_no'=>$master['dpn_ref_no'],
		    'dpn_manual_ref_no'=>$master['dpn_manual_ref_no'],
		    'dpn_warehouse_id'=>$master['dpn_warehouse_id'],
		    'added_user_id'=>$master['added_user_id'],
		    'added_date_time'=>$master['added_date_time'],
		    'total_dpn_cost'=>$master['total_dpn_cost'],
		    'pickup_status'=>$master['pickup_status'],
		    'pickup_by'=>$master['pickup_by'],
		    'pickup_date_time'=>$master['pickup_date_time'],
		    'dpn_note'=>$master['dpn_note'],
		    'is_deleted'=>$master['is_deleted'],
		    'dpn_customer_id'=>$master['dpn_customer_id'],
		    'dpn_sale_rep_id'=>$master['dpn_sale_rep_id'],
		    'dpn_type_id'=>$master['dpn_type_id'],
		    'dpn_price_type_id'=>$master['dpn_price_type_id'],
		    'total_dpn_price'=>$master['total_dpn_price'],
		    'dpn_status'=>$master['dpn_status'],
		    'dpn_priority'=>$master['dpn_priority'],
		    'dpn_total_weight'=>$master['dpn_total_weight'],
		    'loading_unloading_charge'=>$master['loading_unloading_charge'],
		    'total_dpn_value'=>$master['total_dpn_value'],
		    'delivery_id'=>$master['delivery_id']
		    );	
	      $last_id=$this->Delivery_Model->save_splitted_master($data);	
	      
	    foreach($item as $it){
	         $data=array(
	           'dni_id'=>$it['dni_id'],
	           'dnm_id'=>$it['dnm_id'],
	           'product_id'=>$it['product_id'],
	           'issued_qty'=>$it['issued_qty'],
	           'is_deleted'=>$it['is_deleted'],
	           'dni_status'=>$it['dni_status'],
	           'uom_price'=>$it['uom_price'],
	           'uom_cost'=>$it['uom_cost'],
	           'total_price'=>$it['total_price'],
	           'total_cost'=>$it['total_cost'],
	           'price_important'=>$it['price_important'],
	           'odri_id'=>$it['odri_id'],
	           'total_weight'=>$it['total_weight'],
	           'batch_id'=>$it['batch_id'],
	           'sdnm_id'=>$last_id,
	           'is_batch_validate'=>$it['is_batch_validate']
	           );
	           $result=$this->Delivery_Model->save_splitted_item($data);
	    }
	     $data=array(
	       'dpn_status'=>0,
	       'split_status'=>1,
	       'split_by'=>$this->session->userdata('ss_user_id'),
		   'split_on'=>date("Y-m-d H:i:s"),
	       );
	      $result=$this->Delivery_Model->update_dispatch_master($dispatch_id,$data);
	    $message='DONE';
	    if($result==0){
	       $message ='EROOR!';
	    }
          $st = array('status' =>$result,'validation' =>$message);
          echo json_encode($st);
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		
	
	

   
  
}