<?php

namespace Mtc\Plugins\NewsletterSignup\Classes;

/**
 * Class CampaignMonitor
 * Newsletter sign-up driver to Campaign Monitor system
 *
 * @package Mtc\Plugins\NewsletterSignup\Classes
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
class CampaignMonitor implements SignUpInterface
{
    /**
     * @var \CS_REST_Subscribers $api the api handler
     */
    private $api;

    /**
     * CampaignMonitor constructor.
     * Initializes the connection with CampaignMonitor API
     *
     * @param \CS_REST_Subscribers $api
     */
    public function __construct(\CS_REST_Subscribers $api)
    {
        $this->api = $api;
    }

    /**
     * Action sign-up of a newsletter on site using CM
     *
     * @param string $email email address to sign up
     * $param array $additional_params any additional params passed to interface
     * @throws \Exception Unsuccessful sign-up message
     * @return bool
     */
    public function signUp($email, $additional_params = [])
    {
        $result = $this->api->add([
            'EmailAddress' => $email,
            'Name' => $additional_params['first_name'].' '.$additional_params['last_name'],
            'Resubscribe' => true,
        ]);

        if ($result->was_successful()) {
            return true;
        }
        throw new \Exception($result->response->Message);
    }

    /**
     * Check if user already exists in CM database
     * Used to ensure user isn't subscribed multiple times
     *
     * @param $email
     * @return bool
     */
    public function checkIfExists($email)
    {
        $result = $this->api->get($email);

        return $result->was_successful();
    }
}
