<?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') {
    $user = $json->username ?? null; // Using null coalescing operator for safety
    $total_amount = $json->total_amount ?? null;
    $address_id = $json->address_id ?? null;

    // Ensure the required data is present
    if ($user && $total_amount !== null) {
        // Start a transaction
        $connect->begin_transaction();

        try {
            // Insert into transactions
            $stmt = $connect->prepare("INSERT INTO transactions (username, total_amount, address_id) VALUES (?, ?, ?)");
            $stmt->bind_param("sii", $user, $total_amount, $address_id);
            $stmt->execute();
            $stmt->close();

            // Update user points
            $stmt = $connect->prepare("UPDATE users SET point = point - ? WHERE username = ?");
            $stmt->bind_param("is", $total_amount, $user);
            $stmt->execute();
            $stmt->close();

            // Commit the transaction
            $connect->commit();
            echo json_encode(["message" => "Transaction 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();
