<?php

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

$json = [];
try {
    $email = \Intgrtn\Lib\Common::request("email");
    $conversionType = \Intgrtn\Lib\Common::request("conversionType");
    $brokerName = \Intgrtn\Lib\Common::request("brokerName");
    $projectName = \Intgrtn\Lib\Common::request("projectName");
    $name = \Intgrtn\Lib\Common::request("name");
    $phone = \Intgrtn\Lib\Common::request("phone");
    $password = \Intgrtn\Lib\Common::request("password");
    $accessUrl = \Intgrtn\Lib\Common::request("accessUrl");
    $emailSubject = \Intgrtn\Lib\Common::request("emailSubject");
    $fromEmail = \Intgrtn\Lib\Common::request("fromEmail");
    $fromName = \Intgrtn\Lib\Common::request("fromName");

    if (empty($email)) {
        throw new ErrorException("Enter email");
    }
    if (empty($conversionType)) {
        throw new ErrorException("Enter conversionType");
    }
    if (empty($fromEmail)) {
        throw new ErrorException("Enter fromEmail");
    }
    if ($conversionType != 'First Deposit') {
        throw new ErrorException("Invalid conversionType");
    }

    if (empty($fromName)) {
        $fromName = $projectName;
    }

    $firstName = null;
    $lastName = null;
    $strippedName = null;
    if (!empty($name)) {
        $nameArray = explode(" ", $name);
        $firstName = $nameArray[0];
        array_shift($nameArray);
        $lastName = implode(" ", $nameArray);

        $stripper = new \Intgrtn\Lib\Stripper();
        $strippedName = $stripper->strippedName($firstName . " " . $lastName);
    }
    if (empty($emailSubject)) {
        $emailSubject = "";
        if (!empty($strippedName)) {
            $emailSubject .= $strippedName . ", ";
        }
        $emailSubject .= "Your " . $projectName . " Access Login And Details!";
    }

    $emailTemplate = new \Intgrtn\Lib\Template(__DIR__ . '/../../templates/genericEmail.html');
    $emailTemplate->name = $strippedName;
    $emailTemplate->email = $email;
    $emailTemplate->password = $password;
    $emailTemplate->brokerName = $brokerName;
    $emailTemplate->accessUrl = $accessUrl;
    $emailTemplate->formEmail = $fromEmail;
    $emailTemplate->fromName = $fromName;

    $emailSender = new \Intgrtn\Lib\EmailSender();
    $emailSender->setSubject($emailSubject);
    $emailSender->setHtml($emailTemplate->parse());
    $emailSender->addToEmail($email, $strippedName);
    $emailSender->setFromEmail($fromEmail);
    $emailSender->setFromName($fromName);
    $isSent = $emailSender->send();

    $json['data'] = [
        "email" => [
            "isSent" => $isSent ? 1 : 0,
            "error" => $emailSender->getError(),
        ]
    ];
    $json['message'] = "Success";
} catch (ErrorException $exc) {
    http_response_code(400);
    $json['message'] = $exc->getMessage();
}

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