<?php

namespace App\Utilities;

class ApiCalls
{
    /**
     * Create a new class instance.
     */
    
    public static function CurlGet($url){
        $get_url = env('APIBASEURL') . $url;
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => $get_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 => 'GET',
          CURLOPT_HTTPHEADER => array(),
        ));

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

    }
    public static function CurlPost($data, $url){
        $post_url = env('APIBASEURL') . $url;
        $header_part = '';
        $client_id = session('current_user.org_id');
        if ($url == 'sms/send') {
            // code...
            
            $apps_url = "applications/client/$client_id?page=0&size=20&sort=createdAt,desc";
            $result = static::CurlGet($apps_url);
            $result_arr = json_decode($result);
            $api_key = $result_arr->content[0]->apiKey;            
            $header_part = "Authorization: Bearer " . $api_key; //env('SUNKING_APIKEY');
        }

        \Log::info('Request Params :' . $data);
        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => $post_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 => 'POST',
          CURLOPT_POSTFIELDS => $data,
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json', $header_part
          ),
        )); 
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    
    public static function CurlPatch($data, $url){
        $patch_url = env('APIBASEURL') . $url;
        $header_part = '';

        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => $patch_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 => 'PATCH',
          CURLOPT_POSTFIELDS => $data,
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json', $header_part
          ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;

    }
   
    public static function generatePassword($length = 10) {
        return bin2hex(random_bytes($length / 2));
    }
}
