<?php

//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;

    $today = date('d-m');
    $message = `
        <div style="background-color:#f7f7f7;width:100%;">

            <div style="max-width:600px;margin:0 auto;background-color:#ffffff;border-radius:10px;overflow:hidden;">

                <!-- Header -->
                <div data-section="header" style="background-color:#ff9a9e;padding:30px 20px;color:#ffffff;text-align:center;">
                    <h1 style="margin:0;font-size:36px;font-weight:bold;">Happy Birthday!</h1>
                    <p style="margin:10px 0 0;font-size:18px;">Celebrating your special day with us!</p>
                </div>

                <!-- Content -->
                <div style="padding:30px;text-align:center;">

                    <!-- Greeting -->
                    <p style="font-size:24px;color:#ff6b6b;font-weight:bold;margin:0 0 20px;">
                        Dear %firstname% %lastname%,
                    </p>

                    <!-- Message -->
                    <p style="font-size:16px;color:#555;line-height:1.7;margin:0 0 15px;">
                        Wishing you a day filled with happiness, joy, and wonderful surprises! On your special day, we want to express our gratitude for being a valued part of our community.
                    </p>

                    <!-- Quote -->
                    <p style="font-style:italic;color:#777;font-size:15px;border-top:1px dashed #eee;border-bottom:1px dashed #eee;padding:15px;margin:25px 0;">
                        "May your birthday be as bright as your smile, as sweet as your laughter, and as wonderful as you are."
                    </p>

                </div>

                <!-- Footer -->
                <div style="background-color:#f9f9f9;padding:20px;font-size:14px;color:#888;text-align:center;">
                    <p style="margin:0 0 10px;">
                        With warmest wishes,<br>
                        The NDPHC Team
                    </p>

                    <p style="margin:0 0 10px;">
                        123 Celebration Street, Nigeria<br>
                        <a href="tel:+1234567890" style="color:#ff9a9e;text-decoration:none;">(123) 456-7890</a> |
                        <a href="mailto:ndphc@company.com" style="color:#ff9a9e;text-decoration:none;">ndphc@company.com</a>
                    </p>

                    <p style="font-size:12px;color:#aaa;margin:15px 0 0;">
                        You're receiving this email because you're a valued member of our community.
                    </p>
                </div>

            </div>

        </div>
    `;

    // get staff whoose email address is provided
    $sql2="select * from staff WHERE email != ?";
    $r2=$con->select_query($sql2, [""]);

    // determine if a record was received
    if (!$r2) {
        // no staff record received
        exit;
    }

    if($r2 && count($r2) > 0) {
        
        foreach ($r2 as $value2) {

            $dob = date("Y-m-d", strtotime($value2["dob"]));
            $birthday = date("d-m", strtotime($dob));

            // determine if the birthday is today
            if ($birthday != $today) {
                continue; // skip iteration
            }
            
            $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 = "Happy Birthday {$firstname}";
            $mail->Body    = str_replace(["%firstname%", "%lastname%", "%othername%"], [$firstname, $lastname, $othername], $message);

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

            $mail->clearAddresses();
            
        }

        echo 'Message has been sent';

        // cron ran
        cron_log("All Messages has been sent");
           
    }

} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    
        // cron ran
        cron_log("Message could not be sent. Mailer Error for send_birthday_mails.php file: {$mail->ErrorInfo}");
           
}