<?php
header('Content-Type: application/json; charset=utf-8');

include 'connection.php';

$response = [];

try {
    $bondNumber = $_POST['Bond_Number'] ?? '';

    if (empty($bondNumber)) {
        throw new Exception("Bond number required");
    }

    // Search in Past_Draw_History
    $stmt = $conn->prepare("SELECT Draw_Number, Draw_Date, Winner_Position_Number 
                            FROM Past_Draw_History 
                            WHERE Winner_Bond_Number = ?");
    $stmt->bind_param("s", $bondNumber);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        // Found winner
        $response = [
            "status" => "success",
            "winner" => true,
            "data" => [
                "Bond_Number" => $bondNumber,
                "Draw_Number" => $row['Draw_Number'],
                "Draw_Date"   => $row['Draw_Date'],
                "Position"    => $row['Winner_Position_Number']
            ]
        ];
    } else {
        // Not found
        $response = [
            "status" => "success",
            "winner" => false,
            "data" => [
                "Bond_Number" => $bondNumber
            ]
        ];
    }

    $stmt->close();

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
} finally {
    $conn->close();
}

echo json_encode($response);
?>
