<?php
ini_set('display_errors', 0);
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

session_start();
ob_start();

require_once('configuration/server_connect.php');
require_once('configuration/all_function.php');

$active_id=$_REQUEST['active_id'];
$menu_id=$_REQUEST['menu_id'];

$get_tr_no=$_REQUEST['tr_no'];
$get_recipe_type=$_REQUEST['recipe_type'];


 // Common Information

$page_title="Batch Production";
$page="1002_batch_production.php?active_id=".$active_id."&menu_id=".$menu_id."";


if(isset($_POST['run_data']))

{

$tr_date=$_POST['tr_date'];
$recipe_type=$_POST['recipe_type'];
$no_of_batch=$_POST['no_of_batch'];

$entry_by =  $_SESSION['user']['id'];
$entry_at = $now=date('Y-m-d H:i:s');


		$YR = date('Y',strtotime($tr_date));
 		$year = date('y',strtotime($tr_date));
  		$month = date('m',strtotime($tr_date));
 		$inv_cy_id = find_a_field($conn,'batch_production_master','max(tr_id)','year="'.$YR.'"')+1;
  		$cy_id = sprintf("%06d", $inv_cy_id);
   		$tr_no=''.$year.''.$month.''.$recipe_type.''.$cy_id;
		$batch_no='BATCH'.$tr_no;


 $ms_ins_sql = 'INSERT INTO batch_production_master (tr_no, tr_id, year, tr_date, batch_no, recipe_type, no_of_batch, entry_at, entry_by) VALUES

("'.$tr_no.'", "'.$inv_cy_id.'",  "'.$YR.'", "'.$tr_date.'", "'.$batch_no.'", "'.$recipe_type.'", "'.$no_of_batch.'", "'.$entry_at.'", "'.$entry_by.'")';
	
mysqli_query($conn,$ms_ins_sql);


header("location:".$page.'&tr_no='.$tr_no.'&recipe_type='.$recipe_type."");

} ?>








<!DOCTYPE html>
<html lang="en">

<!-- ======= <head> ======= -->
 <?php require_once('inc_files/inc_head.php'); ?>
<!-- ======= </head> ======= -->
 <?php
  do_calander('#tr_date');
  ?>
  
<script language="javascript">

function getXMLHTTP() { //fuction to return the xml http object



		var xmlhttp=false;	



		try{



			xmlhttp=new XMLHttpRequest();



		}



		catch(e)	{		



			try{			



				xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");

			}

			catch(e){



				try{



				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");



				}



				catch(e1){



					xmlhttp=false;



				}



			}



		}



		 	



		return xmlhttp;



    }




function TR_calculation(cattle_id){

var total_unit_morning=(document.getElementById('total_unit_morning_'+cattle_id).value)*1; 
var total_unit_afternoon=(document.getElementById('total_unit_afternoon_'+cattle_id).value)*1; 

document.getElementById('total_unit_'+cattle_id).value=(total_unit_morning+total_unit_afternoon);

}




	function update_value(id)
	{
	
var tr_no=(document.getElementById('tr_no').value); 
var batch_date=(document.getElementById('batch_date').value); 
var recipe_type=(document.getElementById('recipe_type').value); 
var no_of_batch=(document.getElementById('no_of_batch').value); 

var item_id=(document.getElementById('item_id_'+id).value); 
var unit_name=(document.getElementById('unit_name_'+id).value);
var unit_price=(document.getElementById('unit_price_'+id).value); 
var batch_qty=(document.getElementById('batch_qty_'+id).value)*1; 
var total_unit_cal=(document.getElementById('total_unit_cal_'+id).value)*1; 
var total_unit=(document.getElementById('total_unit_'+id).value)*1; 

var flag=(document.getElementById('flag_'+id).value); 

var strURL="1002_batch_production_ajax.php?id="+id+"&tr_no="+tr_no+"&batch_date="+batch_date+"&recipe_type="+recipe_type+"&no_of_batch="+no_of_batch+"&item_id="+item_id+"&unit_name="+unit_name+"&unit_price="+unit_price+"&batch_qty="+batch_qty+"&total_unit_cal="+total_unit_cal+"&total_unit="+total_unit+"&flag="+flag;



		var req = getXMLHTTP();



		if (req) {



			req.onreadystatechange = function() {

				if (req.readyState == 4) {

					// only if "OK"

					if (req.status == 200) {						

						document.getElementById('divi_'+id).style.display='inline';

						document.getElementById('divi_'+id).innerHTML=req.responseText;						

					} else {

						alert("There was a problem while using XMLHTTP:\n" + req.statusText);

					}

				}				

			}

			req.open("GET", strURL, true);

			req.send(null);

		}	



}




