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

// Set response header
header('Content-Type: application/json');

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

// Check if required GET parameter is set
if (!isset($_GET['trans_type'])) {
    echo json_encode(["error" => true, "message" => "Missing trans_type parameter"]);
    exit();
}

$trans_type = $_GET['trans_type'];
$trans_id = isset($_GET['trans_id']) ? $_GET['trans_id'] : null;

try {
    // Build the base query
    $query = "SELECT trans_id, trans_details FROM transactions WHERE trans_type = ?";
    $params = [$trans_type];
    $types = "s";

    // If trans_id is provided, add it to the query
    if (!empty($trans_id)) {
        $query .= " AND trans_id = ?";
        $params[] = $trans_id;
        $types .= "i";
    }

    // Prepare and execute the query
    $stmt = $connect->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    // Fetch result
    if ($row = $result->fetch_assoc()) {
        // Decode trans_details JSON string
        $row['trans_details'] = json_decode($row['trans_details'], true);
        $response["data"] = $row;
        $response["message"] = "Transaction retrieved successfully.";
    } else {
        $response["message"] = "No transaction found.";
    }
} catch (Exception $e) {
    $response["error"] = true;
    $response["message"] = "Error fetching transaction: " . $e->getMessage();
}

// Output JSON response
echo json_encode($response, JSON_PRETTY_PRINT);
?>
