<?php
/**
 * Command Line Hotspot User Cleanup Script
 * Run this from command line to avoid web timeouts
 * Usage: php cleanup_stuck_users_cli.php
 */

// Set unlimited execution time for CLI
if (php_sapi_name() === 'cli') {
    set_time_limit(0);
    ini_set('memory_limit', '512M');
} else {
    die("This script must be run from command line only.\n");
}

require_once 'init.php';

echo "=== Hotspot User Cleanup CLI Tool ===\n";
echo "Started at: " . date('Y-m-d H:i:s') . "\n";
echo "Process ID: " . getmypid() . "\n\n";

// Get all expired hotspot recharges
$expired_recharges = ORM::for_table('tbl_user_recharges')
    ->where('type', 'Hotspot')
    ->where('status', 'off')
    ->where_lte('expiration', date('Y-m-d'))
    ->find_many();

$total_users = count($expired_recharges);
echo "Found $total_users expired hotspot users to process\n\n";

if ($total_users == 0) {
    echo "✅ No stuck users found! System is clean.\n";
    exit(0);
}

$processed_count = 0;
$cleaned_count = 0;
$error_count = 0;
$cleaned_users = [];
$routers_processed = [];
$start_time = microtime(true);

foreach ($expired_recharges as $index => $recharge) {
    $current = $index + 1;
    $percent = round(($current / $total_users) * 100, 1);
    
    echo "[$current/$total_users] ({$percent}%) Processing: {$recharge->username} (expired: {$recharge->expiration})\n";
    
    try {
        // Get router info
        $router = ORM::for_table('tbl_routers')->where('name', $recharge->routers)->find_one();
        if (!$router) {
            echo "  ❌ Router '{$recharge->routers}' not found\n";
            $error_count++;
            continue;
        }
        
        if (!in_array($router->name, $routers_processed)) {
            $routers_processed[] = $router->name;
            echo "  🔗 Connecting to router: {$router->name} ({$router->ip_address})\n";
        }
        
        // Initialize MikroTik handler
        $device_file = "system/devices/MikrotikHotspot.php";
        if (file_exists($device_file)) {
            require_once $device_file;
            $mikrotik_handler = new MikrotikHotspot();
            
            try {
                $client = $mikrotik_handler->getClient($router->ip_address, $router->username, $router->password);
                if ($client === null) {
                    echo "  ❌ Cannot connect to router {$router->name}\n";
                    $error_count++;
                    continue;
                }
                
                // Check if user exists in router
                $printRequest = new PEAR2\Net\RouterOS\Request('/ip/hotspot/user/print');
                $printRequest->setArgument('.proplist', '.id,name');
                $printRequest->setQuery(PEAR2\Net\RouterOS\Query::where('name', $recharge->username));
                $userResponse = $client->sendSync($printRequest);
                $userID = $userResponse->getProperty('.id');
                
                if ($userID) {
                    echo "  🔍 Found in router, removing...\n";
                    
                    // Remove active sessions first
                    $mikrotik_handler->removeHotspotActiveUser($client, $recharge->username);
                    
                    // Remove the user
                    $removeRequest = new PEAR2\Net\RouterOS\Request('/ip/hotspot/user/remove');
                    $removeRequest->setArgument('numbers', $userID);
                    $client->sendSync($removeRequest);
                    
                    echo "  ✅ Successfully removed from router\n";
                    $cleaned_users[] = $recharge->username;
                    $cleaned_count++;
                } else {
                    echo "  ℹ️  Not found in router (already clean)\n";
                }
                
                $processed_count++;
                
            } catch (Exception $e) {
                echo "  ❌ Router error: " . $e->getMessage() . "\n";
                $error_count++;
            }
        } else {
            echo "  ❌ MikroTik device handler not found\n";
            $error_count++;
        }
        
    } catch (Exception $e) {
        echo "  ❌ Critical error: " . $e->getMessage() . "\n";
        $error_count++;
    }
    
    // Progress indicator every 10 users
    if ($current % 10 == 0 || $current == $total_users) {
        $elapsed = round(microtime(true) - $start_time, 2);
        $rate = round($current / $elapsed, 2);
        $eta = $rate > 0 ? round(($total_users - $current) / $rate, 2) : 0;
        echo "  📊 Progress: $current/$total_users | Rate: {$rate}/sec | ETA: {$eta}sec\n";
    }
    
    echo "\n";
}

$total_time = round(microtime(true) - $start_time, 2);

echo "=== Final Summary ===\n";
echo "Total users found: $total_users\n";
echo "Successfully processed: $processed_count\n";
echo "Users cleaned from routers: $cleaned_count\n";
echo "Errors encountered: $error_count\n";
echo "Routers accessed: " . implode(', ', $routers_processed) . "\n";
echo "Total execution time: {$total_time} seconds\n";
echo "Average rate: " . round($processed_count / $total_time, 2) . " users/second\n";

if (!empty($cleaned_users)) {
    echo "\nCleaned users:\n";
    foreach ($cleaned_users as $username) {
        echo "  - $username\n";
    }
}

if ($error_count > 0) {
    echo "\n⚠️  $error_count errors occurred. Check the output above for details.\n";
}

echo "\nCompleted at: " . date('Y-m-d H:i:s') . "\n";
echo "✅ Cleanup process finished!\n";

// Log the completion
_log("Hotspot cleanup completed: $cleaned_count users cleaned, $error_count errors, {$total_time}s execution time");
?>
