<?php

require_once __DIR__ . "/../../vendor/autoload.php";

$json = [];
try {
    $email = \Intgrtn\Lib\Common::request("email");
    $fromEmail = \Intgrtn\Lib\Common::request("fromEmail");
    $fromName = \Intgrtn\Lib\Common::request("fromName");
    $projectName = \Intgrtn\Lib\Common::request("projectName");
    $firstName = \Intgrtn\Lib\Common::request("firstName");
    $replyURL = \Intgrtn\Lib\Common::request("replyURL");
    $emailSubject = \Intgrtn\Lib\Common::request("emailSubject");

    if (empty($email)) {
        throw new ErrorException("Enter email");
    }
    if (empty($fromEmail)) {
        throw new ErrorException("Enter fromEmail");
    }
    if (empty($replyURL)) {
        throw new ErrorException("Enter replyURL");
    }

    $emailTemplate = new \Intgrtn\Lib\Template(__DIR__ . '/../../templates/contactRequestMessage.html');
    $emailTemplate->replyURL = $replyURL;
    $emailTemplate->firstName = $firstName;

    if (empty($firstName)) {
        $emailTemplate->helloPartStyles = 'display: none;';
    }

    $emailSender = new \Intgrtn\Lib\EmailSender();
    if (empty($emailSubject)) {
        $emailSubject = !empty($projectName) ? 'New Response From ' . $projectName : 'New Response';
    }
    $emailSender->setSubject($emailSubject);
    $emailSender->setHtml($emailTemplate->parse());
    $emailSender->addToEmail($email);
    $emailSender->setFromEmail($fromEmail);
    $emailSender->setFromName("Support");
    if (!empty($fromName)) {
        $emailSender->setFromName($fromName);
    }
    $isSent = $emailSender->send();

    if ($isSent == false) {
        throw new ErrorException("Email can't be sent. Error: " . $emailSender->getError());
    }

    $json['message'] = "The email has been sent successfully";
} catch (ErrorException $exc) {
    http_response_code(400);
    $json['message'] = $exc->getMessage();
}

header('Content-Type: application/json');
echo json_encode($json);

