<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
    include('core_stock_in_out.php');  
class Stock_In_Out extends Core_Stock_In_Out
{
    public function __construct()
    {
        parent::__construct();
    }
    function IssueMaterialBatchForSTN(){
        ini_set('display_errors', 1); 
        $id=$this->getId();
        $sungle_item_list=$this->Stock_In_Out_Model->runGetproductionRequiredMaterial($id,null);
        $overall_process_status=1;
        foreach($sungle_item_list as $sil){
            //$overall_req_qty=$this->Stock_In_Out_Model->runGetSumAllBatchMaterial($sil['pbsi_product_mat_id'],$sil['psnm_id']);
            $overall_req_qty=$sil['pbis_qty'];
            
            $avilble_qty=$this->Stock_Counter_Model->get_stock_balance($sil['psnm_warehouse_id'],$sil['pbsi_product_mat_id']); 
            //echo "overall Qty ".$sil['pbsi_product_mat_id']." " .$overall_req_qty." Availble Qty ". $avilble_qty."<br> ";
            if($avilble_qty<$overall_req_qty){
               $overall_process_status=0;
               break;
            }
        }
        if($overall_process_status==0){
            $st = array('status' =>0,'validation' =>'Out of Stock','result'=>'null');
            echo json_encode($st);
            return false;
        } 
        $snt_result=$this->Stock_In_Out_Model->runGetproductionBatchMaterial($id,null);
           foreach($snt_result as $stnr){
             // echo "product".$stnr['pbsi_product_mat_id']." Qty ".$stnr['pbis_qty']." <br>Brackdown<br>...........<br>";
              $batch_list=$this->Stock_In_Out_Model->runGetMaterialBatch($stnr['pbsi_product_mat_id']);
              //print_r($stnr);
              $requried_qty=$stnr['pbis_qty'];
              $total_allocated_qty=0;
              $total_balance_qty=$stnr['pbis_qty'];
              foreach($batch_list as $bl){
                  if($total_allocated_qty==$requried_qty){
                      continue;
                  }
                   $batch_qty=$this->Stock_Counter_Model->get_stock_balance_batch($stnr['psnm_warehouse_id'],$stnr['pbsi_product_mat_id'],$bl['batch_id']);
                  if($batch_qty>=$total_balance_qty){
                      //echo $total_balance_qty."<br>";
                      $data=array(
                          'pbi_id'=>$stnr['pbi_id'],
                          'pbsi_id'=>$stnr['pbsi_id'],
                          'psni_id'=>$stnr['psni_id'],
                          'psnm_id'=>$stnr['psnm_id'],
                          'psoi_id'=>$stnr['psnm_id'],
                          'psom_id'=>$stnr['psnm_id'],
                          'product_mat_id'=>$stnr['pbsi_product_mat_id'],
                          'product_mat_batch_id'=>$bl['batch_id'],
                          'unit_price'=>$bl['product_cost'],
                          'cost'=>($bl['product_cost']*$total_balance_qty),
                          'quantity'=>$total_balance_qty,
                          'stock_out'=>$total_balance_qty,
                          'psio_issue_by'=>$this->session->userdata('ss_user_id'),
                          'psio_issue_on'=>date('Y-m-d H:i:s')
                          );
                      $last_id= $this->executeSaveMasterTable($data);
                      $data=array(
		        'prodcution_start_status'=>1,
		        'prodcution_start_on'=>date('Y-m-d H:i:s'),
		        'production_start_by'=>$this->session->userdata('ss_user_id'),
		        );
		       $this->Stock_In_Out_Model->updateProductionBatch($stnr['pbi_id'],$data);
                     $total_allocated_qty+=$total_balance_qty;
                     $total_balance_qty-=$total_balance_qty;
                  }else{
                      $total_allocated_qty+=$batch_qty;
                      $total_balance_qty-=$batch_qty;
                      $data=array(
                          'pbi_id'=>$stnr['pbi_id'],
                          'pbsi_id'=>$stnr['pbsi_id'],
                          'psni_id'=>$stnr['psni_id'],
                          'psnm_id'=>$stnr['psnm_id'],
                          'psoi_id'=>$stnr['psnm_id'],
                          'psom_id'=>$stnr['psnm_id'],
                          'product_mat_id'=>$stnr['pbsi_product_mat_id'],
                          'product_mat_batch_id'=>$bl['batch_id'],
                          'unit_price'=>$bl['product_cost'],
                          'cost'=>($bl['product_cost']*$batch_qty),
                          'quantity'=>$batch_qty,
                          'stock_out'=>$batch_qty,
                          'psio_issue_by'=>$this->session->userdata('ss_user_id'),
                          'psio_issue_on'=>date('Y-m-d H:i:s')
                          );
                      $last_id= $this->executeSaveMasterTable($data);
                        //echo $batch_qty."<br>";
                  }
                  
              }
            //echo "<br> total Allocated ".$total_allocated_qty."<br>";
            //echo "<br> total Balance ".$total_balance_qty."<br>";
            //echo "<hr>";
            //echo "<br>........................<br>";
           }
          if($overall_process_status==1){
           $data=array(
            'psoi_status'=>1,
			'issue_by'=>$this->session->userdata('ss_user_id'),
			'issue_on'=>date('Y-m-d H:i:s'),
		);
		$status=$this->executeUpdateItemTable($id,$data);
		foreach($snt_result as $stn2){
		    $data=array(
		        'pbsi_issue_on'=>date('Y-m-d H:i:s'),
		        'pbsi_issue_by'=>$this->session->userdata('ss_user_id'),
		        'pbsi_issue_status'=>1
		        );
		        $this->Stock_In_Out_Model->runUpdateBatchSubItemsUsingPrimaryId($stn2['pbsi_id'],$data);
		}
		
    	$batch_result=$this->executeSelectSubItemsTableUsingSecondaryId($id);
		foreach($batch_result as $bat_r){
		    $data=array(
		        'pbi_id'=>$bat_r['pbi_id'],
		        'psnm_id'=>$bat_r['psnm_id'],
		        'psni_id'=>$bat_r['psni_id'],
		        'pbstn_status'=>1,
		        'pbstn_on'=>date('Y-m-d H:i:s'),
		        'pbstn_by'=>$this->session->userdata('ss_user_id'),
		        );
		       $this->Stock_In_Out_Model->runSaveBatchSTN($data);
		}
		
		
		
		
		
		$st = array('status' =>$status,'validation' =>'Rollbacked','result'=>'null');
            echo json_encode($st);
        }else{
            $st = array('status' =>0,'validation' =>'Not Found','result'=>'null');
            echo json_encode($st);
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    //old functions
     function productionMaterilOut(){
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('store/production_material_out_master',$data);
    }
     function storeProductionMaterilOut(){
        $this->load->library('form_validation');
		$this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|xss_clean');
		$this->form_validation->set_rules('ref_no', 'Ref No ', 'xss_clean');
	    $this->form_validation->set_rules('note', 'Note', 'xss_clean');
		$ref_no=$this->cleanAndValidateText($this->input->post('ref_no'));
		$warehouse_id=$this->cleanAndValidateNumber($this->input->post('warehouse_id'));
	    $note=$this->cleanAndValidateText($this->input->post('note'));
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'psom_document_no'=>$ref_no,
			'psom_warehouse_id'=>$warehouse_id,
			'psom_note'=>$note,
			'psom_user_id'=>$this->session->userdata('ss_user_id'),
			'psom_date_time'=>date('Y-m-d H:i:s'),
			'psom_ref_no'=>$this->Common_Model->gen_ref_number('psom_id','production_stock_out_master','SI')
		);
		$last_id= $this->executeSaveMasterTable($data);
		$st = array('status' =>1,'validation' =>'Added','result'=>$last_id);
        echo json_encode($st);
		}
    }
    function loadSTNListForIssue(){
        $id=$this->getId();
        $data=array();
        $data['details'] = $this->executeSelectMasterTable($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $data['stn_id'] =$id;
        $this->load->view('store/production_material_out_items',$data);
    }
     function getListPendingSTN(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getPendingSTNListForBasicDataTable($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $row) {
	        $nestad_data=array();
	        $nestad_data[]  = $row['psnm_ref_no'];
	        $nestad_data[]  = $row['psnm_manual_ref_no'];
	        $nestad_data[]  = $row['warehouse_name'];
	        $nestad_data[]  = $row['psnm_date_time'];
	        $nestad_data[]  = $row['user_first_name'];
	        $action='<input type="checkbox" id="select_'.$row['psnm_id'].'" name="select[]" value="'.$row['psnm_id'].'">';
	      $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        }else{
            $output = array(
                'data' => array(),
                "recordsTotal" => intval(0),
                "recordsFiltered" => intval(0)
            );
            echo json_encode($output);
        }
   }
    
    function saveStoreSTNItems(){
        $this->load->library('form_validation');
		$this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|xss_clean');
		$this->form_validation->set_rules('master_id', 'Main Recode', 'required|xss_clean');
	    $this->form_validation->set_rules('select', 'Select Item', 'required');
		$master_id=$this->cleanAndValidateNumber($this->input->post('master_id'));
		$warehouse_id=$this->cleanAndValidateNumber($this->input->post('warehouse_id'));
	    $select=$this->cleanAndValidateArray($this->input->post('select'));
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        foreach($select as $row){
	         $data=array(
			'psom_id'=>$master_id,
			'psnm_id'=>$row,
		);
		$last_id= $this->executeSaveItemTable($data);
		 $data=array(
			'psnm_pickup_status'=>1,
			'psnm_pickup_by'=>$this->session->userdata('ss_user_id'),
			'psnm_pickup_on'=>date('Y-m-d H:i:s'),
		);
		$this->executeUpdateSubItemTable($row,$data);
	    }
		$st = array('status' =>1,'validation' =>'Added','result'=>$last_id);
        echo json_encode($st);
		}
    }
    
