<?php
/**
 * Payment Reminder Sender
 * Run via cron: daily at 10 AM
 * Crontab: 0 10 * * * php /path/to/hostiva/cron/send_payment_reminders.php
 */

$config = require __DIR__ . '/../config/config.php';

try {
    $db = new PDO(
        'mysql:host=' . $config['database']['host'] . ';dbname=' . $config['database']['name'],
        $config['database']['user'],
        $config['database']['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    exit(1);
}

require __DIR__ . '/../api/services/EmailService.php';
$email_service = new EmailService($db, $config);

echo "[" . date('Y-m-d H:i:s') . "] Sending payment reminders...\n";

// Find unpaid invoices due in 2 days or overdue
$stmt = $db->prepare("
    SELECT id FROM folio_charges 
    WHERE status = 'pending' 
    AND due_date <= DATE_ADD(NOW(), INTERVAL 2 DAY)
");
$stmt->execute();
$invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

$sent = 0;
foreach ($invoices as $invoice) {
    if ($email_service->sendPaymentReminder($invoice['id'])) {
        $sent++;
    }
}

echo "[" . date('Y-m-d H:i:s') . "] Sent $sent payment reminders\n";
