<?php
/**
 * سودانا — Invoice Expiry Cron
 * Runs: daily (or every 6 hours)
 * Marks invoices past 48h as expired
 */
require_once __DIR__ . '/../config.php';

// Mark all pending invoices past expires_at as rejected/expired
$expired = db()->query(
    "UPDATE invoices
     SET status = 'rejected',
         notes  = CONCAT(IFNULL(notes,''), ' [EXPIRED-AUTO]')
     WHERE status IN ('pending','proof_uploaded')
       AND expires_at IS NOT NULL
       AND expires_at < NOW()"
);
$count = $expired->rowCount();

if ($count > 0) {
    error_log("[expire_invoices] Expired $count invoices at " . date('Y-m-d H:i:s'));
    // Notify users of expired invoices
    $users = db()->query(
        "SELECT id, user_id, reference_code FROM invoices
         WHERE status='rejected' AND notes LIKE '%EXPIRED-AUTO%'
           AND updated_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE)"
    )->fetchAll(PDO::FETCH_ASSOC);

    foreach ($users as $inv) {
        try {
            db()->prepare(
                "INSERT IGNORE INTO notifications (user_id, type, title, body, data, created_at)
                 VALUES (?, 'invoice_expired', '⚠️ انتهت صلاحية فاتورتك',
                 ?, ?, NOW())"
            )->execute([$inv['user_id'],
                'الفاتورة ' . $inv['reference_code'] . ' انتهت صلاحيتها (48 ساعة). أنشئ فاتورة جديدة.',
                json_encode(['invoice_id'=>$inv['id']], JSON_UNESCAPED_UNICODE)
            ]);
        } catch (Throwable $e) {
            error_log("[expire_invoices::notify] " . $e->getMessage());
        }
    }
}
echo "Expired: $count invoices
";
