<?php
$logFile = __DIR__ . '/newsletter_log.txt';
file_put_contents($logFile, "Script started at " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/autoload.php';
include '../db_connect.php';

// Fetch all subscribers
$result = $conn->query("SELECT email FROM newsletter_emails");

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $email = $row['email'];

        $mail = new PHPMailer(true);
        try {
            // SMTP settings
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'benjamindanieljr11@gmail.com'; // your gmail
            $mail->Password = 'tvvvkzlylfgdmcys'; // Gmail App Password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;

            // Recipients
            $mail->setFrom('benjamindanieljr11@gmail.com', 'Zemaraim Technology');
            $mail->addAddress($email);

            // Content
            $mail->isHTML(true);
            $mail->Subject = "🚀 Zemaraim Technology Monthly Newsletter";

            // Load your HTML newsletter template
            $mail->Body = file_get_contents('../newsletter.html');

            $mail->send();
            echo "Newsletter sent to: $email<br>";
        } catch (Exception $e) {
            echo "Failed for $email. Error: {$mail->ErrorInfo}<br>";
        }
    }
} else {
    echo "No subscribers found.";
}

$conn->close();
file_put_contents($logFile, "Script ended at " . date('Y-m-d H:i:s') . "\n\n", FILE_APPEND);
?>
