<?php
header("Content-Type: application/json");

require("dbcon.php");
// ? Receive JSON POST Request
$data = json_decode(file_get_contents("php://input"), true);

$transaction_ref = isset($data['transaction_ref']) ? trim($data['transaction_ref']) : null;
$emailOrPhone = isset($data['emailOrPhone']) ? trim($data['emailOrPhone']) : null;

// ? Validate required fields
if (!$transaction_ref || !$emailOrPhone) {
    echo json_encode([
        "success" => false,
        "message" => "Missing transaction_ref or emailOrPhone",
        "data" => $data
    ]);
    exit;
}

// ? Fetch transaction details
$sql = "SELECT transaction_ref, amount, recipientName, toAccount, 
               recipientBank, fromAccount, status, note, created_at
        FROM transactions 
        WHERE transaction_ref = :ref 
        AND (emailOrPhone = :emailOrPhone)
        LIMIT 1";

$stmt = $pdo->prepare($sql);
$stmt->bindParam(":ref", $transaction_ref);
$stmt->bindParam(":emailOrPhone", $emailOrPhone);

$stmt->execute();
$receipt = $stmt->fetch(PDO::FETCH_ASSOC);

if ($receipt) {
    echo json_encode(["success" => true, "data" => $receipt]);
} else {
    echo json_encode([
        "success" => false,
        "message" => "Receipt not found or does not belong to this user"
    ]);
}
?>
