<?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']) && isset($_POST['batch_perc'])) {
        $created_batch_id = $_POST['created_batch_id'];
        $created_qty = $_POST['created_qty']; 
        $batch_percentage = $_POST['batch_perc']; 
        $batch_perc = number_format($batch_percentage, 2);
        $totalCost = 0;
        $sumOfCosts = 0;

        // Fetch data from batch_tracking table using created_batch_id
        $filterBatchTracking = " WHERE created_batch_id = '$created_batch_id'";
        $batchTrackingData = BatchSetup::GetBatchTrackingData($filterBatchTracking);

        if ($batchTrackingData) {
            $sum_detucted_qty = 0; 
            $sumwastage_qty = 0;

            foreach ($batchTrackingData as $tracking) {
                $reserved_qty_format = $tracking->reserved_qty;
                $reserved_qty = number_format($reserved_qty_format, 2);
                $stock_id = $tracking->stock_id;

                // Fetch price from ingredient_stock table using stock_id
                $ingredientStock = IngredientStock::GetStockById($stock_id);
                $price_format = $ingredientStock->price;
                $price = number_format($price_format, 2);

                // Multiply reserved_qty by price
                $cost_before_percentage = $reserved_qty_format * $price_format;
                $sumOfCosts += $cost_before_percentage;
                $sumOfCosts_format = number_format($sumOfCosts, 2);
            }

            // Fetch data from batch_tracking table using created_batch_id and deductible condition
            $filterdetuctedIng = "AND bt.created_batch_id = '$created_batch_id'";
            $ingredientDetails = BatchSetup::GetDeductedIngQuantity($filterdetuctedIng);

            foreach ($ingredientDetails as $detail) {
                $reserved_qty1 = $detail->reserved_qty;
                $deducted_qty_format = $reserved_qty1 - (($batch_perc / 100) * $reserved_qty1);
                $sum_detucted_qty += $deducted_qty_format;
                $wastage_qty_format = ($batch_perc / 100) * $reserved_qty1;
                $sum_wastage_qty += $wastage_qty_format;
            }

            $batchData = BatchSetup::GetBatchIdByCreatedBatchId($created_batch_id);
            if ($batchData) {
                $batch_id = $batchData['batch_id'];
                $product_id = $batchData['product_id'];
                $product_unit_weight = $batchData['product_In_Kg']; 

                // Calculate total produced quantity
                $total_produce_quantity = $sum_detucted_qty / $product_unit_weight;
                $total_produce_quantity_formatted = number_format($total_produce_quantity, 2);

                // Calculate unit cost produced
                $unit_cost_produced = $sumOfCosts / $total_produce_quantity;
                $unit_cost_produced = number_format($unit_cost_produced, 2);
            } 

            // Insert data into produced_products table
            $producedProductData = [
                'product_id' => $product_id,
                'created_batch_id' => $created_batch_id,
                'total_produced_quantity' => $total_produce_quantity,
                'remaining_quantity' => $total_produce_quantity,
                'used_quantity' => 0,
                'unit_cost_produced' => $unit_cost_produced,
                'production_date' => date('Y-m-d'),
                'batch_perc' => $batch_perc,
                'total_cost' => $sumOfCosts,
                'wastage_qty' => $sum_wastage_qty,
            ];

            $producedProductId = BatchSetup::AddProducedProduct($producedProductData);
            if ($producedProductId) {
                // Set a session variable to show a success message on the redirect page
                $_SESSION['success_msg'] = 'Production calculation completed successfully!';
                
                // Redirect to production.php
                header("Location: production.php");
                exit();
            } else {
                $output = "<div class='alert alert-error'>Failed to complete production calculation. Please try again.</div>";
            }
        } else {
            $output = "<div class='alert alert-error'>No data found in batch_tracking for the given batch ID.</div>";
        }
    }
}
?>

<!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">
                <h3>Production Calculation</h3>
                <hr>
                <?php echo $output; ?>
                <form action="" method="POST">
                    <div class="row margin">
                        <div class="input-field col s12">
                            <input type="number" name="batch_perc" id="batch_perc" required>
                            <label for="batch_perc">Enter Percentage *</label>
                        </div>
                    </div>
                    <div class="row margin">
                        <div class="input-field col s12">
                            <input type="text" name="batch_date" id="batch_date" class="datepicker" value="<?= date('d-m-Y') ?>" required>
                            <label for="batch_date">Batch Date *</label>
                        </div>
                    </div>
                    <input type="hidden" name="batch_id" value="<?= $_POST['batch_id']; ?>">
                    <input type="hidden" name="created_qty" value="<?= $_POST['created_qty']; ?>">
                    <input type="hidden" name="created_batch_id" value="<?= $_POST['created_batch_id']; ?>">
                    <div class="row margin">
                        <div class="input-field col s12">
                            <button type="submit" class="btn waves-effect waves-light">Submit</button>
                            <button type="button" class="btn waves-effect waves-light" onclick="location.href='production.php'">Cancel</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php include('../includes/inc_footer.php'); ?>
    <?php include('../includes/inc_js.php'); ?>
    <script type="application/javascript">
        $(document).ready(function(){
            $('#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>
