<?php

/**
 * @return bool
 */
function shopify_verify_webhook_hmac(string $rawBody, ?string $hmacHeader, string $secret): bool
{
    if ($secret === '' || $hmacHeader === null || $hmacHeader === '') {
        return false;
    }
    $calculated = base64_encode(hash_hmac('sha256', $rawBody, $secret, true));
    return hash_equals($hmacHeader, $calculated);
}

/**
 * @return string|null Product type string, or null if request failed
 */
function shopify_get_product_type(string $shopDomain, string $accessToken, int $productId): ?string
{
    $shopDomain = preg_replace('#^https?://#', '', rtrim($shopDomain, '/'));
    $url = sprintf(
        'https://%s/admin/api/%s/products/%d.json',
        $shopDomain,
        SHOPIFY_ADMIN_API_VERSION,
        $productId
    );

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-Shopify-Access-Token: ' . $accessToken,
        ],
        CURLOPT_TIMEOUT => 30,
    ]);
    $response = curl_exec($ch);
    $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false || $code !== 200) {
        return null;
    }
    $data = json_decode($response, true);
    if (!is_array($data) || !isset($data['product']['product_type'])) {
        return null;
    }
    return (string) $data['product']['product_type'];
}


