<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include 'conexion.php';

$getJson = file_get_contents('php://input');
$json = json_decode($getJson);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $product_name = $json->product_name ?? null;
    $quantity = $json->quantity ?? null;
    $user = $json->username ?? null;

    if ($user && $quantity && $user !== null) {
        // Start a transaction
        $connect->begin_transaction();

        try {
            // Insert into transactions
            $stmt = $connect->prepare("INSERT INTO requested_item (product_name, quantity, username) VALUES (?, ?, ?)");
            $stmt->bind_param("sis", $product_name, $quantity, $user);
            $stmt->execute();
            $stmt->close();

            // Commit the transaction
            $connect->commit();
            echo json_encode(["message" => "Success"]);
        } catch (Exception $e) {
            // Rollback the transaction if something failed
            $connect->rollback();
            echo json_encode(["error" => "Error processing transaction: " . $e->getMessage()]);
        }
    } else {
        echo json_encode(["error" => "Invalid input data"]);
    }
} else {
    echo json_encode(["error" => "Invalid request method"]);
}

$connect->close();
