<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../app/bootstrap.php';

use Core\Helpers\EmailHelper;
use App\Services\EmailService;

// Avoid session warnings in CLI
if (php_sapi_name() === 'cli') {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
}

$service = new EmailService();

while (true) {
    try {
        $pendingEmails = EmailHelper::getPendingEmails();

        if (!empty($pendingEmails)) {
            echo "[" . date('Y-m-d H:i:s') . "] Sending " . count($pendingEmails) . " emails...\n";
            $service->sendQueuedEmails($pendingEmails);
            echo "[" . date('Y-m-d H:i:s') . "] Done sending.\n";
        } else {
            echo "[" . date('Y-m-d H:i:s') . "] No pending emails.\n";
        }

    } catch (\Throwable $e) {
        echo "[" . date('Y-m-d H:i:s') . "] Error: " . $e->getMessage() . "\n";
    }

    // Sleep for 10 seconds before checking again
    sleep(10);
}
