<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
   
class Dispatch extends CI_Controller
{
    var $main_menu_name = "dispatch";
    var $sub_menu_name = "dispatch";
    private $main_model;
   
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Colombo");
        $this->load->model('Common_Model');
        $this->load->model('Dispatch_Model');
        $this->load->model('User_Model');
        $this->load->model('Customer_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Product_Models');
    }
    public function index()
    {
       show_404();
    }
     function list_dispatch_note(){
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_dispatch_note';
	    $this->load->view('dispatch/list_dispatch',$data);
	}  
     function get_dispatch_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->Dispatch_Model->get_dispatch_list($start, $length, $search_key_val);
        $value_count    = $this->Dispatch_Model->get_dispatch_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->Dispatch_Model->get_dispatch_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-danger"> PENDING </sapn>';
                if($products->dpn_status==1){
                   $status='<span class=" btn btn-xs btn-warning"> TO BE LOADING</sapn>'; 
                }
                $row[]               = $products->added_date_time;
                $row[]               = $products->dpn_ref_no;
                 $row[]               = $products->dpn_manual_ref_no;
                $row[]               = $products->cus_code;
                $row[]               = $products->cus_name;
                $row[]               = $products->user_first_name." ".$products->user_last_name;
                $row[]               = $status;
               $row[]               = $products->total_dpn_value;
                $actdes = '';
               if($products->dpn_status==0){
                    $option_split='<li><a href="' . base_url('dispatch/add_dispatch_items') . '?id=' . $products->dpn_id . '"><i class="fa fa-gear"></i> SPLIT</a></li>'; 
               }else{
                   $option_split='';
               }
                $update_action='<li><a  href="' . base_url('dispatch/dispatch_note_details') . '?id=' . $products->dpn_id . '"><i class="fa fa-file-text-o"></i> DETAILS</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.$option_split.'
                            <!--<li><a style="cursor: pointer;" onclick="approval_requste('. $products->dpn_id .')"><i class="glyphicon fa fa-check"></i> APPROVAL</a></li>
                            <li><a style="cursor: pointer;" onclick="reject_request('. $products->dpn_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 dispatch_note_details(){
        $id = $this->input->get('id');
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_dispatch_note';
	     $data['details'] = $this->Dispatch_Model->get_all_dipatch_details($id);
	      $data['item_list'] = $this->Dispatch_Model->get_order_dispatch_item_list($id);
	    $this->load->view('dispatch/dispatch_details',$data);
	}
    function list_invoice(){
	    $data['main_menu_name'] = 'invoice';
		$data['sub_menu_name'] = 'list_invoice';
	    $this->load->view('dispatch/list_dispatch',$data);
	}  
    function add_dispatch_items(){
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_dispatch_note';
		$data['dpn_id'] =$this->input->get('id');
		$data['details']=$this->Dispatch_Model->get_all_dipatch_details($data['dpn_id']);
	    $this->load->view('dispatch/add_dispatch_items',$data);
	}
    public function get_dispatch_note_item_list() {
        $id=$this->input->get('id');
        $values = $this->Dispatch_Model->get_order_dispatch_item_list($id);
         $data          = array();
	    foreach ($values as $row) {
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['unit_code'];
	        $nestad_data[]  = $row['uom_price'];
	        $nestad_data[]  = $row['issued_qty'];
	       $nestad_data[]  =$row['total_price'];
	       $nestad_data[]  =($row['product_weight']/$row['pr_quantity'])*$row['issued_qty'];
	       
	     $action='
	     <button type="button" class="btn btn-primary btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit Quantity" onClick="update_aloacted_qty('.$row['dni_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['dni_id'].')"><i class="fa fa-trash-o" aria-hidden="true"> REMOVE</i></button>-->
	     ';
	       $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
            );
            echo json_encode($output);
    }  
     public function update_dispatch_product_qty(){
		$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.99]|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');
	    	$original_data=$this->Dispatch_Model->get_original_item_data($id);
	    	if($original_data['issued_qty']<$result){
	    	  $st = array('status' =>0,'validation' =>'You cannot exceed the maximum dispatch quantity');
	    	   echo json_encode($st);
	    	   return;
	    	}
            $data=array(
			'issued_qty'=>$result,
			'total_price'=>$original_data['uom_price']*$result,
			'total_cost'=>$original_data['uom_cost']*$result,
			'total_weight'=>($original_data['product_weight']/$original_data['pr_quantity'])*$result,
		);	
         $result=$this->Dispatch_Model->update_dispach_note_item($id,$data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	} 
	function final_dispatch_note(){
       	$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->Dispatch_Model->get_dispatch_note_total_values($id);
            $total_waight=$result['total_weight'];
            $total_cost=$result['total_cost'];
            $total_price=$result['total_price'];
            if($result['total_cost']==0){
                  $st = array('status' =>0,'validation' => 'DISPATCH NOTE IS INVALID');
                  echo json_encode($st);
                  return false;
             }
           	$charge = $this->Dispatch_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_cost,
		    'total_dpn_price'=>$total_price,
		    'loading_unloading_charge'=>$loading_unloading_charge,
		    'total_dpn_value'=>$total_price+$loading_unloading_charge,
		    'dpn_status'=>1
		    );
		    $result=$this->Dispatch_Model->update_dispach_note_master($id,$data);
		    $original_data=$this->Dispatch_Model->get_original_master_data($id);
		    
		    $data=array(
            'order_id'=>$original_data['order_id'],
			'dpn_warehouse_id'=>$original_data['dpn_warehouse_id'],
			'dpn_sale_rep_id'=>$original_data['dpn_sale_rep_id'],
			'dpn_customer_id'=>$original_data['dpn_customer_id'],
			'dpn_manual_ref_no'=>$original_data['dpn_manual_ref_no'],
			'dpn_note'=>$original_data['dpn_note'],	
			'dpn_type_id'=>$original_data['dpn_type_id'],
			'dpn_price_type_id'=>$original_data['dpn_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->Dispatch_Model->save_dispach_note($data);
		$original_item_data=$this->Dispatch_Model->get_original_item_data_list($id);
	    foreach($original_item_data as $oid){
	        $issue_data=$this->Dispatch_Model->get_issued_item_data($oid['dni_id']);
	        $issue_qty=$issue_data['issued_qty'];
	        $qty_balance=$oid['issued_qty']-$issue_qty;
	        
	        $data=array(
            'dnm_id'=>$last_id,
			'odri_id'=>$oid['odri_id'],
			'product_id'=>$oid['product_id'],
			'issued_qty'=>$qty_balance,	
			'uom_price'=>$oid['uom_price'],
			'uom_cost'=>$oid['uom_cost'],
			'total_price'=>$oid['uom_cost']*$qty_balance,
			'total_cost'=>$oid['uom_cost']*$qty_balance,
			'price_important'=>$oid['price_important'],
			'total_weight'=>($oid['product_weight']/$oid['pr_quantity'])*$qty_balance,
		);	
		$this->Dispatch_Model->save_dispach_note_item($data);
	    }
	     $result=$this->Dispatch_Model->get_dispatch_note_total_values($last_id);
            $total_waight=$result['total_weight'];
            $total_cost=$result['total_cost'];
            $total_price=$result['total_price'];
            $loading_unloading_charge=($total_waight/$charge['unit_qty'])*$charge['charge'];
		    $data=array(
		    'dpn_total_weight'=>$total_waight,
		    'total_dpn_cost'=>$total_cost,
		    'total_dpn_price'=>$total_price,
		    'loading_unloading_charge'=>$loading_unloading_charge,
		    'total_dpn_value'=>$total_price+$loading_unloading_charge,
		    'dpn_status'=>1
		    );
		    $result=$this->Dispatch_Model->update_dispach_note_master($last_id,$data);
          $st = array('status' =>1,'validation' =>'DISPATCH NOTE COMPLETED');
          echo json_encode($st);
		}
    }
       
       
       
     
     function add_dispatch_invoice(){
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_dispatch_note';
		$data['dpn_id'] =$this->input->get('id');
		$data['details']=$this->Dispatch_Model->get_all_dipatch_details($data['dpn_id']);
	    $this->load->view('dispatch/add_dispatch_invoice',$data);
	}
     
      public function get_dispatch_note_invoice_item_list() {
        $id=$this->input->get('id');
        $values = $this->Dispatch_Model->get_order_dispatch_item_list($id);
         $data          = array();
	    foreach ($values as $row) {
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['unit_code'];
	         $nestad_data[]  = $row['issued_qty'];
	          $nestad_data[]  = $row['invoice_qty'];
	        $nestad_data[]  = $row['uom_price'];
	       $nestad_data[]  =$row['uom_price']*$row['invoice_qty'];
	       //$nestad_data[]  =($row['product_weight']/$row['pr_quantity'])*$row['invoice_qty'];
	       
	     $action='
	     <button type="button" class="btn btn-primary btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit Quantity" onClick="update_aloacted_qty('.$row['dni_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['dni_id'].')"><i class="fa fa-trash-o" aria-hidden="true"> REMOVE</i></button>-->
	     ';
	       $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
            );
            echo json_encode($output);
    }  
    
     public function update_dispatch_invoice_qty(){
		$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.99]|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');
	    	$original_data=$this->Dispatch_Model->get_issued_item_data($id);
	    	if($original_data['issued_qty']<$result){
	    	  $st = array('status' =>0,'validation' =>'You cannot exceed the maximum dispatch quantity');
	    	   echo json_encode($st);
	    	   return;
	    	}
            $data=array(
			'invoice_qty'=>$result,
			'return_qy'=>$original_data['issued_qty']-$result,
			'invoice_by'=>$this->session->userdata('ss_user_id'),
			'invoice_on'=>date("Y-m-d H:i:s"),
		);	
         $result=$this->Dispatch_Model->update_dispach_note_item($id,$data);	   
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
		}
	} 
	
	function final_invoice(){
       	$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->Dispatch_Model->get_issued_item_list_data($id);
            $invoice_qty_count=0;
            foreach($result as $r){
                $invoice_qty_count+=$r['invoice_qty'];
            }
            if($invoice_qty_count<=0){
                $data=array(
		    'invoice_status'=>1,
		    'invoice_by'=>$this->session->userdata('ss_user_id'),
			'invoice_on'=>date("Y-m-d H:i:s"),
		    );
		    $result=$this->Dispatch_Model->update_dispach_note_master($id,$data);
                  $st = array('status' =>0,'validation' => 'ALL ITEM RETURN');
                  echo json_encode($st);
                  return false;
             }
           
		    $original_data=$this->Dispatch_Model->get_all_dipatch_details($id);
		    
		    $data=array(
			'warehouse_id'=>$original_data['dpn_warehouse_id'],
			'sales_rep_id'=>$original_data['dpn_sale_rep_id'],
			'customer_id'=>$original_data['dpn_customer_id'],
			'bill_no'=>$original_data['dpn_ref_no'],
			'card_ref_number'=>$original_data['dpn_ref_no'],
			'sale_note'=>$original_data['dpn_note'],	
			'invoice_type'=>$original_data['dpn_type_id'],
			'invoice_type'=>$original_data['dpn_price_type_id'],
			'delivery_charge'=>$original_data['loading_unloading_charge'],
			'sale_reference_no'=>$this->Common_Model->gen_ref_number('sale_id','sales','DI'),
			'user'=>$this->session->userdata('ss_user_id'),
			'sale_datetime'=>date("Y-m-d H:i:s"),
			'sale_datetime_created'=>date("Y-m-d H:i:s"),
		);  
		$last_id=$this->Dispatch_Model->save_invoice_master($data);
		$original_item_data=$this->Dispatch_Model->get_issued_item_list_data($id);
	    foreach($original_item_data as $oid){
	        $avg_cost=$this->Dispatch_Model->get_issued_all_avg_batch_cost($oid['dni_id']);
	        $data=array(
            'sale_id'=>$last_id,
			'product_id'=>$oid['product_id'],
			'quantity'=>$oid['invoice_qty'],	
			'unit_price'=>$oid['uom_price'],
			'item_cost'=>$avg_cost,
			'total_item_cost'=>$avg_cost*$oid['invoice_qty'],
			'gross_total'=>$oid['uom_price']*$oid['invoice_qty'],
			'net_total'=>$oid['uom_price']*$oid['invoice_qty'],
		);	
		$this->Dispatch_Model->save_invoice_item($data);
	    }
	     $total=$this->Dispatch_Model->get_invoice_total_values($last_id);
            $total_item_cost=$total['total_item_cost'];
            $gross_total=$total['gross_total'];
            $net_total=$total['net_total'];
           
		    $data=array(
		    'cost_total'=>$total_item_cost,
		    'sale_total'=>$net_total+$original_data['loading_unloading_charge'],
		    'sale_inv_total'=>$net_total,
		    'sale_inv_gross_total'=>$gross_total,
		    );
		    $result=$this->Dispatch_Model->update_sale_master($last_id,$data);
		    
		    $data=array(
		    'invoice_status'=>1,
		    'invoice_by'=>$this->session->userdata('ss_user_id'),
			'invoice_on'=>date("Y-m-d H:i:s"),
		    );
		    $result=$this->Dispatch_Model->update_dispach_note_master($id,$data);
          $st = array('status' =>1,'validation' =>'INVOICED','delivery_id'=>$original_data['delivery_id']);
          echo json_encode($st);
		}
    }
     
      function dispatch_note_print(){
        $id = $this->input->get('id');
	    $data['main_menu_name'] = 'store';
		$data['sub_menu_name'] = 'list_dispatch_note';
	    $data['details'] = $this->Dispatch_Model->get_all_dipatch_details($id);
	    $data['warehouse_details']= $data['details'];
	    $data['item_list'] = $this->Dispatch_Model->get_order_dispatch_item_list($id);
	    $data['return_note_items'] = $this->Dispatch_Model->get_return_item_list($id);
	    $data['return_note_master'] = $this->Dispatch_Model->get_return_master_list($id);
	    
	    $this->load->view('dispatch/dispatch_note_print',$data);
	}
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
       
       
       
       
     
  
}