<?php

// set the default timezone
date_default_timezone_set('Africa/Lagos');

$graceMinutes = 1; // safety buffer
$cutoff = (new DateTime())->modify("-{$graceMinutes} minutes")->format('Y-m-d H:i:s');

//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader (created by composer, not included with PHPMailer)
require 'PHPMailer/vendor/autoload.php';

// include('../../include/connection.php');
include('connection.php');
require_once '../../lib/dbconfig.php';
require_once '../../lib/custom.php';
include('../../include/app_config.php');
//require_once 'lib/auth.class.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

function cron_log($message)
{
    $logFile = __DIR__ . '/cron_mail.log';
    file_put_contents(
        $logFile,
        '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL,
        FILE_APPEND
    );
}
     
        // cron ran
        cron_log("cron_job sighted!");
           
try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'ndphc.net';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = '_mainaccount@ndphc.net';                     //SMTP username
    $mail->Password   = 'dDfL2BhX8Qjw9xS';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    // // $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    // $mail->isSMTP();
    // $mail->Host = 'localhost';
    // $mail->Port = 1025;
    // $mail->SMTPAuth = false;
    // $mail->SMTPSecure = false;

    // get current date and time
    $now = date('Y-m-d H:i');

    // get scheduled mails that are still not sent out yet
    $sql="select * from scheduled_mails WHERE send_status = ? AND sent_later <= ? ORDER BY send_later ASC LIMIT 50";
    $r=$con->select_query($sql, [0, $cutoff]);
    
    // check if there are scheduled mails to send
    if ($r) {
        
        // loop through the result received
        foreach($r as $value)
        {
            
            $subject=$value['email_subject'];
            $message=$value['email_message'];

            // // determine the scheduled date for the individual mail scheduled
            // $send_email_at = date('Y-m-d H:i', strtotime($value['send_later']));

            // // skip iteration if the mail is not scheduled to send now
            // if ($send_email_at !== $now) {continue;}
            
            // // determine if now is the time to send the scheduled mail as scheduled
            // if ($send_email_at == $now) {
                
                // build recipient list according to participant filters saved with this scheduled mail
                $r2 = get_recipients_for_scheduled_mail($value['participant_type'] ?? 'all', $value['participant_data'] ?? null, $con);

                // check if recipient list is empty
                if(empty($r2)){

                    // nothing to send to; mark as sent to avoid repeated attempts
                    $sql3 = "UPDATE scheduled_mails SET sent_status = ? WHERE id = ?";
                    $con->update_query($sql3, [1, $value['id']]);

                    // skip this iteration
                    continue;
                }
        
                // loop through the received staff
                foreach ($r2 as $value2) {
                    
                    $firstname=$value2['firstname'];
                    $lastname=$value2['lastname'];
                    $othername=$value2['othernames'] ?: '';
                    $email=$value2['email'];
                    
                    //Recipients
                    
                    $mail->setFrom('_mainaccount@ndphc.net', 'NDPHC');
                    $mail->addAddress($email, $firstname . " " . $lastname);     //Add a recipient
                    $mail->addAddress('kebokwufavour@gmail.com', 'Favour Kebokwu');     //Add a recipient

                    //Content
                    $mail->isHTML(true);                                  //Set email format to HTML
                    $mail->Subject = $subject;
                    $mail->Body    = str_replace(["%firstname%", "%lastname%", "%othername%"], [$firstname, $lastname, $othername], $message);

                    // // send the mail
                    // $mail->send();
                    
                    try {
                        $mail->send();
                        cron_log("Mail sent to {$email}");
                    } catch (Exception $e) {
                        cron_log("Failed sending to {$email}: {$mail->ErrorInfo}");
                    }

                    // clear address to avoid sending to same email multiple times
                    $mail->clearAddresses();
                    
                        cron_log("mail sent for send_later_mails.php");
                        
                }

                // mark this sent scheduled email as sent
                $sql3 = "UPDATE scheduled_mails SET sent_status = ? WHERE id = ?";
                $con->update_query($sql3, [1, $value['id']]);

            // }

        }

        // all scheduled mails processed
        echo 'Message has been sent';

                        cron_log("all Messages has been sent");
                        
    } else {
    
        // no scheduled mails to send
        echo "No scheduled mails to send at this time.\n";
    
                        cron_log("No scheduled mails to send at this time.");
                        
    }
    
} catch (Exception $e) {

    // error occurred while sending mail
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    
                        cron_log("Mailer Error for send_later_mails.php file: {$mail->ErrorInfo}");
                        
}