<?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 = $batch_percentage;
        $totalCost = 0;
        $sumOfCosts = 0;
		$batch_date = date('Y-m-d', strtotime($_POST['batch_date']));

        // 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;  // Ensure sumwastage_qty is initialized

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

                // Fetch price from ingredient_stock table using stock_id
                $ingredientStock = IngredientStock::GetStockById($stock_id);
                $price = $ingredientStock->price;
              //  $price = number_format($price_format, 2);
                $ingredient_id = $ingredientStock->ingredient_id;
                // Multiply reserved_qty by price first
              //  $cost_before_percentage = $reserved_qty_format * $price_format;
               $cost_before_percentage = $reserved_qty * $price;
                $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;
				if($batch_perc > 0){
                // Apply deduction only to deductible ingredients
                $deducted_qty = $reserved_qty1 - (($batch_perc / 100) * $reserved_qty1);
               // $deducted_qty = number_format($deducted_qty_format, 2);
                $sum_detucted_qty += $deducted_qty;
                $wastage_qty_format = ($batch_perc / 100) * $reserved_qty1;
                $sumwastage_qty += $wastage_qty_format;  // Accumulating wastage
               // $wastage_qty = number_format($wastage_qty_format, 2);
               // $sumwastage_qty_format = number_format($sumwastage_qty, 2);
                }
            }
          


            $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']; // Use raw value for calculation

                // Calculate total produced quantity
                $total_produce_quantity = $sum_detucted_qty / $product_unit_weight;
                // Now format the total produced quantity for display
                $total_produce_quantity_formatted = number_format($total_produce_quantity, 2);
                // Calculate unit cost produced
                $unit_cost_produced = $sumOfCosts / $total_produce_quantity; // Calculate without formatting
                $unit_cost_produced = number_format($unit_cost_produced, 2); // Format the result for display
            }

            // 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, // Initially, the remaining quantity is the same as total produced quantity
                'used_quantity' => 0, // Initially, no quantity is used
                'unit_cost_produced' => $unit_cost_produced,
                'production_date' => $batch_date, // Assuming production date is today's date
                'batch_perc' => $batch_perc,
                'total_cost' => $sumOfCosts,
                'wastage_qty' => $sumwastage_qty,
            ];

            $producedProductId = BatchSetup::AddProducedProduct($producedProductData);
            if ($producedProductId) 
            
            {
                $_SESSION['success_msg'] = 'Production calculation completed successfully!';

                // Redirect to production.php
                header("Location: production.php");
             //  exit();
            } else 
            
            {
                echo "<script>alert('Failed to create produced product.');</script>";
            }

            // Fetch data from batch_tracking table using created_batch_id
            $filterBatchTracking = "WHERE bt.created_batch_id = '$created_batch_id'";
            $ingredientDetailsAll = BatchSetup::GetDeductedIngQuantityAll($filterBatchTracking);
           echo "<script>alert('ingredientDetailsAll . $ingredientDetailsAll');</script>";
		   echo "<script>console.log('ingredientDetailsAll: $ingredientDetailsAll);</script>";
            $sum_detucted_qty_all = 0;
            $sumwastage_qty_all = 0;

            if ($ingredientDetailsAll) {

                foreach ($ingredientDetailsAll as $detailAll) {

                    $reserved_qty = $detailAll->reserved_qty;
                    $ingredient_id = $detailAll->ingredient_id;
                    $deductible = $detailAll->deductible;

                    // Fetch price from ingredient_stock table using stock_id
                    $stock_id = $detailAll->stock_id;
                    $ingredientStock = IngredientStock::GetStockById($stock_id);
                    $price = $ingredientStock->price;
                    $ingprice_format = $reserved_qty * $price;
                    $ingprice = number_format($ingprice_format);

                    // Apply deduction only to deductible ingredients
                    if ($deductible == 1) {
                        $deducted_qty = $reserved_qty - ($batch_perc / 100) * $reserved_qty;

                        $wastage_qty = ($batch_perc / 100) * $reserved_qty;

                    } elseif (($deductible != 1)) {
                        $deducted_qty = $reserved_qty;
                        echo "<script>console.log('Deducted TEsat: $deducted_qty);</script>";
                        $wastage_qty = 0;
                    }

                    // Debug: Show values after applying deduction


                    // Calculate cost before any deductions
                    $cost_before_percentage = $reserved_qty * $price;
                    $sum_detucted_qty_all += $deducted_qty;
                    $sumwastage_qty_all += $wastage_qty;

                    // Debug: Show calculated costs


                    // Save the processed data into the production_details table
                    $productionDetailData = [
                        'produced_product_id' => $producedProductId,  // Reference to produced product ID
                        'ingredient_id' => $ingredient_id,
                        'reserved_qty' => $reserved_qty,
                        'deducted_qty' => $deducted_qty,
                        'wastage_qty' => $wastage_qty,
                        'cost' => $ingprice_format,
                    ];
                    echo "<script>console.log('Calling AddProductionDetail with Product ID: $producedProductId');</script>";
                    $result = BatchSetup::AddProductionDetail($productionDetailData);


                    if ($result) {
                        echo "<script>console.log('Production Detail Inserted');</script>";
                    } else {
                        echo "<script>alert('Failed to insert production detail');</script>";
                    }
                }
            }



            // Insert data into product_stock_deductions table
            $productStockDeductionData = [
                'produced_product_id' => $producedProductId,
                'deducted_qty' => $sum_detucted_qty,
                'deducted_cost' => $sumOfCosts,
                'deduction_date' => date('Y-m-d'), // Assuming deduction date is today's date
                'tracking_batch_id' => $tracking->id, // Assuming you're using the tracking ID from batch_tracking
            ];

            $productStockDeductionId = BatchSetup::AddProductStockDeduction($productStockDeductionData);

            if ($productStockDeductionId) {
                echo "<script>alert('Product stock deduction data saved successfully!');</script>";
            } else {
                echo "<script>alert('Failed to save product stock deduction data.');</script>";
            }
        } else {
            echo "<script>alert('No data found in batch_tracking for the given batch ID.');</script>";
        }
    }
}

?>

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

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

      $(document).ready(function () {
    $('.datepicker').pickadate({
        format: 'dd-mm-yyyy',  // Ensures display format is correct
        selectMonths: true,
        selectYears: 10,  // Shows a dropdown with 10 years (5 back & 5 forward)
        min: new Date(new Date().getFullYear() - 5, 0, 1), // Minimum date: 5 years back (Jan 1st)
        max: new Date(new Date().getFullYear() + 5, 11, 31), // Maximum date: 5 years ahead (Dec 31st)
        today: 'Today',  
        clear: 'Clear',  
        close: 'Close',  
        closeOnSelect: true // Close on date selection
    });
});

    </script>
</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 value="13">
                        <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 () {
            // 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>