<?php

class SyncCurl {

    private static $auth_user = 'admin@onlinelegalindia.com';
    private static $auth_token = '4Aialdfu4pe10ee4c515cd3d7ai2rYxWQ';
    public static $url = null;
    public static $params = [];
    public static $method='POST';
    public static $header= [];

    private function __construct () {}

    public static function url(string $url) {
        $c = new Self;
        self::$url = $url;
        self::$header = [];
        self::$method = 'POST';
        self::$params = [];
        return $c;
    }

    public function send() {
        return $this->curl();
    }

    public function withParam(array $params) {
        $c = new Self;
        self::$params = $this->buildParam($params);
        self::$header = array(
                'Content-Type: application/json'
            );
        return $c;
    }

    public function withPostData(array $params) {
        $c = new Self;
        self::$params = $params;
        return $c;
    }

    public function withMethod(string $method){
        $c = new Self;
        self::$method = $method;
        return $c;
    }

    public function withHeader(array $header) {
        $c = new Self;
        self::$header = $header;
        return $c;
    }

    public function withDefaultHeader(){
        $c = new Self;
        $default = [
                        'auth_user: '.self::$auth_user,  
                        'auth_token: '.self::$auth_token  
                    ];
        self::$header = array_merge(self::$header,$default); 
        return $c;
    }

    public function withDefaultParam(){
        $c = new Self;
        self::$params = array_merge(self::$params,$this->defaultParam());
        return $c;
    }

    private function curl() {
        // echo self::$url.'<br>'.self::$method.'<br>';
        // print_r(self::$params);die();
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => self::$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 => self::$method,
            CURLOPT_POSTFIELDS => self::$params,
            CURLOPT_HTTPHEADER => self::$header,
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        return $response;
        
    }

    private function buildParam($params) {
        return json_encode(['body' => array_merge($this->defaultParam(), $params)]);
    }

    private function defaultParam() {
        return [
            'auth_user'     => self::$auth_user,
            'auth_token'    => self::$auth_token
        ];
    }
}

