<?php

namespace Services;

class MailerService
{
    private $apiKey;
    private $url;

    public function __construct()
    {
        $this->apiKey = $_ENV['SENDGRID_API_KEY'];
        $this->url = 'https://api.sendgrid.com/v3/mail/send';
    }

    public function sendEmail($recipients, $fromEmail, $fromName, $subject, $htmlContent)
    {
        $data = [
            "personalizations" => [
                [
                    "to" => $recipients
                ]
            ],
            "from" => [
                "email" => $fromEmail,
                "name" => $fromName
            ],
            "subject" => $subject,
            "content" => [
                [
                    "type" => "text/html",
                    "value" => $htmlContent
                ]
            ]
        ];

        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Desactivar la verificación del certificado SSL

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($response === false) {
            error_log('cURL Error: ' . curl_error($ch));
            return false;
        } else {
            error_log('Status Code: ' . $httpCode);
            error_log('Response: ' . $response);
            return $httpCode === 200 || $httpCode === 202;
        }

        curl_close($ch);
    }
}
?>
