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

class Batch_Process extends CI_Controller {
	
    var $main_menu_name = "purchases";
	  var $sub_menu_name = "categories";

      function __construct() 
      {
        parent::__construct();
        $this->load->model('Batch_Process_Model');
        $this->load->model('Common_Model');
		$this->load->model('Sequerty_Model');
        $this->load->library('form_validation');
		$this->load->model('User_Model');
      }

    public function index($e=0)
    {
      $data['error'] = $e;
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "batch";
      $this->load->view('batch/batch_purchases_list',$data);
    }

    public function get_list_purchases($value='')
    {
          $values = $this->Batch_Process_Model->getpurchases();
            $data = array();
            if (!empty($values)) {
                foreach ($values as $purchases) {
                $row = array();
                    $row[] = $purchases->date;
                    $row[] = $purchases->reference_no;
                    $row[] = $purchases->supp_company_name;
					$row[] = $purchases->supp_invocie_no;
                    $row[] = $purchases->product_code;
                    $row[] = $purchases->product_name;
                    $row[] = $purchases->unit_price;
                     $row[] = $purchases->quantity;
                    $row[] = '<div class="text-center"><div class="btn-group text-left">
                    <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                    <ul role="menu" class="dropdown-menu pull-right">
                    <li><a onClick="click_grn_update_btn('.$purchases->id.')" data-toggle="modal" href="#">create new batch</a></li>
                    <li><a onClick="assign_auto_batch('.$purchases->id.','.$purchases->unit_price.','.$purchases->product_id.')" data-toggle="modal" href="#">Auto assign last batch cost</a></li>
                    </ul></div>
                    </div>';
                    $data[] = $row;
                }
                $output = array('data' =>$data);
                echo json_encode($output);
            }else{
                $output = array('data' =>'');
                echo json_encode($output);
            }
       }
    
