<?php

use Illuminate\Support\Facades\Http;

if (!function_exists('reqGest')) {
    function reqGest($method = 'GET', $url, $body = [], $is_with_client = 3,$d_name = "")
    {

        $d_names_1 = [
            'eservices.geststudent.net',
            'eservices.africawebstudent.net',
            'eservices.africawebstudent.org',
            'eservices.africawebstudent.com',
            'eservices.africawebstudent.bj',
        ];

        $d_names_2 = [
            'geststudent.net',
            'africawebstudent.net',
            'africawebstudent.org',
            'africawebstudent.com',
            'africawebstudent.bj',
        ];

        if(in_array($d_name, $d_names_1)){
            $api_key = config('app.api_key');
        }elseif(in_array($d_name, $d_names_2)){
            $api_key = config('app.api_key_2');
        }

        /**
         * 1 => with api_key only
         * 2 => with api_key AND client id
         * 3 => with access_token AND client id
         */
        $headers = [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'User-Agent' => config('app.user_agent')
        ];
        if ($is_with_client == 1) {
            $headers = array_merge($headers, [
                'Authorization' => 'Bearer '.$api_key
            ]);
        } elseif ($is_with_client == 2) { // add here client Key
            $headers = array_merge($headers, [
                'Authorization' => 'Bearer '.$api_key,
                'X-Client-Reference' => config('app.client_key')
            ]);
        } elseif ($is_with_client == 3) { // add here client Key
            $headers = array_merge($headers, [
                'Authorization' => 'Bearer '.config('app.user_access_token'),
                'X-Client-Reference' => config('app.client_key')
            ]);
        }


        $base_url = config('app.gest_base_url');

        switch ($method) {
            case 'GET':
                return Http::withHeaders($headers)->get($base_url . $url)->json();

            case 'POST':
                return Http::withHeaders($headers)->post($base_url . $url, $body)->json();

            case 'PUT':
                return Http::withHeaders($headers)->put($base_url . $url, $body)->json();

            case 'DELETE':
                return Http::withHeaders($headers)->delete($base_url . $url, $body)->json();

            default:
                return null;
        }

    }
}
