<?php

namespace Digtective\Connectors;

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

class DigtectiveCoreConnector{
    private Client $client;
    private string $token;

    public function __construct(string $token){
        $baseUri = "https://api-digger-v2.digtective.com/digger-core-api/";
        $this->client = new Client(['base_uri' => $baseUri]);
        $this->token = $token;
    }

    public function createFormSubmission(array $bodyParams){
        try{
            $result = $this->client->post(
                'form-submission',
                [
                    "headers"            => ["Authorization" => "Bearer $this->token"],
                    RequestOptions::JSON => $bodyParams,
                ]
            );

            $json_response_obj = json_decode($result->getBody()->getContents());

            error_log(wp_json_encode($result->getBody()->getContents()));

            return $json_response_obj?->data?->formSubmissionId;
        } catch(\Exception $e){
            return $e->getMessage();
        }
    }

    public function updateFormSubmission(string $form_submission_id, array $body_params){
        try{
            $uri = "form-submission/$form_submission_id";

            $result = $this->client->patch(
                $uri,
                [
                    "headers"            => ["Authorization" => "Bearer $this->token"],
                    RequestOptions::JSON => $body_params,
                ]
            );

            error_log(wp_json_encode($result->getBody()->getContents()));
        } catch(\Exception $e){
            error_log($e->getMessage());
            return $e->getMessage();
        }
        return json_decode($result->getBody()->getContents());
    }

    public function validateToken(string $token){
        try{
            $result = $this->client->post(
                'auth/validate-token',
                [
                    RequestOptions::JSON => ["token" => $token],
                ]
            );
        } catch(\Exception $e){
            return $e->getMessage();
        }

        return json_decode($result->getBody()->getContents());
    }
}