</script>

<style>
		
		/*.fixed_head{
		 / Important /
  background-color: red;
  position: sticky;
  z-index: 100;
  top: 0;
		}	
	
	table thead  {
  / Important /
  background-color: red;
  position: sticky;
  z-index: 100;
  top: 0;
}*/
	
		</style>
  
<body>

  <!-- ======= Header ======= -->
  <?php require_once('inc_files/inc_header.php'); ?><!-- End Header -->

  <!-- ======= Sidebar ======= -->
   <?php  require_once('inc_files/inc_menu.php'); ?>
   <!-- End Sidebar-->
   
  

  <main id="main" class="main">

    <div class="pagetitle">
      <h1><?php echo $page_title;?></h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="home.php">Home</a></li>
          <li class="breadcrumb-item">Inventory Management</li>
          <li class="breadcrumb-item active"><?php echo $page_title;?></li>
        </ol>
      </nav>
    </div><!-- End Page Title -->
    <section class="section">
      <div class="row">
	  
	<?php if($get_tr_no=="") {?>
		<div class="col-lg-12"> 

          <div class="card">
            <div class="card-body">
             <!-- <h5 class="card-title"><strong><?php echo $page_title;?></strong></h5>-->
			 <br />

              <!-- No Labels Form -->
              <form class="row g-3" action="" method="post" name="codz" id="codz">
                
       
                <div class="col-md-2">
           <label for="first_name" class="form-label"><strong> Date</strong></label> 
			<input type="text" class="form-control" id="tr_date" name="tr_date" required value="<?php echo isset($_REQUEST['tr_date'])?$_REQUEST['tr_date']:date('Y-m-d');?>" >
	
                </div>
                <div class="col-md-5">
			<label for="first_name" class="form-label"><strong> Recipe Type</strong></label> 
           <select id="recipe_type" name="recipe_type" required class="form-select"  style="width: 95%;">
                      <option></option>
 <?php foreign_relation($conn,'recipe_type','id','recipe_type',$_REQUEST['recipe_type'],'id group by id');?>
                    </select>
		
                </div>
                
				<div class="col-md-2">
				<label for="first_name" class="form-label"><strong> Batch Qty</strong></label> 
         <input type="text" class="form-control" id="no_of_batch" name="no_of_batch" required value="<?php echo $_POST['no_of_batch'];?>" >
                </div>
				<div class="col-md-3" align="center">
				
				 <button type="submit" name="run_data" id="run_data" class="btn btn-success rounded-pill btn-sm">&nbsp;<i class="bi bi-filter me-1"></i> Run Report&nbsp;&nbsp;</button>
				</div>
				
                
              </form>

            </div>
          </div>
		
		</div>
	<?php } ?>
		
	  <?php if($get_tr_no>0) {?>
		<div class="col-lg-12"> 

          <div class="card">
            <div class="card-body">
            
			 <br />

              <!-- No Labels Form -->
              <form class="row g-3" action="" method="post" name="codz" id="codz">
                
       <div class="col-md-3">
           <label for="first_name" class="form-label"><strong> Batch No</strong></label> 
		  <?php $ms_sql="SELECT * FROM batch_production_master  WHERE tr_no='".$get_tr_no."'";
		  $ms_data = find_all_field_sql($conn,$ms_sql); ?>
		   
		   <input type="hidden" class="form-control" id="tr_no" name="tr_no" required  readonly="" value="<?php echo $ms_data->tr_no;?>" >
			<input type="text" class="form-control" id="batch_no" name="batch_no" required  readonly="" value="<?php echo $ms_data->batch_no;?>" >
	
                </div>
                <div class="col-md-2">
           <label for="first_name" class="form-label"><strong> Date</strong></label>  
			<input type="text" class="form-control" id="batch_date" name="batch_date" required value="<?php echo $ms_data->tr_date;?>" readonly="" >
	
                </div>
                <div class="col-md-5">
			<label for="first_name" class="form-label"><strong> Recipe Type</strong></label> 
           <select id="recipe_type" name="recipe_type" required class="form-select"  style="width: 95%;">
                      
 <?php foreign_relation($conn,'recipe_type','id','recipe_type',$_REQUEST['recipe_type'],'id="'.$ms_data->recipe_type.'" group by id');?>
                    </select>
		
                </div>
                
				<div class="col-md-2">
				<label for="first_name" class="form-label"><strong> Batch Qty</strong></label> 
         <input type="text" class="form-control" id="no_of_batch" name="no_of_batch" readonly="" value="<?php echo $ms_data->no_of_batch;?>" >
                </div>
				
				
                
              </form>

            </div>
          </div>
		
		</div>
	<?php } ?>
	  
        <div class="col-lg-12"> 

          <div class="card">
            <div class="card-body">
			<br>
			

              <!-- Table with stripped rows id="example" -->
              <table class="table table-sm" style="font-size:12px;"  >
                <thead class="fixed_head">
                  <tr style="text-transform:uppercase; font-size:12px; color:#012970; border-top: 1px solid #CCCCCC; background:#f6f9ff; height:32px;">
                    <th width="13%" scope="col">DATE</th>
                    <th width="20%" scope="col">Product</th>
                    <th width="6%" scope="col">Unit</th>
                    <th width="12%" scope="col" style="white-space:nowrap" ><div align="center">Batch Qty </div></th>
                    <th width="17%" scope="col"><div align="center">Quantity </div></th>
                    <th width="15%" scope="col">Action</th>
                  </tr>
                </thead>
                <tbody>
		<?php
		
		
		if($_POST['tr_date']!=''){
		$tr_date =$_REQUEST['tr_date'];
		}else{
		$tr_date =date('Y-m-d');
		}
		
		
		
		
		 $sql = "select order_no, sum(total_unit) as issue_qty from batch_production_issue where tr_no='".$get_tr_no."' 
		 and recipe_type='".$get_recipe_type."' group by  order_no";
		 $query = mysqli_query($conn,$sql);
		 while($info=mysqli_fetch_object($query)){
  		 $issue_qty[$info->order_no]=$info->issue_qty;
		}
		
		
		
					
					//if($_POST['cattle_id']!='')
