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

include 'connection.php';
include '/home/screensh/private/encryption_helper.php'; // AES-256-CBC decrypt
include '/home/screensh/private/privet_key.php';
include 'decrypt_and_validate.php';                     // AES-128-ECB decrypt for Android input

$response = [];

try {
    $uidEnc    = $_POST['User_Id'] ?? '';
    $apiKeyEnc = $_POST['API_Key'] ?? '';

    // Decrypt both
    $userId = decryptData($uidEnc);
    $apiKey = decryptData($apiKeyEnc);

    // Validate API key
    $validation = validateApiKey($apiKey);
    if (!$validation['status']) {
        throw new Exception($validation['message']);
    }
    if (empty($userId)) {
        throw new Exception("User ID required");
    }

    // Step 1: Get all user bonds
    $stmt = $conn->prepare("SELECT Bond_Series, Bond_Number, Bond_Add_Date 
                            FROM User_Bond_Add_History 
                            WHERE User_ID = ?");
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    $matches = [];

    while ($row = $result->fetch_assoc()) {
        $series = decryptSensitive($row['Bond_Series'], $GLOBALS['PRIVATE_KEY']);
        $number = decryptSensitive($row['Bond_Number'], $GLOBALS['PRIVATE_KEY']);
        $date   = $row['Bond_Add_Date'];

        // Step 2: Check against Past_Draw_History
        $checkStmt = $conn->prepare("SELECT id, Draw_Number, Draw_Date, Winner_Position_Number, Winner_Bond_Number 
                                     FROM Past_Draw_History 
                                     WHERE Winner_Bond_Number = ?
                                     ORDER BY id DESC LIMIT 10");
        $checkStmt->bind_param("s", $number);
        $checkStmt->execute();
        $checkRes = $checkStmt->get_result();

        while ($win = $checkRes->fetch_assoc()) {
            $matches[] = [
                "id"                     => $win['id'],
                "Draw_Number"            => $win['Draw_Number'],
                "Draw_Date"              => $win['Draw_Date'],
                "Winner_Position_Number" => $win['Winner_Position_Number'],
                "Winner_Bond_Number"     => $win['Winner_Bond_Number'],
                "Bond_Series"            => $series,
                "Bond_Add_Date"          => $date
            ];
        }
        $checkStmt->close();
    }
    $stmt->close();

    // Limit to 10 items overall
    $matches = array_slice($matches, 0, 10);

    $response = ["status" => "success", "data" => $matches];

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

echo json_encode($response);
?>
