<?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 incoming values
    $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");
    }

    // Fetch bonds
    $sql = "SELECT Bond_Series, Bond_Number, Bond_Add_Date 
            FROM User_Bond_Add_History 
            WHERE User_ID = ? 
            ORDER BY Bond_Add_Date DESC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    $bonds = [];
    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'];

        $bonds[] = [
            "Bond_Series" => $series,
            "Bond_Number" => $number,
            "Bond_Add_Date" => $date
        ];
    }

    $stmt->close();

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

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

echo json_encode($response);
?>
