<?php
/**
 * Manual Hotspot User Cleanup Script
 * This script will clean up expired hotspot users that are stuck in the router
 * Run this script to fix the current issue with users not being removed from MikroTik
 */

require_once 'init.php';

// Check if admin is logged in (if running from web)
if (php_sapi_name() !== 'cli') {
    $admin = Admin::_info();
    if (!$admin) {
        die('Please login as admin first');
    }
    echo "<pre>";
}

echo "=== Manual Hotspot User Cleanup Script ===\n";
echo "Started at: " . date('Y-m-d H:i:s') . "\n\n";

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

echo "Found " . count($expired_recharges) . " expired hotspot recharges to process\n\n";

$processed_count = 0;
$error_count = 0;
$cleaned_users = [];

foreach ($expired_recharges as $recharge) {
    try {
        echo "Processing user: {$recharge->username} (expired: {$recharge->expiration})\n";
        
        // Get the plan and router info
        $plan = ORM::for_table('tbl_plans')->find_one($recharge->plan_id);
        if (!$plan) {
            echo "  ❌ Plan not found for user {$recharge->username}\n";
            $error_count++;
            continue;
        }
        
        // Get customer info
        $customer = ORM::for_table('tbl_customers')->find_one($recharge->customer_id);
        if (!$customer) {
            echo "  ⚠️  Customer record not found, using recharge data\n";
            $customer = $recharge; // Use recharge data as fallback
        }
        
        // Initialize the MikroTik device handler
        $device_file = "system/devices/MikrotikHotspot.php";
        if (file_exists($device_file)) {
            require_once $device_file;
            $mikrotik_handler = new MikrotikHotspot();
            
            // 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;
            }
            
            // Try to connect to the router
            try {
                $client = $mikrotik_handler->getClient($router->ip_address, $router->username, $router->password);
                if ($client === null) {
                    echo "  ❌ Failed to connect to router {$router->name} ({$router->ip_address})\n";
                    $error_count++;
                    continue;
                }
                
                echo "  ✅ Connected to router {$router->name}\n";
                
                // Check if user exists in hotspot users
                $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 user in hotspot users list, removing...\n";
                    
                    // Remove active sessions first
                    $mikrotik_handler->removeHotspotActiveUser($client, $recharge->username);
                    
                    // Remove the user from hotspot users
                    $removeRequest = new PEAR2\Net\RouterOS\Request('/ip/hotspot/user/remove');
                    $removeRequest->setArgument('numbers', $userID);
                    $client->sendSync($removeRequest);
                    
                    echo "  ✅ Successfully removed user {$recharge->username} from router\n";
                    $cleaned_users[] = $recharge->username;
                } else {
                    echo "  ℹ️  User {$recharge->username} not found in router (already cleaned)\n";
                }
                
                $processed_count++;
                
            } catch (Exception $e) {
                echo "  ❌ Error processing user {$recharge->username}: " . $e->getMessage() . "\n";
                $error_count++;
            }
            
        } else {
            echo "  ❌ MikroTik device handler not found\n";
            $error_count++;
        }
        
        echo "\n";
        
    } catch (Exception $e) {
        echo "  ❌ Critical error processing {$recharge->username}: " . $e->getMessage() . "\n\n";
        $error_count++;
    }
}

echo "=== Cleanup Summary ===\n";
echo "Total processed: $processed_count\n";
echo "Errors encountered: $error_count\n";
echo "Users cleaned from routers: " . count($cleaned_users) . "\n";

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

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

if (php_sapi_name() !== 'cli') {
    echo "</pre>";
}

echo "\n=== Next Steps ===\n";
echo "1. The improved removeHotspotActiveUser() function has been updated\n";
echo "2. Future expired users should be properly cleaned by the cron job\n";
echo "3. Monitor the system to ensure the issue is resolved\n";
echo "4. You can delete this script after confirming everything works\n";
?>
