<?php
/**
 * class notifications
 */
class Mail{

    private static function getTemplate($template){
        ob_start();
        global $apiVersion;
        require(ROOT_DIR . PATH_COMPONENTS.$apiVersion.'/utils/mail_templates/'.$template);

        return ob_get_clean();
    }

    private static function replaceTemplateParams($message, $tempalteParams){
        $tempalteParams['APPLICATION_NAME'] = APPLICATION_NAME;
        $replaceFrom = array_keys($tempalteParams);
        foreach ($replaceFrom as &$value) {
            $value = '{'.$value.'}';
        }
        $replaceWith = $tempalteParams;
        $message = str_replace($replaceFrom, $replaceWith, $message);

        return $message;
    }

    public static function sendMail($toList, $subject, $template, $tempalteParams = []){
        $multipleTos = false;

        if(is_array($toList)) {
            $toList = array_unique($toList);
            if(count($toList) === 1) {
                $to = new SendGrid\Email(null, $toList[0]);
            } else {
                $personalization = new SendGrid\Personalization();
                foreach($toList as $position => $toMail) {
                    if($position === 0) {
                        $to = new SendGrid\Email(null, $toMail);
                        $multipleTos = true;
                    } else {
                        $email = new SendGrid\Email(null, $toMail);
                        $personalization->addTo($email);
                    }
                }
            }
        } else {
            $to = new SendGrid\Email(null, $toList);
        }

        if(APPLICATION_MODE === 'PROD') {
            $from = new SendGrid\Email(APPLICATION_NAME." Admin", ADMIN_MAIL);
            $message = self::getTemplate($template);
            $message = empty($tempalteParams) ? $message : self::replaceTemplateParams($message, $tempalteParams);
            $content = new SendGrid\Content("text/html", $message);

            $mail = new SendGrid\Mail($from, $subject, $to, $content);
            if($multipleTos) {
                $mail->addPersonalization($personalization);
            }
            $sg = new \SendGrid(SENDGRID_API_KEY);
            $response = $sg->client->mail()->send()->post($mail);

            $sendStatus = $response->statusCode() === 202;

            if(!$sendStatus){
                var_dump($response);
                $err_mes = 'SendGrid failed to send the mail!';
                trigger_error($err_mes, E_USER_ERROR);
            }

            return $sendStatus;
        } else {
            return true;
        }
    }
}
