<?php
include("../../classes/manager.class.php");

$m = new Manager();
$output = '';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['created_batch_id'])) {
        // Missing closing PHP tag to output HTML
?>


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

<head>
    <title>Production Calculation</title>
    <?php include('../includes/inc_head.php'); ?>
</head>

<body>
    <?php include('../includes/inc_top.php'); ?>
    <div class="container">
        <div class="row">
            <div class="col s12">
                        <?php
                $created_batch_id = $_POST['created_batch_id'];
                $producedproduct = ProducedProducts::GetProducedProductByCreatedBatchId($created_batch_id);
      		//	$producedquantity = $producedproduct->total_produced_quantity;   
       
      			$product_id =  $producedproduct->product_id;    
      			$unitcostproduced = $producedproduct->unit_cost_produced;
      			$totalproducedquantity = $producedproduct->total_produced_quantity;	
      			
      			
      			$productinfo = ProductSetup::GetProductSetupById($product_id);
      			$productname = $productinfo->name;
      			$productweight = $productinfo->carton_pieces;
      			
      			//get batch name code
      			$batchDetails = BatchSetup::GetCreatedBatchSetupById($created_batch_id);
       $json_data = json_encode($batchDetails);
        error_log("Fetched product data: " . $json_data);
      			$batch_id = $batchDetails->batch_id;
      			$batchinfo = BatchSetup::GetBatchById($batch_id);
      			$batchname = $batchinfo->name;

      ?>
    
                <h4><?php echo  $batchname?> - Porudced Quantity - <?php echo  $totalproducedquantity?> - Total Carton: <?php echo  $totalproducedquantity / $productweight?> </h4>
              <a href="created_batch_Setup.php" class="btn waves-effect waves-light">
    Back to Batch Setup
</a>

                <hr>
                <?php
                $created_batch_id = $_POST['created_batch_id'];
              //  $filter = " WHERE created_batch_id = $created_batch_id";
                $batchDetails = BatchSetup::GetBatchTrackingDetailsByCreatedBatchId($created_batch_id);
    		//	$producedproduct = ProducedProducts::GetProducedProductByCreatedBatchId($created_batch_id);
      		//	$producedquantity = $producedproduct->	total_produced_quantity;
      
   //   echo "<pre>";
//print_r($batchDetails);
//echo "</pre>";

                if ($batchDetails) {
                    $countingSr = 1;
                    echo '<table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th>Ingredient Name</th>
                            <th>Used Quantity</th>
                            <th>Unit Price</th>
    						<th>Total Cost</th>
                        </tr>
                        </thead>
                        <tbody>';

                    foreach ($batchDetails as $detail) {
                        $ingredient_id = $detail->ingredient_id;
                       // $batch_date = date('Y-m-d', strtotime($detail->created_date));
                        $ingredient_name = $detail->ingredient_name;
                        $reserved_qty = $detail->reserved_qty;
                        $batch_id = $detail->batch_id;
                        $created_batch_id = $detail->created_batch_id;
                      
                      	$stock_id = $detail->stock_id;
                        $stock = IngredientStock::GetStockById($stock_id);
                        $unit_price = $stock ? $stock->price : 0;
                      	$total_price = round($reserved_qty * $unit_price, 2);

                        echo '<tr style="border: 1px solid #666;">
                            <td>' . $countingSr . '</td>
                            <td>' .  $ingredient_name . '</td>
                            <td>' .    $reserved_qty . '</td>
                            <td>' . number_format($unit_price, 2) . '</td>
        					<td>' . number_format($total_price, 2) . '</td>
                            
                        </tr>';
						$grandTotalCost += $total_price;
                        $countingSr++;
                    }
                  	echo '<tr style="font-weight:bold;">
                              <td colspan="4" style="text-align:right;">Total Ingredient Cost</td>
                              <td>' . number_format($grandTotalCost, 2) . '</td>
                          </tr>';

                    echo '</tbody>
                        </table>
                        
                        <br>';
                

                } else {
                    echo "<p>No data found for the selected Created Batch.</p>";
                }
                ?>
            </div>
        </div>
    </div>

    <?php
    } // Closing the POST check here
} // Closing the request method check here
?>

    <?php include('../includes/inc_footer.php'); ?>
    <?php include('../includes/inc_js.php'); ?>
    <script type="application/javascript">
        $(document).ready(function () {
            // Initialize the datepicker with the current date
            $('#batch_date').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
                selectYears: 15,
                onStart: function () {
                    var today = new Date('<?= date('Y-m-d') ?>');
                    this.set('select', today);
                }
            });
        });
    </script>
</body>

</html>
