<?php
namespace app\wpRestApiEvent;

/**
 * Class HttpClient
 * @package app\wpRestApiEvent
 */
class HttpClient
{
    /**
     * @param  string  $eventType
     * @param $data
     *
     * @return null|string
     */
    public function logEvent(string $eventType, $data)
    {
        $data['event']    = [
            'slug' => $eventType,
        ];

        return $this->doPostRequest(LAWCARTA_WP_REST_API_EVENT_LOG_URL, $data);
    }

    /**
     * @param $data
     * @return null|string
     */
    public function sendRequest($data)
    {
        return $this->doPostRequest(LAWCARTA_WP_REST_API_REQUEST_URL, $data);
    }

    /**
     * @param $sysLogId
     * @param $data
     * @return string|\WP_Error
     */
    public function sendResponse($sysLogId, $data)
    {
        $data['sysLogId'] = $sysLogId;
        return $this->doPostRequest(LAWCARTA_WP_REST_API_RESPONSE_URL, $data);
    }

    /**
     * @param $url
     * @param $data
     * @return string|\WP_Error
     */
    private function doPostRequest($url, $data)
    {
        $response = wp_remote_post($url, [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($data),
            'sslverify' => false

        ]);
        $sysLogId = null;
        /** @var \WP_HTTP_Requests_Response $httpResponse */
        if(!empty($response['http_response'])){
            $httpResponse = $response['http_response'];
            if ($httpResponse->get_status() == 200) {
                $body = isset($response['body']) ? json_decode($response['body'], true) : null;
                $sysLogId = $body['sysLogId'] ?? null;
            }
        }

        return $sysLogId;
    }

    /**
     * @return HttpClient
     */
    public static function create()
    {
        return new self();
    }
}