<?php
use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;

require '../include/php/PHPMailer/src/Exception.php';

require '../include/php/PHPMailer/src/PHPMailer.php';

require '../include/php/PHPMailer/src/SMTP.php';

// ================= GOOGLE RECAPTCHA =================
function googleCaptcha($postData)
{
    $response = $postData;
    $remote_ip = $_SERVER["REMOTE_ADDR"];
    $secret_key = '6Lcji3gsAAAAACGWmPPI0GlBRal2VEKTxt171bEn';
    $url = "https://www.google.com/recaptcha/api/siteverify?secret={$secret_key}&response={$response}&remoteip={$remote_ip}";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);

    $output = curl_exec($curl);
    curl_close($curl);

    return json_decode($output, true);
}

// ================= EMAIL FUNCTION =================
// function sMail($to = [], $subject, $messageBody)
// {
//     $headers  = "MIME-Version: 1.0\r\n";
//     $headers .= "Content-type:text/html;charset=UTF-8\r\n";
//     $headers .= "From: Eterno Distributors <info@eternodistributors.com>\r\n";
//     $headers .= "Reply-To: info@eternodistributors.com\r\n";

//     $to = implode(',', $to);

//     return mail($to, $subject, $messageBody, $headers) ? "sent" : "failed";
// }

function sMail($to = array(), $subject = "", $messageBody = "")
{

    $from = "greenavafoods@gmail.com";

    $mail = new PHPMailer(true);

    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com'; // Your SMTP server
        $mail->SMTPAuth = true;
        $mail->Username = $from; // Your SMTP username
        $mail->Password = 'wxrafvpzxlxjynbj'; // Your SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = "587"; // TCP port to connect to

        // Recipients
        $mail->setFrom($from, 'Greenava Foods');
        $mail->addReplyTo($from, 'Greenava Foods');
        $mail->addCustomHeader('X-Mailer', 'PHPMailer');
        $mail->addCustomHeader('X-Origin', 'Greenava Foods');

        foreach ($to as $recipient) {
            $mail->addAddress($recipient);
        }


        // Content
        $mail->IsHTML(true);
        $mail->CharSet = 'UTF-8';
        $mail->Subject = $subject;
        $mail->Body = $messageBody;

        if ($mail->send()) {
            return 'sent';
        } else {
            return 'Failed to send email: ' . $mail->ErrorInfo;
        }

    } catch (Exception $e) {
        // echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        return json_encode(array('success' => false, 'Mailer Error' => $mail->ErrorInfo));
    }
}


?>