    function getListSelectedSTN(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getSelectedSTNListForBasicDataTable($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $row) {
	        $nestad_data=array();
	        $nestad_data[]  = $row['psnm_ref_no'];
	        $nestad_data[]  = $row['psnm_manual_ref_no'];
	        $nestad_data[]  = $row['warehouse_name'];
	        $nestad_data[]  = $row['psnm_date_time'];
	        $nestad_data[]  = $row['user_first_name']; 
	        $action='<button class="btn btn-xs btn-danger" id="delete'.$row['psoi_id'].'" name="delete'.$row['psoi_id'].'" onclick="rollback('.$row['psoi_id'].')" >Rolll Back</button>';
	        if($row['psoi_status']==1){
	             $action='<span class="btn btn-xs btn-success" >Finished</span>';
	        }
	      $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        }else{
            $output = array(
                'data' => array(),
                "recordsTotal" => intval(0),
                "recordsFiltered" => intval(0)
            );
            echo json_encode($output);
        }
   }
    function rollbackSTNToPendingStatus(){
        $id=$this->getId();
        $result=$this->executeSelectItemTable($id);
        if(isset($result['psnm_id'])){
           $main_recode_id=$result['psnm_id']; 
           $data=array(
            'psnm_rollback_status'=>1,
			'psnm_pickup_status'=>0,
			'psnm_rollback_by'=>$this->session->userdata('ss_user_id'),
			'psnm_rollback_on'=>date('Y-m-d H:i:s'),
		);
		$status=$this->executeUpdateSubItemTable($main_recode_id,$data);
		if($status==1){
		  $status=$this->executeDeleteItemTable($id);  
		}
		$st = array('status' =>$status,'validation' =>'Rollbacked','result'=>'null');
            echo json_encode($st);
        }else{
            $st = array('status' =>0,'validation' =>'Not Found','result'=>'null');
            echo json_encode($st);
        }
    }
    
