<?php

$baseUrl = getenv('WH_OPEN_API_BASE_URL') ?: 'https://open.whbdvr.com';
$appKey = getenv('WH_OPEN_API_APP_KEY') ?: 'replace-with-app-key';
$appSecret = getenv('WH_OPEN_API_APP_SECRET') ?: 'replace-with-app-secret';

function signOpenApiRequest(string $method, string $path, string $timestamp, string $appSecret): string
{
    $signingKey = hash('sha256', $appSecret);
    $payload = strtoupper($method) . "\n" . $path . "\n" . $timestamp;
    return hash_hmac('sha256', $payload, $signingKey);
}

function requestOpenApi(string $method, string $path): array
{
    global $baseUrl, $appKey, $appSecret;

    $timestamp = (string) round(microtime(true) * 1000);
    $signature = signOpenApiRequest($method, $path, $timestamp, $appSecret);
    $headers = [
        'X-WH-App-Key: ' . $appKey,
        'X-WH-Timestamp: ' . $timestamp,
        'X-WH-Signature: ' . $signature,
    ];

    $ch = curl_init($baseUrl . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => strtoupper($method),
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);

    $body = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($body === false || $status < 200 || $status >= 300) {
        throw new RuntimeException('Open API request failed: ' . $status . ' ' . $error . ' ' . (string) $body);
    }

    return json_decode((string) $body, true) ?: [];
}

$tenantProfile = requestOpenApi('GET', '/api/external/open-api/tenant/profile');
$orders = requestOpenApi('GET', '/api/external/open-api/orders');
$businessTrend = requestOpenApi('GET', '/api/external/open-api/reports/business-trend');
$productSalesRanking = requestOpenApi('GET', '/api/external/open-api/reports/product-sales-ranking');
$memberGrowthRetention = requestOpenApi('GET', '/api/external/open-api/reports/member-growth-retention');
$businessMetricGroups = requestOpenApi('GET', '/api/external/open-api/reports/business-metric-groups');

echo "tenantProfile:\n";
print_r($tenantProfile);
echo "orders:\n";
print_r($orders);
echo "businessTrend:\n";
print_r($businessTrend);
echo "productSalesRanking:\n";
print_r($productSalesRanking);
echo "memberGrowthRetention:\n";
print_r($memberGrowthRetention);
echo "businessMetricGroups:\n";
print_r($businessMetricGroups);
