<?php

/**
 * Script to manually expire all sessions for a specific user
 * Usage: php scripts/expire-user-session.php [user_id]
 */

require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

if ($argc < 2) {
    echo "Usage: php expire-user-session.php [user_id]\n";
    exit(1);
}

$userId = (int) $argv[1];

$user = \App\Models\User::find($userId);

if (!$user) {
    echo "User {$userId} not found\n";
    exit(1);
}

echo "User found: {$user->name} (ID: {$user->id})\n";
echo "Session driver: " . config('session.driver') . "\n\n";

$sessionDriver = config('session.driver');
$deleted = 0;

if ($sessionDriver === 'redis') {
    echo "Scanning Redis for user sessions...\n";

    $redis = \Illuminate\Support\Facades\Redis::connection(config('session.connection') ?: 'default');
    $prefix = config('database.redis.options.prefix', '');

    // Get all session keys
    $cursor = '0';
    $allKeys = [];

    do {
        $result = $redis->scan($cursor, ['match' => $prefix . 'laravel_session:*', 'count' => 100]);
        $cursor = $result[0];
        $keys = $result[1] ?? [];
        $allKeys = array_merge($allKeys, $keys);
    } while ($cursor !== '0');

    echo "Found " . count($allKeys) . " total sessions\n";

    // Check each session for the user ID
    foreach ($allKeys as $key) {
        $sessionData = $redis->get($key);

        if ($sessionData) {
            // Check if this session belongs to our user
            // Laravel stores user ID in the session data
            if (strpos($sessionData, '"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d";i:' . $userId) !== false ||
                strpos($sessionData, 's:7:"user_id";i:' . $userId) !== false) {

                $redis->del($key);
                $deleted++;
                echo "✓ Deleted session: " . str_replace($prefix, '', $key) . "\n";
            }
        }
    }

} elseif ($sessionDriver === 'database') {
    echo "Scanning database for user sessions...\n";

    $table = config('session.table', 'sessions');

    $sessions = DB::table($table)
        ->where('user_id', $userId)
        ->get();

    echo "Found " . count($sessions) . " sessions for user {$userId}\n";

    foreach ($sessions as $session) {
        DB::table($table)->where('id', $session->id)->delete();
        $deleted++;
        echo "✓ Deleted session: {$session->id}\n";
    }

} else {
    echo "Session driver '{$sessionDriver}' is not supported by this script\n";
    exit(1);
}

echo "\n";
echo "====================================\n";
echo "Total sessions deleted: {$deleted}\n";
echo "User {$user->name} has been logged out from all devices\n";
echo "====================================\n";
