<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

$result = $conn->query("SELECT email FROM newsletter_emails");

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

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

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

            $mail->isHTML(true);
            $mail->Subject = "Zemaraim Technology Monthly Newsletter";
            $mail->Body = file_get_contents('../frontend/newsletter.html');

            $mail->send();
            echo "Sent to: $email<br>";
            $count++;
        } catch (Exception $e) {
            // Skip failed emails silently
        }
    }
    echo "✅ Newsletter sent to $count subscribers.";
} else {
    echo "No subscribers found.";
}
$conn->close();
?>
