<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
    include('core_manufacture_preparation.php');  
class Manufacture_Preparation extends Core_Manufacture_Preparation
{
    public function __construct()
    {
        ini_set('display_errors', 1);
        parent::__construct();
    }
     function loadPendingManufacture(){
          
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'pending_manufacture';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/pending_manufacture',$data);
    }
     function getListPendingProduction(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getPendingProductionListForBasicDataTable($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['pbi_ref_no'];
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['pbi_qty'];
	        $nestad_data[]  = $row['psnm_ref_no'];
	        $nestad_data[]  = $row['warehouse_name'];
	        $nestad_data[]  = $row['user_first_name'];
	        $action='<button class="btn btn-xs btn-primary" id="send'.$row['pbi_id'].'" name="send'.$row['pbi_id'].'" onclick="sendToProduction('.$row['pbi_id'].')" >Send To Production</button>';
	        $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 sendToProduction(){
        $id=$this->getId();
        if($id>0){
           $data=array(
            'prodcution_start_status'=>1,
			'production_start_by'=>$this->session->userdata('ss_user_id'),
			'prodcution_start_on'=>date('Y-m-d H:i:s'),
		);
		$status=$this->executeUpdateMasterTable($id,$data);
		$st = array('status' =>$status,'validation' =>'Successfully Updated ','result'=>'null');
            echo json_encode($st);
        }else{
            $st = array('status' =>0,'validation' =>'Not Found','result'=>'null');
            echo json_encode($st);
        }
    }
    function loadOngoingManufacture(){
          
        $data=array();
        $this->load->model('Warehouse_Model');
        $this->load->model('Production_Estimate_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'ongoing_manufacture';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $data['time_profile_list'] = $this->Production_Estimate_Model->loadTimeProfile(125567);
        $this->load->view('manufacture/ongoing_manufacture',$data);
    }
     function getListOngoingProduction(){
       // $request_data=$this->getClientSideBasicDataTableParameters();
       	$warehouse_id=$this->input->get('warehouse_id');
		$req_date=$this->input->get('req_date');
		$req_date=date('Y-m-d H:i:s', strtotime($req_date));
		$time_profile_id=$this->input->get('time_profile_id');
        $result_array=$this->Manufacture_Preparation_Model->getOngoingProductionNew($warehouse_id,$time_profile_id,$req_date);
        
        
        $values=$result_array;//$result_array['values'];
        $value_count=count($result_array);//$result_array['value_count'];
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $row) {
	        $nestad_data=array();
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['pbi_ref_no'];
	        
	        
	        $nestad_data[]  = $row['pbi_qty'];
	        $nestad_data[]  = $row['pbi_required_date'];
	        $nestad_data[]  = $row['mtp_name'];
	        
	        $status=' <button class="btn btn-warning btn-sm " onClick="start_production('.$row['pbi_id'].')">START MANUFACTURE <i class="fa fa-clock-o  fa-2x fa-fw"></i></button> '; 
	        if($row['prodcution_start_status']==1){
	          $status='QC QTY  <input id="qc_qty_'.$row['pbi_id'].'" name="qc_qty" class="" value="" required> <button class="btn btn-primary btn-sm" onclick="approval_qc('.$row['pbi_id'].')">FINISH MANUFACTURE <i class="fa fa-circle-o-notch fa-spin fa-2x fa-fw"></i></button> ';  
	        }
	        
	        
	        
	       
	        $nestad_data[]  = '<span class="col-sm-12"> <button class="btn btn-default btn-sm" onclick="show_ingredients('.$row['pbi_id'].')">CHECK INGREDIENTS</button> '.$status."</span>";
	        //$action='<button class="btn btn-xs btn-primary" id="send'.$row['pbi_id'].'" name="send'.$row['pbi_id'].'" onclick="finish_production('.$row['pbi_id'].')" >Finish Production</button>';
	        
	        
	        //--------------------------------
	        
	    
	        
	        
	        
	        
	        //-------------------------------------
	        
	     /*   $action='<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=""  style="cursor: pointer;" id="send'.$row['pbi_id'].'" name="send'.$row['pbi_id'].'" onclick="finish_production('.$row['pbi_id'].')"><i class="glyphicon fa fa-check"></i> Finish Production</a></li>
                              <!--<li><a href="'.base_url('manufacture_preparation/loadRequestAddtionalItems?id='. $row['pbi_id'] ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-plus-circle"></i> Request Additional Items</a></li>-->
                             <!--<li><a href="'.base_url('manufacture_preparation/loadRemoveRemainingItems?id='. $row['pbi_id'] ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-minus-circle"></i> Send Remaining Items</a></li>-->
                            <li><a href="#"  onclick="show_ingredients('.$row['pbi_id'].')"><i class="glyphicon fa fa-eve"></i> Ingredients</a></li>
                            
                            
                            ';*/
	        
	        
	       // $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 finishProduction(){
        $id=$this->getId();
        if($id>0){
           $data=array(
            'production_end_status'=>1,
			'production_end_by'=>$this->session->userdata('ss_user_id'),
			'production_end_on'=>date('Y-m-d H:i:s'),
		);
		$status=$this->executeUpdateMasterTable($id,$data);
		$st = array('status' =>$status,'validation' =>'Successfully Updated ','result'=>'null');
            echo json_encode($st);
        }else{
            $st = array('status' =>0,'validation' =>'Not Found','result'=>'null');
            echo json_encode($st);
        }
    }
    function loadManufacturedProduct(){
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'manufactured_manufacture';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/manufactured_manufacture',$data);
    }
     function getListManufacturedProduction(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getManufacturedProductionListForBasicDataTable($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['pbi_ref_no'];
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['pbi_qty'];
	        $nestad_data[]  = $row['psnm_ref_no'];
	        $nestad_data[]  = $row['warehouse_name'];
	        $nestad_data[]  = $row['user_first_name'];
	        $action='<button class="btn btn-xs btn-primary" id="send'.$row['pbi_id'].'" name="send'.$row['pbi_id'].'" onclick="finish_production('.$row['pbi_id'].')" >Finish Production</button>';
	      
	        
	        
	        $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 loadQCProcess(){
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'qc_process';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/quality_check',$data);
    }
    function getListPendingQCProduction(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getManufacturedProductionListForBasicDataTable($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['pbi_ref_no'];
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['pbi_qty'];
	        $nestad_data[]  = $row['output_qty'];
	        $nestad_data[]  = $row['defect_qty'];
	        
	        $nestad_data[]  = $row['warehouse_name'];
	        $nestad_data[]  = $row['user_first_name'];
	        $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="approval_qc('. $row['pbi_id'].')"><i class="glyphicon fa fa-check"></i> QC Approval</a></li>
                               <li><a style="cursor: pointer;" onclick="reject_qc('. $row['pbi_id'].')"><i class="glyphicon fa fa-ban"></i> QC Reject</a></li>
                            ';
	        $nestad_data[]  =$actdes;
	         $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 setQcApproval(){
        $status=0;
        $massage='Enter Valid Quantity';
        $this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'Main Recode', 'required|xss_clean');
		$this->form_validation->set_rules('result', 'QC Quntity', 'required|xss_clean| greater_than[0]');
		$master_id=$this->cleanAndValidateNumber($this->input->post('id'));
		$qty=$this->cleanAndValidateNumber($this->input->post('result'));
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
            
        $total_actual_cost=$this->Manufacture_Preparation_Model->runGetSumBatchMaterialCost($master_id);
        $total_addtional_cost=$this->Manufacture_Preparation_Model->runGetSumAdditionalBatchMaterialCost($master_id);
         $row_data=$this->executeSelectMasterTable($master_id) ;
           if(isset($row_data['pbi_qty'])){
               if($row_data['pbi_qty']>=$qty){
                   $remain_qty=$row_data['pbi_qty']-$qty;
                   $data=array(
                       'pbi_lost_value'=>(($total_actual_cost/$row_data['pbi_qty'])*$remain_qty),
                       'pbi_additional_cost'=>$total_addtional_cost,
                       'pbi_total_actual_cost'=>$total_actual_cost,
                       'pbi_unit_cost'=>($total_actual_cost/$row_data['pbi_qty']),
                       'defect_qty'=>$remain_qty,
                       'output_qty'=>$qty,
			           'qc_status'=>1,
			           'qc_by'=>$this->session->userdata('ss_user_id'),
			           'qc_on'=>date('Y-m-d H:i:s'),
			           'production_end_status'=>1,
			           'production_end_on'=>date('Y-m-d H:i:s'),
			           'production_end_by'=>$this->session->userdata('ss_user_id'),
		            );
                   $this->executeUpdateMasterTable($master_id,$data);
                   $data=array('product_cost'=>($total_actual_cost/$row_data['pbi_qty']));
                   $this->Manufacture_Preparation_Model->update_product_table($row_data['pbi_product_id'],$data);
                    $status=1;
                   $massage="Sucssesfully Updated!";
               }else{
                   $status=0;
                   $massage="Not Valid Quntity";
               }
           } else{
                $status=0;
                   $massage="Not Found";
           }
           $st = array('status' =>$status,'validation' =>$massage,'result'=>'null');
        echo json_encode($st);
	    }
		
		}
	
    
    function setQcApprovalReject(){
        $this->load->library('form_validation');
		$this->form_validation->set_rules('id', 'Main Recode', 'required|xss_clean');
		$master_id=$this->cleanAndValidateNumber($this->input->post('id'));
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        $total_actual_cost=$this->Manufacture_Preparation_Model->runGetSumBatchMaterialCost($master_id);
        $total_addtional_cost=$this->Manufacture_Preparation_Model->runGetSumAdditionalBatchMaterialCost($master_id);
         $row_data=$this->executeSelectMasterTable($master_id) ;
           if(isset($row_data['pbi_qty'])){
               if($row_data['pbi_qty']){
                   $data=array(
                       'pbi_lost_value'=>$total_actual_cost,
                       'pbi_additional_cost'=>$total_addtional_cost,
                       'pbi_total_actual_cost'=>$total_actual_cost,
                       'pbi_unit_cost'=>($total_actual_cost/$row_data['pbi_qty']),
                       'defect_qty'=>$row_data['pbi_qty'],
                       'output_qty'=>0,
			           'qc_status'=>2,
			           'qc_by'=>$this->session->userdata('ss_user_id'),
			           'qc_on'=>date('Y-m-d H:i:s'),
		            );
                   $this->executeUpdateMasterTable($master_id,$data);
                    $status=1;
                   $massage="Sucssesfully Updated!";
               }else{
                   $status=0;
                   $massage="Not Valid Quntity";
               }
           } else{
                $status=0;
                   $massage="Not Found";
           }
	    }
		$st = array('status' =>$status,'validation' =>$massage,'result'=>'null');
        echo json_encode($st);
		}
		
		function loadReadyForGRN(){
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'ready_for_grn';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/ready_for_grn',$data);
    }
    
    function getListReadyForGRN(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getQCProductionListForBasicDataTable($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['pbi_ref_no'];
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['pbi_qty'];
	        $nestad_data[]  = $row['output_qty'];
	        $nestad_data[]  = $row['defect_qty'];
	       $nestad_data[]  = $row['pbi_unit_cost'];
	       $nestad_data[]  = $row['pbi_lost_value'];
	        $nestad_data[]  = $row['warehouse_name'];
	        $nestad_data[]  = $row['user_first_name'];
	        $nestad_data[]  = $row['qc_on'];
	       /* $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="approval_qc('. $row['pbi_id'].')"><i class="glyphicon fa fa-check"></i> QC Approval</a></li>
                               <li><a style="cursor: pointer;" onclick="reject_qc('. $row['pbi_id'].')"><i class="glyphicon fa fa-ban"></i> QC Reject</a></li>
                            ';*/
	        //$nestad_data[]  =$actdes;
	         $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 loadCreateNewGTN(){
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'not_completed_gtn';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/create_new_gtn',$data);
    }
    
    function createNewGTN(){
        $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(
			'pgrnm_doc_no'=>$ref_no,
			'pgrnm_warehouse_id'=>$warehouse_id,
			'pgrnm_note'=>$note,
			'pgrnm_user_id'=>$this->session->userdata('ss_user_id'),
			'pgrnm_date_time'=>date('Y-m-d H:i:s'),
			'pgrnm_ref_no'=>$this->Common_Model->gen_ref_number('pgrnm_id','production_grn','MGRN')
		);
		$last_id= $this->executeSaveItemTable($data);
		$st = array('status' =>1,'validation' =>'Added','result'=>$last_id);
        echo json_encode($st);
		}
    }
    function loadQCPassedProduct(){
        $id=$this->getId();
        $data=array();
        $data['details'] = $this->executeSelectItemTable($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $data['stn_id'] =$id;
        $this->load->view('manufacture/update_gtn',$data);
    }
    function getListPendingGTNProductionBatch(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getQCProductionListForBasicDataTable($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['pbi_ref_no'];
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['output_qty'];
	        $nestad_data[]  = $row['user_first_name'];
	        $nestad_data[]  = $row['qc_on'];
	        $action='<input type="checkbox" id="pbi_id'.$row['pbi_id'].'" name="pbi_id[]" value="'.$row['pbi_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 saveGTNItems(){
        $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('pbi_id', 'Select Item', 'required');
		$master_id=$this->cleanAndValidateNumber($this->input->post('master_id'));
		$warehouse_id=$this->cleanAndValidateNumber($this->input->post('warehouse_id'));
	    $pbi_id=$this->cleanAndValidateArray($this->input->post('pbi_id'));
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        foreach($pbi_id as $row){
            $details=$this->Manufacture_Preparation_Model->runGetBtachProductDetails($row);
	         $data=array(
			'pgrnm_id'=>$master_id,
			'pbi_id'=>$row,
			'product_id'=>$details['pbi_product_id'],
			'product_mat_id'=>$details['sub_product_of'],
			'quantity'=>$details['output_qty'],
			'pgrni_unit_cost'=>$details['pbi_unit_cost'],
			'pgrni_total_cost'=>$details['pbi_unit_cost']*$details['output_qty'],
			'pgrni_product_type_id'=>$details['product_type_id'],
			
		);
		$last_id= $this->executeSaveSubItemTable($data);
		 $data=array(
			'finish_status'=>1,
			'finish_by'=>$this->session->userdata('ss_user_id'),
			'finish_on'=>date('Y-m-d H:i:s'),
		);
		$this->executeUpdateMasterTable($row,$data);
	    }
		$st = array('status' =>1,'validation' =>'Added','result'=>$last_id);
        echo json_encode($st);
		}
    }
    
     function getListSelectedGTNProductionBatch(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getQCSelectedGTNProductionListForBasicDataTable($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['pbi_ref_no'];
	        $nestad_data[]  = $row['product_code'];
	        $nestad_data[]  = $row['product_name'];
	        $nestad_data[]  = $row['output_qty'];
	        $nestad_data[]  = $row['user_first_name'];
	        $nestad_data[]  = $row['qc_on'];
	        $action='<button class="btn btn-xs btn-danger" id="func'.$row['pgrnp_id'].'" name="func'.$row['pgrnp_id'].'" onclick="rollback('.$row['pgrnp_id'].')" >Roll-Back</button>';
	        if($row['pgrnm_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 rollbackGTNItemToPendingStatus(){
        $id=$this->getId();
        $result=$this->executeSelectSubItemsTable($id);
        if(isset($result['pbi_id'])){
           $main_recode_id=$result['pbi_id']; 
           $data=array(
            'pbi_rollback_status'=>1,
			'finish_status'=>0,
			'pbi_rollback_by'=>$this->session->userdata('ss_user_id'),
			'pbi_rollback_on'=>date('Y-m-d H:i:s'),
		);
		$status=$this->executeUpdateMasterTable($main_recode_id,$data);
		if($status==1){
		  $status=$this->executeDeleteSubItemTable($id);  
		}
		$st = array('status' =>$status,'validation' =>'Rollback','result'=>'null');
            echo json_encode($st);
        }else{
            $st = array('status' =>0,'validation' =>'Not Found','result'=>'null');
            echo json_encode($st);
        }
    }
    
    
    function FinishGTN(){
        $id=$this->getId();
        $result=$this->executeSelectSubItemsTableUsingSecondaryId($id);
        if($result){}else{$result=array();}
        $recode_count=0;
        foreach($result as $row){
            $recode_count++;
            if($row['pgrni_product_type_id']==2){
            $data=array(
            'pgrnm_id'=>$row['pgrnm_id'],
			'pbi_id'=>$row['pbi_id'],
			'product_id'=>$row['product_id'],
			'product_mat_id'=>$row['product_mat_id'],
			'quantity'=>$row['quantity'],
			'pgrnp_id'=>$row['pgrnp_id'],
		    );
		    $this->Manufacture_Preparation_Model->runSaveIntermediateItems($data);
            }
        }
           $data=array(
            'pgrnm_status'=>1,
			'finish_by'=>$this->session->userdata('ss_user_id'),
			'finish_on'=>date('Y-m-d H:i:s'),
		);
		if($recode_count>0){
		$status=$this->executeUpdateItemTable($id,$data);
		$message='Completed';
		}else{
		    $status=0;
		    $message='You Must Select at least 1 Production Batch !';
		}
		$st = array('status' =>$status,'validation' =>$message,'result'=>'null');
            echo json_encode($st);
       
    }
    
     function loadNotCompletedGTN(){
        $data=array();
        $this->load->model('Warehouse_Model');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'not_completed_gtn';
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('manufacture/pending_gtn',$data);
    }
    
    function getListPendingInternalGTN(){
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getPendingInternalGTNBasicDataTable($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->pgrnm_ref_no;
                $row[]               = $products->pgrnm_doc_no;
                $row[]               = $products->pgrnm_date_time;
                 $row[]               = $products->user_first_name;
                $row[]               = $products->warehouse_name;
                $row[]               = $products->pgrnm_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('manufacture_preparation/loadQCPassedProduct?id='. $products->pgrnm_id ).'"  style="cursor: pointer;"><i class="glyphicon fa fa-edit"></i> Update GTN</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 loadRequestAddtionalItems(){
        $id=$this->getId();
        $data=array();
        $data['product_batch_id']=$id;
        $data['details'] = $this->Manufacture_Preparation_Model->runGetProductBatchDetails($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $this->load->view('manufacture/request_add_material',$data);
    }
    
      function getlistAdditionalBatchItem(){
       $this->load->model('Stock_Counter_Model');
       ini_set('display_errors', 1); 
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getPendingAdditionalBatchItemBasicDataTable($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['product_mat_code'];
	        $nestad_data[]  = $row['product_mat_name'];
	        $nestad_data[]  = $row['mpt_name'];
	        $nestad_data[]  = $row['unit_name'];
	        $nestad_data[]  = $row['pbsi_original_cost'];
	         $nestad_data[]  = $row['pbis_qty'];
	          $nestad_data[]  = $row['pbsi_cost_total'];
	          $action='';
	          if($row['request_type']==1){
	              $action='<span class="btn btn-xs btn-success">Original</span>';
	          }else{
	              $action='<span class="btn btn-xs btn-warning">Additional</span> ';
	              if($row['request_type']==2&&$row['pbsi_issue_status']==0){
	                  $action.=' <button class="btn btn-xs btn-danger"  onclick="rollback('.$row['pbsi_id'].')" > <i class="fa fa-trash-o"></i> </button>';
	              }
	          }
	           $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);
        }
   }
  
   public function saveAdditionalBatchMaterial()    {
		$this->load->library('form_validation');
		
		$product_id=$this->input->post('product_id');
		$product_batch_id=$this->input->post('product_batch_id');
		$allocated_quantity=$this->input->post('allocated_quantity');
		$warehouse_id=$this->input->post('warehouse_id');
		$this->form_validation->set_rules('product_id', 'Product', 'required|xss_clean');
		$this->form_validation->set_rules('product_batch_id', 'Batch', 'required|xss_clean');
		$this->form_validation->set_rules('allocated_quantity', 'Quntity', 'required|xss_clean');
		$this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|xss_clean');
		
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        $product=$this->Manufacture_Preparation_Model->runGetProductMAterialDetails($product_id);
        if(isset($product['product_mat_id'])){}else{exit;}
            $data=array(
			'pbi_id'=>$product_batch_id,
			'pbsi_product_mat_id'=>$product_id,
			'pbis_qty'=>$allocated_quantity,
			'pbsi_original_cost'=>$product['product_mat_cost'],
			'pbsi_cost_total'=>$product['product_mat_cost']*$allocated_quantity,
			'request_type'=>2,
		);	
         $last_id=$this->Manufacture_Preparation_Model->runSaveBatchSubItemTable($data);
          $data=array(
			'psnm_warehouse_id'=>$warehouse_id,
			'psnm_user_id'=>$this->session->userdata('ss_user_id'),
			'psnm_date_time'=>date('Y-m-d H:i:s'),
			'psnm_ref_no'=>$this->Common_Model->gen_ref_number('psnm_id','production_store_note_master','STN'),
			'psnm_status'=>1
		);
         $last_stn_mstr_id=$this->Manufacture_Preparation_Model->runSaveSTNMasterTable($data);
          $data=array(
			'psnm_id'=>$last_stn_mstr_id,
			'pbi_id'=>$product_batch_id,
		);
		$last_stn_item_id=$this->Manufacture_Preparation_Model->runSaveSTNItemTable($data);
		$data=array(
			'psnm_id'=>$last_stn_mstr_id,
			'psni_id'=>$last_stn_item_id,
			'pbi_id'=>$product_batch_id,
			'pbsi_id'=>$last_id,
		);
		$this->Manufacture_Preparation_Model->runSaveSTNSubItemTable($data);
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
       
		}
	}
	
	 function loadRemoveRemainingItems(){
        $id=$this->getId();
        $data=array();
        $data['product_batch_id']=$id;
        $data['details'] = $this->Manufacture_Preparation_Model->runGetProductBatchDetails($id);
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'production_material_in_out';
        $this->load->view('manufacture/remove_remaining_material',$data);
    }
    function getlistIssuedBatchItem(){
       $this->load->model('Stock_Counter_Model');
       ini_set('display_errors', 1); 
        $request_data=$this->getClientSideBasicDataTableParameters();
        $result_array=$this->getIssuedBatchItemBasicDataTable($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['product_mat_code'];
	        $nestad_data[]  = $row['product_mat_name'];
	        $nestad_data[]  = $row['mpt_name'];
	        $nestad_data[]  = $row['unit_name'];
	        $nestad_data[]  = $row['unit_price'];
	         $nestad_data[]  = $row['quantity'];
	          $nestad_data[]  = $row['cost'];
	          $action='';
	          if($row['psio_request_type']==3){
	              $action='<span class="btn btn-xs btn-success">Removed Items</span>';
	          }else{
	              $action='<span class="btn btn-xs btn-warning">Original</span> ';
	              if($row['psio_request_type']==1&&$row['pick_up_status']==1){
	                  $action.=' <button class="btn btn-xs btn-danger"  onclick="send_back('.$row['psio_id'].')" > <i class="fa fa-undo">Send Back</i> </button>';
	              }
	          }
	           $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);
        }
   }
   
   
    public function saveSendBackBatchMaterial()    {
		$this->load->library('form_validation');
		
		$issue_id=$this->input->post('id');
		$allocated_quantity=$this->input->post('result');
		$this->form_validation->set_rules('id', 'Product', 'required|xss_clean');
		$this->form_validation->set_rules('result', 'Quntity', 'required|xss_clean');
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
        $sendbak_qty=($allocated_quantity*-1);
        $issued_details=$this->Manufacture_Preparation_Model->runGetMAterialIssueDetails($issue_id);
        $product=$this->Manufacture_Preparation_Model->runGetProductMAterialDetails($issued_details['product_mat_id']);
        if($issued_details['quantity']<$allocated_quantity){
            $st = array('status' =>0,'validation' =>'Invalid Qty');
            echo json_encode($st);
            return false;
        }
        if(isset($product['product_mat_id'])){}else{exit;}
            $data=array(
			'pbi_id'=>$issued_details['pbi_id'],
			'pbsi_product_mat_id'=>$issued_details['product_mat_id'],
			'pbis_qty'=>$sendbak_qty,
			'pbsi_original_cost'=>$product['product_mat_cost'],
			'pbsi_cost_total'=>$product['product_mat_cost']*$sendbak_qty,
			'request_type'=>3,
			'pbsi_issue_status'=>1
		);	
         $last_id=$this->Manufacture_Preparation_Model->runSaveBatchSubItemTable($data);
		$data=array(
			'pbi_id'=>$issued_details['pbi_id'],
			'pbsi_id'=>$issued_details['pbsi_id'],
			'psni_id'=>$issued_details['psni_id'],
			'psnm_id'=>$issued_details['psnm_id'],
			'psoi_id'=>$issued_details['psoi_id'],
			'psom_id'=>$issued_details['psom_id'],
			'product_mat_id'=>$issued_details['product_mat_id'],
			'product_mat_batch_id'=>$issued_details['product_mat_batch_id'],
			'unit_price'=>$issued_details['unit_price'],
			'cost'=>$issued_details['unit_price']*$sendbak_qty,
			'quantity'=>$sendbak_qty,
			'stock_in'=>$allocated_quantity,
			'psio_issue_by'=>$this->session->userdata('ss_user_id'),
			'psio_issue_on'=>date('Y-m-d H:i:s'),
			'stock_out'=>0,
			'psio_request_type'=>3,
			'pick_up_status'=>1,
		);
	$this->Manufacture_Preparation_Model->runSaveSTNIssueItemTable($data);
          $st = array('status' =>1,'validation' =>'Added');
          echo json_encode($st);
            return true;
		}
	}
	
	
	 function getIngredients(){
	     $this->load->model('Stock_Counter_Model');
        $id=$this->getId();
          $items=$this->Manufacture_Preparation_Model->runGetPendingAdditionalBatchItem($id);
           $table_start='<table  class="table"">';
	              $table_head_start='<thead >';
	              $table_head_end='</thead>';
	              $table_end='</table>';
	              $table_body=' <tr><th>INGREDIENTS</th><th data-toggle="tooltip" data-placement="top" title="UNIT OF MEASUREMENTS">UOM</th><th data-toggle="tooltip" data-placement="top" title="REQUIRED QUANTITY">R.QTY</th><th data-toggle="tooltip" data-placement="top" title="CURRANT STOCK">C.STOCK</th></tr>';
	           $currant_stock=0;
          foreach($items as $lab){
                $currant_stock=$this->Stock_Counter_Model->get_stock_balance('',$lab['pbsi_product_mat_id']);
	              $table_body.='<tr><td>'.$lab['product_mat_code'].' - '.$lab['product_mat_name'].' </td><td>'.$lab['unit_name'].'</td><td>'.number_format($lab['pbis_qty'],2,".","").'</td> <td>'.number_format($currant_stock,2,".","").'</td></tr>';
	              
          }
           $complete_table=$table_start.$table_body.$table_end;
          $st=array('data'=>$complete_table);
          
          
          
          
	
            echo json_encode($st);
        
    }
   
 
   
}