//					$cattle_id_con=" and c.cattle_id='".$_POST['cattle_id']."'";
//					
//					if($_POST['shed_no']!='')
//					$shed_no_con=" and c.shed_no='".$_POST['shed_no']."'";
					
		// $sql = "select item_id, percent from cattle_feed_ratio where cattle_type='".$_POST['cattle_type']."' group by  item_id";
//		 $query = mysqli_query($conn,$sql);
//		 while($info=mysqli_fetch_object($query)){
//  		 $percent[$info->item_id]=$info->percent;
//		}
					
						 $sql = 'select  i.item_id, i.item_name, i.cost_price, b.* from  item_info i, bill_of_materials b
						where i.item_id=b.item_id and b.recipe_type="'.$get_recipe_type.'"  group by b.id order by i.item_category, b.id ';
						$query = mysqli_query($conn,$sql);
						while ($data = mysqli_fetch_object($query)) {

					?>
				<?php //if(isset($_POST['run_data'])){ }?>	
                 <tr>
                   <td style="white-space: nowrap;"><?php echo date('d-M-y',strtotime($tr_date));?>				  			   </td>
                   <td><?php echo $data->item_name;?>
				   <input name="item_id_<?php echo $data->id?>" type="hidden" id="item_id_<?php echo $data->id?>"
				   value="<?php echo $data->item_id;?>"  style="width:120px" class="form-control"/>				   </td>
                   <td>
				  <input name="unit_name_<?php echo $data->id?>" type="hidden" id="unit_name_<?php echo $data->id?>"
				   value="<?php echo $data->unit_name;?>"  style="width:120px" class="form-control"/>		
				   <?php echo $data->unit_name;?>
				   <input name="unit_price_<?php echo $data->id?>" type="hidden" id="unit_price_<?php echo $data->id?>"
				   value="<?php echo $data->cost_price;?>"  style="width:100px" class="form-control"/>				   </td>
                   <td style="white-space: nowrap;"><div align="center">
                     <input name="batch_qty_<?php echo $data->id?>" type="text" id="batch_qty_<?php echo $data->id?>"
				   value="<?php echo $data->total_unit;?>"  style="width:70px" class="form-control"/>
                   </div></td>
                   <td>
				   <div align="center">
				   <input name="total_unit_cal_<?php echo $data->id?>" type="hidden" id="total_unit_cal_<?php echo $data->id?>"
				   value="<?php echo $total_unit_cal=($ms_data->no_of_batch*$data->total_unit);?>" style="width:120px" class="form-control"/>
				   
				 
				  <input name="total_unit_<?php echo $data->id?>" type="text" id="total_unit_<?php echo $data->id?>"
				   value="<?php if($issue_qty[$data->id]>0)
				    {echo $issue_qty[$data->id];}else{
					echo $total_unit_cal;
					}?>" style="width:120px" class="form-control"/>
		           </div></td>
                   <td><span id="divi_<?php echo $data->id?>">
			 <?php if($issue_qty[$data->id]>0) {?>
			  <input name="flag_<?php echo $data->id?>" type="hidden" id="flag_<?php echo $data->id?>" value="1" />
			  <input class="form-control" type="button" name="Button" value="Edit"  onclick="update_value(<?php echo $data->id?>)" style="width:80px; height:30px; background-color: #FF3366; font-weight:700; font-size:12px;"/>
			  <? }else{?>
			  <input name="flag_<?php echo $data->id?>" type="hidden" id="flag_<?php echo $data->id?>" value="0" />
			  <input class="form-control" type="button" name="Button" value="Save"  onclick="update_value(<?php echo $data->id?>)" style="width:80px; height:30px; background-color: #28a745; font-weight:700; font-size:12px;"/>
			  <?php }?>
          </span></td>
                 </tr>
                 
                 
				  <?php }?>
				  
				  <!--<tr style="font-size:16px;">
                   <td>&nbsp;</td>
                   <td>&nbsp;</td>
                   <td><div align="center"><strong>Total</strong></div></td>
                   <td>&nbsp;</td>
                   <td><div align="center"><strong><?php echo number_format($tot_morning_qty,2);?></strong></div></td>
                   <td>&nbsp;</td>
                 </tr>-->
                </tbody>
              </table>
			  
			
              <!-- End Table with stripped rows -->

            </div>
          </div>

        </div>

        
      </div>
    </section>

  </main><!-- End #main -->

 <!-- ======= Footer ======= -->
 <?php require_once('inc_files/inc_footer.php'); ?>
