<?php

namespace BitApps\PiPro\src\Integrations\Emailit;

use BitApps\PiPro\Deps\BitApps\WPKit\Helpers\JSON;

if (!\defined('ABSPATH')) {
    exit;
}

class EmailitService
{
    private $http;

    private $baseUrl;

    /**
     * EmailitService constructor.
     *
     * @param mixed $httpClient
     */
    public function __construct($httpClient)
    {
        $this->http = $httpClient;
        $this->baseUrl = 'https://api.emailit.com/v1';
    }

    /**
     * Create Emailit audience.
     *
     * @param array $fieldMapData
     *
     * @return array
     */
    public function createAudience($fieldMapData)
    {
        $endPoint = $this->baseUrl . '/audiences';
        $audienceData = JSON::encode($fieldMapData);
        $response = $this->http->request($endPoint, 'POST', $audienceData);

        return [
            'response'    => $response,
            'payload'     => $audienceData,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    /**
     * Subscribe a member to Emailit audience.
     *
     * @param string $tokenId
     * @param array $subscriberData
     *
     * @return array
     */
    public function subscribeToAudience($tokenId, $subscriberData)
    {
        $endPoint = $this->baseUrl . '/audiences/subscribe/' . $tokenId;
        $subscriberPayload = JSON::encode($subscriberData);
        $response = $this->http->request($endPoint, 'POST', $subscriberPayload);

        return [
            'response'    => $response,
            'payload'     => $subscriberPayload,
            'status_code' => $this->http->getResponseCode()
        ];
    }

    /**
     * Send email via Emailit.
     *
     * @param array $emailData
     * @param mixed $htmlFormatSwitch
     *
     * @return array
     */
    public function sendEmail($htmlFormatSwitch, $emailData)
    {
        if (isset($emailData['body']) && $emailData['body'] !== null && $htmlFormatSwitch === true) {
            $emailData['html'] = $emailData['body'];
        } elseif (isset($emailData['body'])) {
            $emailData['text'] = $emailData['body'];
        }

        if (isset($emailData['body'])) {
            unset($emailData['body']);
        }

        $endPoint = $this->baseUrl . '/emails';
        $emailPayload = JSON::encode($emailData);
        $response = $this->http->request($endPoint, 'POST', $emailPayload);

        return [
            'response'    => $response,
            'payload'     => $emailPayload,
            'status_code' => $this->http->getResponseCode()
        ];
    }
}
