<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../helpers/Env.php';

// Load environment variables
Env::load(__DIR__ . '/../.env');
require_once __DIR__ . '/../config/app.php';
require_once APP_ROOT . '/config/database.php';
require_once APP_ROOT . '/helpers/Session.php';
require_once APP_ROOT . '/helpers/Lang.php';
require_once APP_ROOT . '/helpers/Mailer.php';
require_once APP_ROOT . '/models/ListNote.php';
require_once APP_ROOT . '/models/Setting.php';

// Initialize Lang with default locale for cron (no session)
Lang::load();

$listModel = new ListNote();
$pending = $listModel->getPendingReminders();

foreach ($pending as $list) {
    if (empty($list['reminder_email'])) {
        $listModel->markReminderSent($list['id']);
        continue;
    }

    $subject = Lang::get('app_name') . ' - ' . Lang::get('reminder') . ': ' . $list['title'];
    $body = '<h2>' . htmlspecialchars($list['title']) . '</h2>';
    if (!empty($list['content'])) {
        $body .= '<p>' . nl2br(htmlspecialchars($list['content'])) . '</p>';
    }
    $body .= '<p><em>' . Lang::get('reminder_scheduled_for') . ': ' . $list['reminder_at'] . '</em></p>';

    $sent = Mailer::send($list['reminder_email'], $subject, $body);

    if ($sent) {
        $listModel->markReminderSent($list['id']);
        echo date('Y-m-d H:i:s') . " - Reminder sent for list #{$list['id']} to {$list['reminder_email']}\n";
    } else {
        echo date('Y-m-d H:i:s') . " - FAILED to send reminder for list #{$list['id']}\n";
    }
}

if (empty($pending)) {
    echo date('Y-m-d H:i:s') . " - No pending reminders\n";
}