<!-- ======= Footer ======= -->

<?php selected_two("#cattle_id"); ?>
<script>
var printCounter = 0;
 
new DataTable('#example', {
    caption: "&copy; Copyright Five Star Farm House Limited. All Rights Reserved",
    layout: {
        topStart: {
            buttons: [
                'copy',
                {
                    extend: 'excel',
                    messageTop:
                        'The information in this table is copyright to Five Star Farm House Limited.'
                },
                {
                    extend: 'pdf',
                    //messageBottom: null
					messageBottom: "Copyright Five Star Farm House Limited. All Rights Reserved"
                },
                {
                    extend: 'print',
                    messageTop: function () {
                        printCounter++;
 
                        if (printCounter === 1) {
                            return 'This is the first time you have printed this document.';
                        }
                        else {
                            return (
                                'You have printed this document ' + printCounter + ' times'
                            );
                        }
                    },
                    messageBottom: "&copy; Copyright Five Star Farm House Limited. All Rights Reserved"
                }
            ]
        }
    }
});
</script>

<!--<script type="text/javascript">
$(document).ready(function() {
    // Check if DataTable is already initialized
    if ($.fn.DataTable.isDataTable('#example')) {
        // If DataTable is already initialized, destroy it
        $('#example').DataTable().destroy();
    }
    
    // Reinitialize DataTable with new options
    $('#example').dataTable({
        'iDisplayLength': 50
    });
});
</script>-->


</body>

</html>