<?php

use function Sodium\compare;

require_once '../core/bootstrap.php';

// This script should be run as a cron job, e.g., daily.

// --- Auto-Migration for last_notified_at ---
$db = new Database();
try {
    $db->query("SELECT last_notified_at FROM sponsor_campaigns LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    $db->query("ALTER TABLE sponsor_campaigns ADD COLUMN last_notified_at DATETIME DEFAULT NULL");
    $db->execute();
}

$sponsorModel = new Sponsorship();
$walletModel = new Wallet();
$notificationModel = new Notification();

$lowBudgetCampaigns = $sponsorModel->getCampaignsRunningLow();
$notificationsSent = 0;

if (!empty($lowBudgetCampaigns)) {
    foreach ($lowBudgetCampaigns as $campaign) {
        // Check if notified in the last 24 hours
        if (!empty($campaign->last_notified_at) && strtotime($campaign->last_notified_at) > strtotime('-24 hours')) {
            continue;
        }

        $userId = $campaign->user_id;
        $package_name = $campaign->package_name;
        $walletBalance = $campaign->wallet_balance;
        $packagePrice = $campaign->package_price;

        // Notify user
        $msg = "Your campaign \"{$package_name}\" is running low on funds. Wallet balance is {$walletBalance}, which is less than campaign price {$packagePrice}. Please add funds to continue campaign.";
        $notificationModel->create($userId, 'low_budget', $msg);
        
        // Update last notified timestamp
        $sponsorModel->updateLowBudgetNotification($campaign->campaign_id);

        // Log the notification to make it easier to track
        error_log("Low budget notification sent to user {$userId} for campaign {$campaign->campaign_id}.");
        $notificationsSent++;
    }

    echo "Successfully checked " . count($lowBudgetCampaigns) . " campaign(s) running low. Sent $notificationsSent notification(s).\n";
} else {
    echo "No campaigns running low on funds today.\n";
}

?>