     function notCompleteStoreNote(){
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'not_complete_store_note';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('estimate/not_completed_store_note',$data);
    }
    
    
    
     function getListNotCompleteStoreNote(){
        $request_data=$this->getClientSideDataTableParameters();
        $result_array=$this->getNotCompleteStoreNoteForBasicDataTableOnServerSide($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $row=array();
                $row[]               = $products->psnm_ref_no;
                $row[]               = $products->psnm_manual_ref_no;
                $row[]               = $products->psnm_date_time;
                 $row[]               = $products->user_first_name;
                $row[]               = $products->warehouse_name;
                $row[]               = $products->psnm_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('production_preparation/loadStoreNoteItems?id='. $products->psnm_id ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-edit"></i> Update Store Note</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 getListSelectedSTNTotalMaterial(){
       $this->load->model('Stock_Counter_Model');
       ini_set('display_errors', 1); 
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getSelectedSTNMaterialListForBasicDataTable($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $row) {
            $required_qty=  $this->Production_Material_In_Out_Model->runGetSumAllSTNMaterial($row['product_mat_id'],$request_data['id']);
            $avilble_qty=$this->Stock_Counter_Model->get_stock_balance(4,$row['product_mat_id']);   
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_mat_code'];
	        $nestad_data[]  = $row['product_mat_name'];
	        $nestad_data[]  = $row['mpt_name'];
	        $nestad_data[]  = $row['unit_name'];
	        $nestad_data[]  = $required_qty;  
	        $nestad_data[]  = $avilble_qty; 
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        }else{
            $output = array(
                'data' => array(),
                "recordsTotal" => intval(0),
                "recordsFiltered" => intval(0)
            );
            echo json_encode($output);
        }
   }
   function updteStoreNote(){
       return 0;
        $this->load->library('form_validation');
		$this->form_validation->set_rules('stn_master_id', 'Recode', 'required|xss_clean');
		$stn_master_id=$this->cleanAndValidateNumber($this->input->post('stn_master_id'));
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            $data=array(
			'psnm_status'=>1,
			'finish_by'=>$this->session->userdata('ss_user_id'),
			'finish_on'=>date('Y-m-d H:i:s'),
		);
		$last_id= $this->executeUpdateMasterTable($stn_master_id,$data);
		$st = array('status' =>1,'validation' =>'Added','result'=>$last_id);
        echo json_encode($st);
		}
    }
     function loadSTNIssueFromStore(){
        $id=$this->getId();
        $data=array();
        $data['details'] = $this->executeSelectMasterTable($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $data['stn_id'] =$id;
        $this->load->view('store/production_material_issue',$data);
    }
    function getListSelectedSTNforIssueMaterialBatch(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getSelectedSTNListForBasicDataTable($request_data);
        $values=$result_array['values'];
        $value_count=$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $row) {
	        $nestad_data=array();
	        $nestad_data[]  = $row['psnm_ref_no'];
	        $nestad_data[]  = $row['psnm_manual_ref_no'];
	        $nestad_data[]  = $row['warehouse_name'];
	        $nestad_data[]  = $row['psnm_date_time'];
	        $nestad_data[]  = $row['user_first_name']; 
	        $action='
	        <button class="btn btn-xs btn-primary" id="issue'.$row['psoi_id'].'" name="issue'.$row['psoi_id'].'" onclick="issueMaterial('.$row['psoi_id'].')" >Issue Materials</button>
	        
	        <button class="btn btn-xs btn-danger" id="delete'.$row['psoi_id'].'" name="delete'.$row['psoi_id'].'" onclick="rollback('.$row['psoi_id'].')" >Rolll Back</button>';
	        if($row['psoi_status']==1){
	             $action='<span class="btn btn-xs btn-success" >Finished</span>';
	        }
	      $nestad_data[]  =$action;
	         $data[]=$nestad_data;
	    }
	     $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        }else{
            $output = array(
                'data' => array(),
                "recordsTotal" => intval(0),
                "recordsFiltered" => intval(0)
            );
            echo json_encode($output);
        }
   }
   
  
  
  
   
}