#!/usr/bin/env php
<?php

/**
 * Quick Session Manipulation for Security Testing
 *
 * Usage: php manipulate-session.php <profile_id> <profile_type>
 * This will manipulate the MOST RECENT session
 *
 * Examples:
 *   php manipulate-session.php 5 user       # Change to User ID 5
 *   php manipulate-session.php 1 org        # Change to Organization ID 1
 *   php manipulate-session.php 1 bank       # Change to Bank ID 1
 *   php manipulate-session.php 1 admin      # Change to Admin ID 1
 */

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

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

if ($argc < 3) {
    echo "Usage: php manipulate-session.php <profile_id> <profile_type>\n";
    echo "\nExamples:\n";
    echo "  php manipulate-session.php 5 user       # Change to User ID 5\n";
    echo "  php manipulate-session.php 1 org        # Change to Organization ID 1\n";
    echo "  php manipulate-session.php 1 bank       # Change to Bank ID 1\n";
    echo "  php manipulate-session.php 1 admin      # Change to Admin ID 1\n";
    exit(1);
}

$newProfileId = (int) $argv[1];
$typeArg = strtolower($argv[2]);

// Map short type names to full class names
$typeMap = [
    'user' => 'App\\Models\\User',
    'org' => 'App\\Models\\Organization',
    'organization' => 'App\\Models\\Organization',
    'bank' => 'App\\Models\\Bank',
    'admin' => 'App\\Models\\Admin',
];

if (!isset($typeMap[$typeArg])) {
    echo "ERROR: Invalid profile type '$typeArg'\n";
    echo "Valid types: user, org, organization, bank, admin\n";
    exit(1);
}

$newProfileType = $typeMap[$typeArg];

// Get the most recent session
$session = DB::table('sessions')
    ->orderBy('last_activity', 'desc')
    ->first();

if (!$session) {
    echo "ERROR: No active session found\n";
    exit(1);
}

echo "Found session:\n";
echo "  Session ID: {$session->id}\n";
echo "  User ID: {$session->user_id}\n";
echo "  IP: {$session->ip_address}\n";
echo "  Last Activity: " . date('Y-m-d H:i:s', $session->last_activity) . "\n";
echo "\n";

// Laravel encrypts session data, so we need to use the session manager
$sessionManager = app('session')->driver();
$sessionManager->setId($session->id);
$sessionManager->start();

echo "Current session data:\n";
echo "  activeProfileId: " . ($sessionManager->get('activeProfileId') ?? 'NOT SET') . "\n";
echo "  activeProfileType: " . ($sessionManager->get('activeProfileType') ?? 'NOT SET') . "\n";
echo "\n";

// Manipulate
$sessionManager->put('activeProfileId', $newProfileId);
$sessionManager->put('activeProfileType', $newProfileType);
$sessionManager->save();

echo "✅ Session manipulated successfully!\n";
echo "  NEW activeProfileId: $newProfileId\n";
echo "  NEW activeProfileType: $newProfileType\n";
echo "\n";
echo "🔄 Now REFRESH your browser to see the changes!\n";
echo "⚠️  WARNING: This is for security testing only!\n";
