<?php

class ServiceDirectClient
{
    private array $cfg;

    public function __construct(array $config)
    {
        $this->cfg = $config;
    }

    /**
     * SD Ping: POST https://api.servicedirect.com/partners/request
     */
    public function ping(array $payload): array
    {
        $url = $this->cfg['servicedirect']['endpoints']['ping'];
        return $this->requestJson($url, $payload);
    }

    /**
     * SD Accept/Post: POST https://api.servicedirect.com/partners/request/<request_id>/accept
     */
    public function accept(int|string $requestId, array $payload): array
    {
        $base = $this->cfg['servicedirect']['endpoints']['post_base'];
        $url  = rtrim($base, '/') . '/' . urlencode((string)$requestId) . '/accept';

        return $this->requestJson($url, $payload);
    }

    private function requestJson(string $url, array $payload): array
    {
        $ch = curl_init($url);

        $json = json_encode($payload);
        $headers = [
            'Content-Type: application/json',
            'Accept: application/json',
        ];

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $json,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_TIMEOUT        => 8,  // SD can take up to ~6 sec
        ]);

        $raw  = curl_exec($ch);
        $err  = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        $decoded = null;
        if (is_string($raw) && $raw !== '') {
            $decoded = json_decode($raw, true);
        }

        return [
            'ok' => ($err === '' && $code >= 200 && $code < 300 && is_array($decoded)),
            'http_code' => $code,
            'error' => $err ?: null,
            'raw' => $raw,
            'json' => is_array($decoded) ? $decoded : null,
        ];
    }
}
