<?php

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

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

    if (empty($email)) {
        throw new ErrorException("Enter email");
    }
    if (empty($fromEmail)) {
        throw new ErrorException("Enter fromEmail");
    }
    if (empty($fromName)) {
        $fromName = $projectName;
    }
    if (empty($emailSubject)) {
        $emailSubject = "Your password recovery process was completed.";
    }

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

    $emailSender = new \Intgrtn\Lib\EmailSender();
    $emailSender->setSubject($emailSubject);
    $emailSender->setHtml($emailTemplate->parse());
    $emailSender->addToEmail($email);
    $emailSender->setFromEmail($fromEmail);
    $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);
