<?php
if (!defined('ABSPATH')) exit;

/**
 * Minimal Asana HTTP helper with retry/backoff + timing.
 * Returns ['code'=>int,'body'=>string,'ms'=>int]
 */
function afb_asana_request(string $method, string $url, string $pat, array $opts = [], int $retries = 3, int $retry_delay_ms = 400): array {
    $start = microtime(true);
    $headers = $opts['headers'] ?? [];
    $headers[] = "Authorization: Bearer $pat";

    $ch = curl_init($url);
    $ca = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST  => strtoupper($method),
        CURLOPT_HTTPHEADER     => $headers,
    ];

    if (isset($opts['json'])) {
        $ca[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
        $ca[CURLOPT_POSTFIELDS]   = json_encode(['data'=>$opts['json']]);
    } elseif (isset($opts['fields'])) {
        $ca[CURLOPT_POSTFIELDS] = $opts['fields'];
    }

    $attempt = 0; $respBody = ''; $code = 0;
    do {
        curl_setopt_array($ch, $ca);
        $respBody = curl_exec($ch);
        $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($code >= 200 && $code < 300) break;
        $attempt++;
        if ($attempt <= $retries && in_array($code, [0, 408, 425, 429, 500, 502, 503, 504], true)) {
            usleep($retry_delay_ms * 1000);
        } else break;
    } while (true);

    curl_close($ch);
    $ms = (int)round((microtime(true) - $start) * 1000);
    return ['code'=>$code,'body'=>$respBody,'ms'=>$ms];
}
