<?php
require('config.php');

// Prepare response array
$response = ["error" => false, "message" => ""];

// Check if required POST data is set
if (!isset($_POST['servedBy']) || !isset($_POST['flag'])) {
    echo json_encode(["error" => true, "message" => "Missing required parameters"]);
    exit();
}

$servedBy = $_POST['servedBy'];
$flag = $_POST['flag'];

// Ensure flag is "placeOrder"
if ($flag !== "placeOrder") {
    echo json_encode(["error" => true, "message" => "Invalid flag"]);
    exit();
}

try {
    // Start transaction
    $connect->begin_transaction();

    // Fetch items from tempShopList based on servedBy
    $query = "SELECT id, quantity FROM tempShopList WHERE servedBy = ?";
    $stmt = $connect->prepare($query);
    $stmt->bind_param("s", $servedBy);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $productID = $row['id'];
        $quantity = (int) $row['quantity'];

        // Check available stock
        $stockQuery = "SELECT quantity FROM stock WHERE id = ?";
        $stockStmt = $connect->prepare($stockQuery);
        $stockStmt->bind_param("s", $productID);
        $stockStmt->execute();
        $stockResult = $stockStmt->get_result();

        if ($stockResult->num_rows === 0) {
            throw new Exception("Stock record not found for product ID: $productID");
        }

        $stockRow = $stockResult->fetch_assoc();
        $availableStock = (int) $stockRow['quantity'];

        // Check if the requested quantity exceeds available stock
        if ($quantity > $availableStock) {
            throw new Exception("Insufficient stock for product ID: $productID (Available: $availableStock, Requested: $quantity)");
        }

        // Reduce stock
        $updateStockQuery = "UPDATE stock SET quantity = quantity - ? WHERE id = ?";
        $updateStockStmt = $connect->prepare($updateStockQuery);
        $updateStockStmt->bind_param("is", $quantity, $productID);
        $updateStockStmt->execute();
    }

    // Commit transaction
    $connect->commit();
    $response["message"] = "Stock updated successfully.";

} catch (Exception $e) {
    $connect->rollback();
    $response["error"] = true;
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
?>
