<?php

define('BASE_PATH',realpath(__DIR__.'/..'));

require_once BASE_PATH.'/config/autoload.php';
require_once BASE_PATH.'/config/bootstrap.php';
require_once BASE_PATH.'/app/core/Database.php';
require_once BASE_PATH.'/app/core/SmtpMailer.php';

use App\Core\Database;
use App\Core\SmtpMailer;

function out($m){
echo '['.date('Y-m-d H:i:s').'] '.$m.PHP_EOL;
}

$db=Database::getInstance();

$rows=$db->query("
SELECT *
FROM conference_mail_outbox
WHERE status IN ('queued','failed')
ORDER BY id ASC
LIMIT 25
")->fetchAll(PDO::FETCH_ASSOC);

out("Found ".count($rows)." queued/failed message(s)");

$mail=new SmtpMailer();

foreach($rows as $m){

$id=(int)$m['id'];

try{

out(
"Processing outbox #".$id
." to="
.($m['recipient_email']??'')
);

$mail->send(
$m['recipient_email'],
$m['subject'],
$m['body'],
$m['recipient_name'] ?? ''
);

$db->prepare("
UPDATE conference_mail_outbox
SET
status='sent',
sent_at=NOW(),
error_message=NULL
WHERE id=?
")->execute([$id]);

out("SENT #".$id);

}catch(Throwable $e){

$db->prepare("
UPDATE conference_mail_outbox
SET
status='failed',
error_message=?
WHERE id=?
")->execute([
mb_substr(
$e->getMessage(),
0,
1000
),
$id
]);

out(
"FAILED #".$id
);

}

}

out("DONE");
