<?php
declare(strict_types=1);

define('CLI_SCRIPT', true);
require __DIR__ . '/../../bootstrap.php';

use App\Services\MailQueueService;

$mailConfig = require __DIR__ . '/../../config/mail.php';
$queue = new MailQueueService();
$rows = $queue->queued(25);

if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    $autoload = __DIR__ . '/../../vendor/autoload.php';
    if (file_exists($autoload)) {
        require_once $autoload;
    }
}

if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    echo "PHPMailer not installed.\n";
    exit(1);
}

foreach ($rows as $row) {
    try {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = $mailConfig['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $mailConfig['username'];
        $mail->Password = $mailConfig['password'];
        $mail->SMTPSecure = $mailConfig['encryption'];
        $mail->Port = (int) $mailConfig['port'];
        $mail->CharSet = 'UTF-8';

        $mail->setFrom($mailConfig['from_email'], $mailConfig['from_name']);
        $mail->addAddress((string) $row['to_email'], (string) ($row['to_name'] ?? ''));
        $mail->isHTML(true);
        $mail->Subject = (string) $row['subject_line'];
        $mail->Body = (string) ($row['body_html'] ?? '');
        $mail->AltBody = (string) ($row['body_text'] ?? strip_tags((string) ($row['body_html'] ?? '')));

        $mail->send();
        $queue->markSent((int) $row['id']);
        echo "Sent queue #" . $row['id'] . "\n";
    } catch (\Throwable $e) {
        $queue->markFailed((int) $row['id'], $e->getMessage());
        echo "Failed queue #" . $row['id'] . ": " . $e->getMessage() . "\n";
    }
}
