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

include 'conexion.php';

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $json->username;
    $product_id = $json->product_id;
    $quantity = $json->quantity;
    $total_price = $json->total_price;

    // Ensure the required data is present
    if (isset($username) && isset($product_id) && isset($quantity) && isset($total_price)) {
        // Get the latest transaction_id for the given username
        $stmt = $connect->prepare("SELECT transaction_id FROM transactions WHERE username = ? ORDER BY transaction_date DESC LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->bind_result($transaction_id);
        $stmt->fetch();
        $stmt->close();

        if ($transaction_id) {
            // Prepare to update the transaction detail
            $stmt = $connect->prepare("INSERT INTO transaction_items (transaction_id, product_id, quantity, total_price) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("isid", $transaction_id, $product_id, $quantity, $total_price);

            // Execute the insert and check if successful
            if ($stmt->execute()) {
                // Reduce the product quantity
                $stmt = $connect->prepare("UPDATE products SET quantity = quantity - ? WHERE product_id = ?");
                $stmt->bind_param("is", $quantity, $product_id);

                if ($stmt->execute()) {
                    echo json_encode(["message" => "Transaction detail updated and product quantity reduced successfully."]);
                } else {
                    echo json_encode(["error" => "Error updating product quantity: " . $stmt->error]);
                }
            } else {
                echo json_encode(["error" => "Error updating transaction detail: " . $stmt->error]);
            }

            $stmt->close();
        } else {
            echo json_encode(["error" => "No transaction found for this user."]);
        }
    } else {
        echo json_encode(["error" => "Invalid input data"]);
    }
} else {
    echo json_encode(["error" => "Invalid request method"]);
}

$connect->close();
