<?php

namespace Shm\ShmHttp;

use Shm\ShmDB\mDB;

class ShmHttp
{
    public static function post(string $url,  $data = [], array $headers = []): ?array
    {

        if (is_array($data) || is_object($data)) {
            $data = mDB::replaceObjectIdsToString($data);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge(['Content-Type: application/json'], $headers));
        $result = curl_exec($ch);
        if ($result === false) {
            throw new \Exception("Error: " . curl_error($ch));
        }
        curl_close($ch);
        $result = json_decode($result, true);



        return $result;
    }

    public static function get(string $url, array $headers = []): mixed
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
