<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Curl{
    function call($params)
    {
        $method = $params['method'] ?? 'GET';
        $url = $params['url'];
        $headers = $params['headers'] ?? [];
        $payload = $params['payload'] ?? [];
        $is_formdata = $params['is_formdata'] ?? FALSE;
        if(!$is_formdata){
            $payload = http_build_query($payload);
        }

        $curl = curl_init();
        $curl_params = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
        ];
        if(!empty($headers)){
            $curl_params[CURLOPT_HTTPHEADER] = $headers;
        }
        if($method == 'POST' && !empty($payload)){
            if($is_formdata){
                $curl_params[CURLOPT_HTTPHEADER][] = 'Content-Type: multipart/form-data';
            }else{
                $curl_params[CURLOPT_HTTPHEADER][] = 'Content-Type: application/x-www-form-urlencoded';
            }
            $curl_params[CURLOPT_POSTFIELDS] = $payload;
        }
        curl_setopt_array($curl, $curl_params);
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response, true);
        return $response;
    }
}
