<?php

require './vendor/autoload.php';
require '../../core/backend.php';

class EmailApi extends Api
{
    public $apiName = 'email';
    public $sg;

    public function __construct($requestUri, $encryption=true) {
        parent::__construct($requestUri, $encryption);

        global $savvyext;

        $apiKey = $savvyext->cfgReadChar('mailsend.api_key');
        $sg = new \SendGrid($apiKey);

        $this->sg = $sg;
    }

    public function indexAction() {
        $results = $this->findNewEmails();
        return $this->response(
            array(
                "success" => true,
                "data" => $results
            ), 200 );
    }

    /**
     * @OA\Post(
     *   path="/v1/email/api/email/new",
     *   summary="Send email to users",
     *   @OA\Parameter(
     *     name="name",
     *     description = "Name of email template",
     *     in="body",
     *     required=true,
     *     @OA\Schema(ref="#/components/schemas/create_params")
     *   )
     * )
     */
    public function createAction()
    {
        $db = new Db();
        $message = "Failed to send email";

        $subject = $this->requestParams['subject'] ?? NULL;
        $receivers = $this->requestParams["to"] ?? NULL;
        $htmlBody = $this->requestParams['html_body'] ?? NULL;

        if (!isset($subject) || !isset($receivers) || !isset($htmlBody)) {
            return $this->response(
                array(
                    "success" => false,
                    "message" => 'Missing params'
                ), 400);
        }

        $result = Email::createEmail(
            $db->getConnect(),
            $receivers,
            $subject,
            $htmlBody
        );

        if (!isset($result)) {
            return $this->response(
                array(
                    "success" => false,
                    "message" => $message
                ), 500);
        }

        return $this->response($result, 200);
    }

    public function viewAction() {}

    public function updateAction() {}

    public function deleteAction() {}
}