    	public function create_batch()
	{
        $data['id'] = 1;
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'create_batch';
		
        if (isset($_GET['grn_item_id'])) {
			$grn_item_id=$_GET['grn_item_id'];
		}
		else {
			$grn_item_id='';
		}
		if($grn_item_id){
			$data['grn_item_id']=$grn_item_id;
			$data['type']='A';
			$data['pageName']='CREATE BATCH';
			$data['btnText']='create batch';
			$data['details']= $this->Batch_Process_Model->get_gen_item_id_details($grn_item_id);	
		}
        $this->load->view('batch/create_batch',$data);	
	}
	

	
	 public function save_batch()
	{
	  
	    $this->load->library('form_validation'); //form validation lib
	    $this->form_validation->set_rules('batch_code', 'Batch Code', 'is_unique[batch_product.batch_ref_number]');
		$this->form_validation->set_rules('grn_item_id', 'GRN', 'required');
		$type=$this->input->post('type');
		$grn_item_id=$this->input->post('grn_item_id');
		$product_id=$this->input->post('product_id');
		$cost=$this->input->post('cost');
		$batch_code=$this->input->post('batch_code');
		$dcc=$this->input->post('dcc');
		$dcp=$this->input->post('dcp');
		$dwp=$this->input->post('dwp');
		$rcc=$this->input->post('rcc');
		$rcp=$this->input->post('rcp');	
		$rwp=$this->input->post('rwp');
		if($batch_code)
		{}else{
		$batch_code=$this->Common_Model->gen_ref_number('batch_id','batch_product','BTC');
		}
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
		$data=array(
			'grn_item_id'=>$grn_item_id,
			'product_id'=>$product_id,
			'batch_ref_number'=>$batch_code,	
			'product_cost'=>$cost,
			'product_price'=>$dcc,
			'credit_salling_price'=>$dcp,
			'wholesale_price'=>$dwp,	
			'retail_cash'=>$rcc,
			'retail_credit'=>$rcp,
			'retail_wholesale'=>$rwp,
			'user_id'=>$this->session->userdata('ss_user_id'),
		);
		$result=$this->Batch_Process_Model->save_batch($data);
		$lastid=$this->db->insert_id();
        if($result==1){
            $result=$this->Batch_Process_Model->update_product($grn_item_id);
        }
		if($type=='A'){
			if ($lastid) {
				echo json_encode(array('id'=>$lastid,'type'=>$type,'status' =>1));
			} else {
				echo json_encode(array('status'=>'0'));
			}
		}
		if($type=='E'){
			echo json_encode(array('type'=>$type,'status' =>1));
		}	
		}
	}
	
	public function update_batch()
	{
	    $id=$this->input->get('id');
	    $status=$this->input->get('status');
	    $data=array(
			'batch_status'=>$status,
			'user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);
		$result=$this->Batch_Process_Model->update_batch($id,$data);
			if($result==1){
				echo json_encode(array('id'=>'','status' =>1,'message'=>"Done"));
			} else {
			   echo json_encode(array('id'=>'','status' =>0,'message'=>"Fail"));
			}
	}
	
		public function auto_assign_last_batch()
	{
	    $id=$this->input->get('id');
	    $product_id=$this->input->get('product_id');
	    $cost=$this->input->get('cost');
	    
	    $result=$this->Batch_Process_Model->get_last_batch_id_using_cost($product_id,$cost);
	    if($result!=false){
	        $data=array(
			'grn_item_id'=>$id,
			'product_id'=>$product_id,
			'batch_id'=>$result,
			'user_id'=>$this->session->userdata('ss_user_id'),
			'added_date_time'=>date("Y-m-d H:i:s"),
		);
		$insert_result=$this->Batch_Process_Model->insert_last_batch_id($data);
	        if($insert_result==1){
	            $data=array('is_batch_created'=>1);
	            $result=$this->Batch_Process_Model->update_grn_item_table($id,$data);
	            if($result==1){
	               	echo json_encode(array('id'=>'','status' =>1,'message'=>"Done")); 
	            }else{
	               echo json_encode(array('id'=>'','status' =>0,'message'=>"GRN Item table not update")); 
	            }
	        }
	    }else{
	        echo json_encode(array('id'=>$id,'status' =>0,'message'=>"The relevent product cost not found in the previous batch")); 
	    }
	}
	
		public function edit_batch()
	{
        $data['id'] = 1;
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'etit_batch';
		
        if (isset($_GET['batch_id'])) {
			$batch_id=$_GET['batch_id'];
		}
		else {
			$batch_id='';
		}
		if($batch_id){
			$data['batch_id']=$batch_id;
			$data['type']='A';
			$data['pageName']='EDIT BATCH';
			$data['btnText']='Edit batch';
			$data['details']= $this->Batch_Process_Model->get_product_batch_details($batch_id);	
		}
        $this->load->view('batch/update_batch',$data);	
	}
	
	 public function update_batch_product()
	{
	  
	    $this->load->library('form_validation'); //form validation lib
	    //$this->form_validation->set_rules('batch_code', 'Batch Code', 'is_unique[batch_product.batch_ref_number]');
		$this->form_validation->set_rules('batch_id', 'Batch', 'required');
		$type=$this->input->post('type');
		$batch_id=$this->input->post('batch_id');
		$product_id=$this->input->post('product_id');
		$cost=$this->input->post('cost');
		$batch_code=$this->input->post('batch_code');
		$dcc=$this->input->post('dcc');
		$dcp=$this->input->post('dcp');
		$dwp=$this->input->post('dwp');
		$rcc=$this->input->post('rcc');
		$rcp=$this->input->post('rcp');	
		$rwp=$this->input->post('rwp');
	
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
		$data=array(
		    'product_cost'=>$cost,
			'product_price'=>$dcc,
			'credit_salling_price'=>$dcp,
			'wholesale_price'=>$dwp,	
			'retail_cash'=>$rcc,
			'retail_credit'=>$rcp,
			'retail_wholesale'=>$rwp,
			'user_id'=>$this->session->userdata('ss_user_id'),
		);
		$result=$this->Batch_Process_Model->update_batch($batch_id,$data);
		$result=$this->Batch_Process_Model->update_batch($batch_id,$data);
		$data2=array(
		    'retail_cash'=>$rcc,
		    'retail_wholesale'=>$rwp,
		    );
		$this->Batch_Process_Model->update_main_product_table($data2,$product_id);
		$this->Batch_Process_Model->update_main_product_table($data2,$product_id);
		if($type=='A'){
			if ($result) {
				echo json_encode(array('type'=>$type,'status' =>1));
			} else {
				echo json_encode(array('status'=>'0'));
			}
		}
		if($type=='E'){
			echo json_encode(array('type'=>$type,'status' =>1));
		}	
		}
	}
	
	
	public function batch_qty_adjustment()
	{
        $data['id'] = 1;
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'etit_batch';
        if (isset($_GET['product_id'])) {
			$product_id=$_GET['product_id'];
		}
		else {
			$product_id='';
		}
		if($product_id){
			$data['product_id']=$product_id;
			$data['type']='A';
			$data['pageName']='EDIT BATCH';
			$data['btnText']='Edit batch';
			$data['details']= $this->Batch_Process_Model->get_all_product_details($product_id);
			$data['batch_list']= $this->Batch_Process_Model->get_all_batch_list($product_id);	
		}
        $this->load->view('batch/batch_qty_adjustment',$data);	
	}
	
	public function save_batach_adjustment()
	{
	    $this->load->library('form_validation');
		$this->form_validation->set_rules('product_id', 'Product', 'required');
		$this->form_validation->set_rules('tranfer_from', 'Tranfer from', 'required');
		$this->form_validation->set_rules('tranfer_to', 'Tranfer To', 'required');
		$this->form_validation->set_rules('batch_qty', 'Qty', 'required');
		$type=$this->input->post('type');
		$product_id=$this->input->post('product_id');
		if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
		$data=array(
		    'product_id'=>$this->input->post('product_id'),
			'batch_id'=>$this->input->post('tranfer_from'),
			'batch_id_qty_trasfer_to'=>$this->input->post('tranfer_to'),
			'batch_qty'=>$this->input->post('batch_qty'),	
			'date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),
		);
		$result=$this->Batch_Process_Model->save_batch_qty_adjesment_table($data);
		$original_qty=$this->input->post('batch_qty');
		$reverce_qty=$original_qty*-1;
		$data=array(
		    'product_id'=>$this->input->post('product_id'),
			'batch_id'=>$this->input->post('tranfer_to'),
			'batch_id_qty_trasfer_to'=>$this->input->post('tranfer_from'),
			'batch_qty'=>$reverce_qty,	
			'date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),
		);
		$result=$this->Batch_Process_Model->save_batch_qty_adjesment_table($data);
		if($type=='A'){
			if ($result) {
				echo json_encode(array('type'=>$type,'status' =>1));
			} else {
				echo json_encode(array('status'=>'0'));
			}
		}
		if($type=='E'){
			echo json_encode(array('type'=>$type,'status' =>1));
		}	
		}
	}
	
	
	
	
    function manual_batch_stock_adjesment_function(){
        $this->load->model('Stock_Counter_Model');
	   $result= $this->Batch_Process_Model->get_product_list_for_update(3000,1000);
	   
	   foreach($result as $row){
	       //$total_qty=$this->Stock_Counter_Model->get_stock_balance('',$row['product_id']);
	       
	       $result2= $this->Batch_Process_Model->get_all_batch_list($row['product_id']);
	       
	       if(count($result2)==2){
	           
	           $pus_batch_id="";
	           $pus_batch_number="";
	           $pus_qty=0;
	           $minus_batch_id="";
	           $minus_batch_number="";
	           $minus_qty=0;
	           foreach($result2 as $brow){
	               $btc_qty=$this->Stock_Counter_Model->get_stock_balance_batch('',$row['product_id'],$brow['batch_id']);
	               if($btc_qty>0){
	                  $pus_qty= $btc_qty;
	                  $pus_batch_number=$brow['batch_ref_number'];
	                  $pus_batch_id=$brow['batch_id'];
	                  
	               }else{
	                  $minus_qty= $btc_qty;
	                  $minus_batch_number=$brow['batch_ref_number'];
	                  $minus_batch_id=$brow['batch_id'];
	               }
	           }
	           
	           if($minus_qty<0){
	               echo  $row['product_code']."  ".$row['product_name']." Qty "." <br> plus :   ".$pus_batch_number." Qty : ".$pus_qty."<br> Minuz ".$minus_batch_number." Qty ".$minus_qty."<br>
	               <hr>";
	               
	               
	              $convert_plus_qty=$minus_qty*-1; 
	               
	       $data=array(
		    'product_id'=>$row['product_id'],
			'batch_id'=>$minus_batch_id,
			'batch_id_qty_trasfer_to'=>$pus_batch_id,
			'batch_qty'=>$convert_plus_qty,	
			'date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),
		);
		$result=$this->Batch_Process_Model->save_batch_qty_adjesment_table($data);
		$data=array(
		    'product_id'=>$row['product_id'],
			'batch_id'=>$pus_batch_id,
			'batch_id_qty_trasfer_to'=>$minus_batch_id,
			'batch_qty'=>$minus_qty,	
			'date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),
		);
		$result=$this->Batch_Process_Model->save_batch_qty_adjesment_table($data);
	           }
	       }
	   }
	}
	
	
	
	
	
	


}