<?php

declare(strict_types=1);

namespace Cloonar\BaseDesign\Domain\Finishers;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Form\Domain\Finishers\Exception\FinisherException;
use Symfony\Component\Mime\Address;

class GetResponseFinisher extends \TYPO3\CMS\Form\Domain\Finishers\AbstractFinisher
{

  const GET_RESPONSE_REQUEST_URL = 'https://api.getresponse.com/v3';

  /**
   * @var \TYPO3\CMS\Core\Http\RequestFactory
   */
  protected $request;

  /**
   * @var array
   */
  protected $defaultOptions = [
    'notifyEmail' => '',
    'apiKey' => '',
    'campaignId' => '',
    'email' => '',
    'firstname' => '',
    'lastname' => '',
    'company' => '',
    'register' => false,
  ];

  /**
   * Executes this finisher
   * @see AbstractFinisher::execute()
   *
   * @throws FinisherException
   */
  protected function executeInternal()
  {

    $notifyEmail = $this->parseOption('notifyEmail');
    $apiKey = $this->parseOption('apiKey');
    $campaignId = $this->parseOption('campaignId');
    $email = $this->parseOption('email');
    $firstname = $this->parseOption('firstname');
    $lastname = $this->parseOption('lastname');
    $company = $this->parseOption('compandy');
    $register = $this->parseOption('register');

    if ($register != "1") {
      return;
    }

    if (empty($notifyEmail)) {
      throw new FinisherException('The option "notifyEmail" must be set for the GetResponseFinisher.', 1681331285);
    }
    if (empty($apiKey)) {
      throw new FinisherException('The option "apiKey" must be set for the GetResponseFinisher.', 1681331286);
    }
    if (empty($campaignId)) {
      throw new FinisherException('The option "campaignId" must be set for the GetResponseFinisher.', 1681331287);
    }
    if (empty($email)) {
      throw new FinisherException('The option "email" must be set for the GetResponseFinisher.', 1681331288);
    }
    if (empty($firstname)) {
      throw new FinisherException('The option "firstname" must be set for the GetResponseFinisher.', 1681331289);
    }
    if (empty($lastname)) {
      throw new FinisherException('The option "lastname" must be set for the GetResponseFinisher.', 1681331290);
    }

    $data = [
        "name" => $firstname.' '.$lastname,
        "email" => $email,
        "campaign" => [
            "campaignId" => $campaignId
        ]
    ];


    $request = GeneralUtility::makeInstance(RequestFactory::class);
    $response = $request->request(
      self::GET_RESPONSE_REQUEST_URL.'/contacts',
      'POST',
      [
        'headers' => [
          'X-Auth-Token' => 'api-key '.$apiKey,
          'Content-Type' => 'application/json'
        ],
        'body' => json_encode($data)
      ]
    );

    if ($response->getStatusCode() == 200) {
      $mail = GeneralUtility::makeInstance(MailMessage::class);
      $mail
          ->from(new Address('noreply@cloonar.dev'))
          ->to(
              new Address($notifyEmail)
          )
          ->subject('Newsletter Anmeldung')
          ->text('Vorname: '.$firstname.'\r\nNachname: '.$lastname.'\r\nFirma: '.$company.'\r\nEmail: '.$email)
          ->send();
    }
  }

  /**
   * @param $string
   * @return string
   */
  protected static function escapeString($string)
  {
    $string = htmlspecialchars($string);
    return (string)$string;
  }
}
