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

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

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

if (isset($_GET['batch_id'])) {
    $batch_id = $_GET['batch_id'];
    $batch = BatchSetup::GetBatchSetupById($batch_id);
    // Convert the PHP date format to match the JavaScript format 'yyyy-mm-dd'
    $batch_date = date('d-m-Y');
  
  $product_id = $batch->product_id;
  
      $availableQty = ProducedProducts::GetTotalQuantityByProductId($product_id);
  
  	$totalAvailableQuantity  =$availableQty->total_remaining_quantity / $availableQty->carton_pieces;
//	echo $totalAvailableQuantity;
  
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['batch_qty'])) {
        $batch_qty = $_POST['batch_qty'];
        $batch_date = date('Y-m-d', strtotime($_POST['batch_date']));
      
        $filterBatch = " WHERE batch_id = '$batch_id'";
        $batchItems = BatchSetup::GetBatchItems($filterBatch);

        $notFound = array();
        $allItemsAvailable = true;

        // First pass: check availability
        foreach ($batchItems as $items) {
            $ing_id = $items->ing_id;
            $required_qty = $batch_qty * $items->qty;

            // Check stock without reserving
            $availableQty = IngredientStock::CheckStockAvailabilityFIFO($ing_id, $required_qty);
            if (bccomp((string)$availableQty, (string)$required_qty, 10) === -1) {
                $ing_name = IngSetup::GetIngSetupById($ing_id)->name;
                $notFound[] = $ing_name;
                $allItemsAvailable = false;
            // error_log("Ingredient ID: $ing_id");
//error_log("Required Qty: " . var_export($required_qty, true) . " (" . gettype($required_qty) . ")");
//error_log("Available Qty: " . var_export($availableQty, true) . " (" . gettype($availableQty) . ")");

                break; // Stop checking further, since one item is not available
            }
        }

        if (!$allItemsAvailable) {
            $output = "<div id='card-alert' class='card orange lighten-5'>
                          <div class='card-content orange-text'>
                            <p>WARNING : <strong>Attention! </strong>Stock Not available for the following ingredients: " . implode(', ', $notFound) . "</p>
                          </div>
                          <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                          </button>
                        </div>";
        } else {
            // Prepare data for the new batch creation
            $batchData = [
                'batch_id' => $batch_id,
                'created_qty' => $batch_qty,
                'created_date' => $batch_date,
            ];

            // Create a new batch in created_batch table
            $created_batch_id = BatchSetup::AddNewBatchCreated($batchData);
            if (!$created_batch_id) {
                echo "<script>alert('Failed to create a new batch in created_batch table');</script>";
                return;
            }

            // Second pass: reserve stock
            foreach ($batchItems as $items) {
                $ing_id = $items->ing_id;
                $required_qty = $batch_qty * $items->qty;

                $reservedQty = IngredientStock::ReserveStockFIFO($ing_id, $required_qty, $batch_id, $created_batch_id);
            }

           // Set a success message and redirect to production/created_batch_Setup.php
            $_SESSION['success_msg'] = "All stock has been reserved successfully, and batch created!";
            header("Location: ../production/batch_setup.php?success&view");
            exit();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Check Batch Quantity</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>Batch Setup - <?php echo $batch->name;?><?php echo "<span style='color: green; font-weight: bold;'> - <strong>Available Stock: " . $totalAvailableQuantity . "</strong></span>"; ?>
</h3>
                <hr>
                <?php echo $output; ?>
                <form action="" method="POST">
                    <div class="row margin">
                        <div class="input-field col s12">
                            <input type="number" name="batch_qty" id="batch_qty" min="1" required>
                            <label for="batch_qty">Enter Batch Quantity *</label>
                        </div>
                    </div>

                    <div class="row margin">
                        <div class="input-field col s12">
                            <!-- Use the converted date format 'Y-m-d' for JavaScript -->
                            <input type="text" name="batch_date" id="datepicker" class="datepicker" value="<?= $batch_date ?>" required>
                            <label for="batch_date">Batch Date *</label>
                        </div>
                    </div>
                    <input type="hidden" name="batch_id" value="<?= $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='batch_setup.php?view'">Cancel</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php include('../includes/inc_footer.php'); ?>
    <?php include('../includes/inc_js.php'); ?>

   
</body>
</html>
