<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
   
class Delivery extends CI_Controller
{
    var $main_menu_name = "price_management";
    var $sub_menu_name = "price_management";
    private $main_model;
   
    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 new_delivery(){
        
	    $data['main_menu_name'] = 'delivery';
		$data['sub_menu_name'] = 'new_delivery';
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
	    $this->load->view('delivery/add_new_delivery',$data);
	}
	
	 public function get_user_dynamic(){
        $str = $this->input->post('search_string');
		$result=$this->User_Model->get_user_for_ajex($str,7);
        echo json_encode($result);
    }
	public function get_vehicle_dynamic(){
        $str = $this->input->post('search_string');
		$result=$this->Delivery_Model->get_search_vehicle($str);
        echo json_encode($result);
    }
	
	public function save_delivery_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('ref_no', 'Ref No', 'xss_clean');
		$this->form_validation->set_rules('note', 'NOTE', 'max_length[500]|xss_clean');
		$this->form_validation->set_rules('odr_price_type_id', 'VEHICLE', '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');
		$odr_price_type_id=$this->input->post('odr_price_type_id');
		$ref_no=$this->input->post('ref_no');
		$note=$this->input->post('note');
        $data=array(
			'd_warehouse_id'=>$warehouse_id,
			'driver_id'=>$sale_rep_id,
			'document_no'=>$ref_no,
			'd_note'=>$note,	
			'vehicle_id'=>$odr_price_type_id,
			'd_ref_no'=>$this->Common_Model->gen_ref_number('d_id','delivery_master','LAD'),
			'added_user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);	
          $result = $this->Delivery_Model->save_delivery($data);
        $status=0;
        if($result>0){
           $status=1; 
        }
        $retun_data=array(
            'result'=>$result,
            'status'=>$status,
            );
        echo json_encode($retun_data);
		}
	}
	
	 function list_pending_delivery(){
	    $data['main_menu_name'] = 'delivery';
		$data['sub_menu_name'] = 'list_pending_delivery';
	    $this->load->view('delivery/list_delivery_pending',$data);
	}
	
		public function get_pending_delivery_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->Delivery_Model->get_pending_delivery_list($start, $length, $search_key_val);
        $value_count    = $this->Delivery_Model->get_pending_delivery_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Delivery_Model->get_pending_delivery_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-warning"> PENDING</sapn>';
                if($products->d_status==1){
                   $status='<span class=" btn btn-xs btn-success"> COMPLETED</sapn>'; 
                }
                $row[]               = $products->added_date_time;
                $row[]               = $products->d_ref_no;
                $row[]               = $products->document_no;
                $row[]               = $products->vehicle_code;
                $row[]               = $products->capacity;
                $row[]               = $products->user_first_name." ".$products->user_last_name;
                $row[]               = $products->ds_name;
                $row[]               = $products->mas_name;
                $row[]               = $products->approval_user_first_name." ".$products->approval_user_last_name;
                $row[]               = $products->approval_date_time;//$products->brm_note;
                $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 href="' . base_url('delivery/delivery_details') . '?id=' . $products->d_id . '"><i class="fa fa-pencil-square-o"></i> View & Load</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>
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->d_id .')"><i class="glyphicon fa fa-check"></i> Approval</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->d_id .')"><i class="glyphicon fa fa-ban"></i> Reject</a></li>-->
                            </ui>
                            </div>
                            ';
                $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 list_currant_delivery(){
        
	    $data['main_menu_name'] = 'delivery';
		$data['sub_menu_name'] = 'list_currant_delivery';
	    $this->load->view('delivery/list_delivery_currant',$data);
	}
	public function get_currant_delivery_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->Delivery_Model->get_currant_delivery_list($start, $length, $search_key_val);
        $value_count    = $this->Delivery_Model->get_currant_delivery_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Delivery_Model->get_currant_delivery_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-warning"> PENDING</sapn>';
                if($products->d_status==1){
                   $status='<span class=" btn btn-xs btn-success"> COMPLETED</sapn>'; 
                }
                $row[]               = $products->added_date_time;
                $row[]               = $products->d_ref_no;
                $row[]               = $products->document_no;
                $row[]               = $products->vehicle_code;
                $row[]               = $products->capacity;
                $row[]               = $products->user_first_name." ".$products->user_last_name;
                $row[]               = $products->ds_name;
                $row[]               = $products->mas_name;
                $row[]               = $products->approval_user_first_name." ".$products->approval_user_last_name;
                $row[]               = $products->approval_date_time;//$products->brm_note;
                $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 href="' . base_url('delivery/delivery_details') . '?id=' . $products->d_id . '"><i class="fa fa-pencil-square-o"></i> DETAILS</a></li>
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->d_id .')"><i class="glyphicon fa fa-check"></i> APPROVAL</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->d_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 delivery_details(){
        $id = $this->input->get('id');
        $data['details'] = $this->Delivery_Model->get_delivery_master_details($id);
        $data['dispatch_note_list'] = $this->Delivery_Model->get_delivery_allocated_dispatch_notes($id);
        $data['product_list'] = $this->Delivery_Model->get_delivery_allocated_dispatch_note_product($id);
        $data['return_note_list'] = $this->Delivery_Model->get_return_list_for_delivery_id($id);
	    $data['main_menu_name'] = 'delivery';
		$data['sub_menu_name'] = 'delivery_details';
	    $this->load->view('delivery/delivery_details',$data);
	}
	function list_loading_sheet(){
        
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_loading_sheet';
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
	    $this->load->view('warehouse/list_loading_sheet',$data);
	}
	function loding_sheet(){
        $id = $this->input->get('id');
        $data['details'] = $this->Delivery_Model->get_delivery_master_details($id);
        $data['dispatch_note_list'] = $this->Delivery_Model->get_delivery_allocated_dispatch_notes($id);
        $data['product_list'] = $this->Delivery_Model->get_delivery_allocated_dispatch_note_product($id);
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_loading_sheet';
	    $this->load->view('delivery/delivery_details',$data);
	}
    public function auto_issue_batch_items(){
        $delivery_id = $this->input->post('id');
        $product_list= $this->Delivery_Model->get_all_product_id_relevnt_delivery($delivery_id);
        $product_stock_availibility=1;
         foreach($product_list as $pl){
	        $stock=$this->Stock_Counter_Model->get_actual_stock_balance($pl['dpn_warehouse_id'],$pl['product_id']);
	        if($pl['req_qty']>$stock){
	            $product_stock_availibility=0;
	        }
	     }
        if($product_stock_availibility==0){
            $message="STOCK PROBLEM FOUND";
           $st = array('status' =>0,'validation' => $message);
           echo json_encode($st);
            return ;
        }
        $batch_list= $this->Delivery_Model->get_all_batch_id_relevnt_delivery($delivery_id);
        $product_batch_stock=array();
        foreach($batch_list as $bl){
	        $stock=$this->Stock_Counter_Model->get_actual_stock_balance($bl['dpn_warehouse_id'],$bl['product_id'],$bl['batch_id']); 
	        $nested_data=array(
	            'product_id'=>$bl['product_id'],
	            'batch_id'=>$bl['batch_id'],
	            'batch_ref_number'=>$bl['batch_ref_number'],
	            'product_cost'=>$bl['product_cost'],
	            'product_price'=>$bl['product_price'],
	            'credit_salling_price'=>$bl['credit_salling_price'],
	            'wholesale_price'=>$bl['wholesale_price'],
	            'stock'=>$stock,
	            );
	            $product_batch_stock[]=$nested_data;
	    }
	    
	    $dispatch_list= $this->Delivery_Model->get_all_dispatch_note_item_list_relevnt_delivery($delivery_id);
	    
	    foreach($dispatch_list as $dl){
	        
	       // echo "Product ID : ".$dl['product_id'].", REQUIRED : ".$dl['issued_qty'];
	        $required_quantity=$dl['issued_qty'];
	         foreach($product_batch_stock as $key => $value){
                            if($value['product_id']==$dl['product_id']){
                                
                                if($value['stock']<=0){
                                    continue;
                                }
                                $allcated_batch_qty=0;
                                if($required_quantity>$value['stock']){
                                    $allcated_batch_qty=$value['stock'];
                                    $required_quantity-=$allcated_batch_qty;
                                }else{
                                     $allcated_batch_qty=$required_quantity;
                                     $required_quantity-=$allcated_batch_qty;
                                }
                                $product_batch_stock[$key]['stock'] = $value['stock']-$allcated_batch_qty;
                                $cc_stock=$value['stock']-$allcated_batch_qty;
                                if($dl['is_batch_validate']==1){
                                    if($dl['batch_id']==$value['batch_id']){
                                    $data=array(
                                        'dni_id'=>$dl['dni_id'],
                                        'batch_id'=>$dl['batch_id'],
                                        'product_id'=>$dl['product_id'],   
                                        'batch_qty'=>$dl['issued_qty'],
                                        'batch_uom_cost'=>$value['product_cost'],
                                        'total_cost'=>$value['product_cost']*$dl['issued_qty'],
                                        'batch_validate'=>1
                                        );
                                        $this->Delivery_Model->save_dispatch_batch_issue_item($data);
                                    }
                                }else{
                                     $data=array(
                                        'dni_id'=>$dl['dni_id'],
                                        'product_id'=>$dl['product_id'], 
                                        'batch_id'=>$value['batch_id'],
                                        'batch_qty'=>$allcated_batch_qty,
                                        'batch_uom_cost'=>$value['product_cost'],
                                        'total_cost'=>$value['product_cost']*$allcated_batch_qty,
                                        );
                                        $this->Delivery_Model->save_dispatch_batch_issue_item($data);
                                }
                                //echo "<br>".$value['batch_ref_number'].", AVAILBLE : ". $value['stock'].", ALLOCATED : ".$allcated_batch_qty.", CARRY FORWORD STOCK : ".$cc_stock;
                            }
                        }
                        
                        
                        $mdata=array(
                            'issue_status'=>1,
                            'issue_by'=>$this->session->userdata('ss_user_id'),
			                'issue_on'=>date("Y-m-d H:i:s"),
                            );
                            $this->Delivery_Model->update_dispatch_note_item($dl['dni_id'],$mdata);
                        
                        
                        
                        
	       // echo "<hr>";
	    }
	    
	     $mdata=array('d_status'=>2 );
        $this->Delivery_Model->update_delivery_master($delivery_id,$mdata);
         $st = array('status' =>1,'validation' => 'ISSUED');
           echo json_encode($st);
    }


    function list_pending_approval_delivery(){
	    $data['main_menu_name'] = 'delivery';
		$data['sub_menu_name'] = 'list_pending_approval_delivery';
	    $this->load->view('delivery/list_delivery_pending_approval',$data);
	}
	
		public function get_pending_approval_delivery_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->Delivery_Model->get_pending_delivery_list($start, $length, $search_key_val);
        $value_count    = $this->Delivery_Model->get_pending_delivery_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Delivery_Model->get_pending_delivery_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-warning"> PENDING</sapn>';
                if($products->d_status==1){
                   $status='<span class=" btn btn-xs btn-success"> COMPLETED</sapn>'; 
                }
                $row[]               = $products->added_date_time;
                $row[]               = $products->d_ref_no;
                $row[]               = $products->document_no;
                $row[]               = $products->vehicle_code;
                $row[]               = $products->capacity;
                $row[]               = $products->user_first_name." ".$products->user_last_name;
                $row[]               = $products->ds_name;
                $row[]               = $products->mas_name;
                $row[]               = $products->approval_user_first_name." ".$products->approval_user_last_name;
                $row[]               = $products->approval_date_time;//$products->brm_note;
                $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 href="' . base_url('delivery/delivery_details') . '?id=' . $products->d_id . '"><i class="fa fa-pencil-square-o"></i> View & Load</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>
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->d_id .')"><i class="glyphicon fa fa-check"></i> Approval</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->d_id .')"><i class="glyphicon fa fa-ban"></i> Reject</a></li>-->
                            </ui>
                            </div>
                            ';
                $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 loding_sheet_print(){
        $id = $this->input->get('id');
        $data['details'] = $this->Delivery_Model->get_delivery_master_details($id);
        $data['dispatch_note_list'] = $this->Delivery_Model->get_delivery_allocated_dispatch_notes($id);
        $data['product_list'] = $this->Delivery_Model->get_delivery_dispatch_note_item($id);
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_loading_sheet';
	    $this->load->view('delivery/print_loading_sheet',$data);
    }
    function delivery_sheet_print(){
        $id = $this->input->get('id');
        $data['details'] = $this->Delivery_Model->get_delivery_master_details($id);
        $data['dispatch_note_list'] = $this->Delivery_Model->get_delivery_allocated_dispatch_notes_asc_order($id);
        $data['product_list'] = $this->Delivery_Model->get_delivery_dispatch_note_item($id);
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_loading_sheet';
	    $this->load->view('delivery/print_delivery_sheet',$data);
    }








	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

   
  
}