<?php

namespace App\Services;

use App\Models\CompanyApi;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class GuzzleHttpService
{
    protected $baseUri = '';
    protected $client;
    private $token;

    public function __construct(){
        $companyApi = CompanyApi::where('company_id', auth()->user()->company_id ?? '')
            ->where('status', 1)
            ->first();
        if (!isset($companyApi)){
            return;
        }

        $this->client = new Client([
            'base_uri' => $companyApi->uri,
            'timeout' => 2.0,
            'cookies' => true,
            'headers' => [
                'User-Agent' => app()->environment() . '-bukkenkanri.com/1.0',
                'Accept' => 'application/json',
                'Authorization' => "Bearer " . $this->token
            ]
        ]);
    }

    public function getRequest($url, $params){
        if (!isset($this->client)){
            return  [];
        }
        try {
            return $this->client->request('GET', $url, ['query'=> $params]);
        }catch (ClientException $e) {

        }catch (RequestException $rq){

        }catch (\Exception $e){
        }
        return [];
    }

    public function postRequest($url, $data){
        if (!isset($this->client)){
            return  [];
        }
        if($data instanceof Collection)
            $data = $data->toArray();

        foreach ($data as $key => $val){
            $ar_fields = ['created_at', 'updated_at', 'close_date', 'from_event', 'to_event', 'parking_yes_cost_date', 'conf_day', 'parking_out_cost_date'];
            foreach ($ar_fields as $key){
                if(isset($data[$key])){
                    if(strtotime($data[$key]) < 0 || strtotime($data[$key]) == false){
                        $data[$key] = null;
                    }
                }
            }
        }

        try {
           $res = $this->client->request('POST', $url, [
                'json' => $data
            ]);
           return $res->getBody();
        }catch (ClientException $e) {
            Log::debug(json_encode($e->getMessage()));
        }catch (RequestException $rq){
            //dd($rq);
            Log::debug(json_encode($rq->getMessage()));
        }catch (\Exception $e){
            Log::debug(json_encode($e->getMessage()));
        }
        return [];
    }
}
