<?php
/**
 * Low Balance Checker Script
 * This script checks for users with low balances and sends notifications
 * Can be run via cron job or manually
 */

require_once 'config.php';
require_once 'app/classes/NotificationManager.php';

// Configuration
$lowBalanceThreshold = 10.00; // GHS 10.00 threshold
$notificationManager = new NotificationManager($conn);

echo "Checking for low balances...\n";

// Get all active agents with balances below threshold
$stmt = $conn->prepare("
    SELECT id, username, email, phone, balance, role 
    FROM agents 
    WHERE status = 'active' 
    AND balance <= ? 
    AND balance > 0
    ORDER BY balance ASC
");

$stmt->bind_param("d", $lowBalanceThreshold);
$stmt->execute();
$result = $stmt->get_result();

$lowBalanceUsers = [];
while ($row = $result->fetch_assoc()) {
    $lowBalanceUsers[] = $row;
}
$stmt->close();

echo "Found " . count($lowBalanceUsers) . " users with low balances.\n";

// Send notifications to users with low balances
$notificationsSent = 0;
$notificationsFailed = 0;

foreach ($lowBalanceUsers as $user) {
    try {
        $notificationData = [
            'balance' => number_format($user['balance'], 2)
        ];
        
        $result = $notificationManager->sendNotification($user['id'], 'low_balance', $notificationData);
        
        if ($result['sms'] || $result['email']) {
            $notificationsSent++;
            echo "✅ Notification sent to {$user['username']} (Balance: GHS {$user['balance']})\n";
        } else {
            $notificationsFailed++;
            echo "❌ Failed to send notification to {$user['username']}: " . implode(', ', $result['errors']) . "\n";
        }
    } catch (Exception $e) {
        $notificationsFailed++;
        echo "❌ Error sending notification to {$user['username']}: " . $e->getMessage() . "\n";
    }
}

echo "\nSummary:\n";
echo "- Users with low balances: " . count($lowBalanceUsers) . "\n";
echo "- Notifications sent: $notificationsSent\n";
echo "- Notifications failed: $notificationsFailed\n";

// Log the check to a simple log file instead of database
$logData = [
    'timestamp' => date('Y-m-d H:i:s'),
    'users_checked' => count($lowBalanceUsers),
    'notifications_sent' => $notificationsSent,
    'notifications_failed' => $notificationsFailed,
    'threshold' => $lowBalanceThreshold
];

$logEntry = date('Y-m-d H:i:s') . " - Low Balance Check: " . json_encode($logData) . "\n";
file_put_contents('logs/low_balance_check.log', $logEntry, FILE_APPEND | LOCK_EX);

echo "✅ Low balance check completed and logged.\n";
?>




