<?php
declare(strict_types=1);

// Delivers queued mail. Run from cron every minute.
$api = __DIR__ . '/../api';
require $api . '/lib/Config.php';
require $api . '/lib/DB.php';
require $api . '/lib/Mailer.php';

Config::load($api . '/config/config.php');
date_default_timezone_set((string) Config::get('timezone', 'Asia/Jerusalem'));

// Never let two cron runs overlap. A lock we cannot take is not a reason to
// skip sending — cron runs as www-data, an admin may run this by hand as root,
// and the file may already belong to the other one.
$lockPath = sys_get_temp_dir() . '/helpdesk-mail.lock';
$lock = @fopen($lockPath, 'c');
if ($lock === false) {
    $lock = @fopen($lockPath . '.' . get_current_user(), 'c');
}
if ($lock !== false) {
    @chmod($lockPath, 0666);
    if (!flock($lock, LOCK_EX | LOCK_NB)) {
        exit(0);   // another run is already working the queue
    }
}

$rows = DB::all(
    'SELECT * FROM email_queue WHERE status = "pending" AND attempts < 5 ORDER BY id LIMIT 50'
);

foreach ($rows as $row) {
    try {
        Mailer::send($row['to_email'], $row['subject'], $row['body_html']);
        DB::run('UPDATE email_queue SET status = "sent", sent_at = NOW(), attempts = attempts + 1 WHERE id = ?', [$row['id']]);
        echo date('c'), " sent #{$row['id']} -> {$row['to_email']}\n";
    } catch (Throwable $e) {
        $attempts = (int) $row['attempts'] + 1;
        DB::run('UPDATE email_queue SET attempts = ?, last_error = ?, status = ? WHERE id = ?',
            [$attempts, mb_substr($e->getMessage(), 0, 500), $attempts >= 5 ? 'failed' : 'pending', $row['id']]);
        echo date('c'), " FAILED #{$row['id']}: ", $e->getMessage(), "\n";
    }
}
