<?php

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

use App\Models\User;
use App\Models\Portal;

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

echo "User Portal Access Test\n";
echo str_repeat('=', 100) . "\n\n";

// Check specific user
$email = 'anuradhasampath999@gmail.com';
$user = User::where('email', $email)->with('portals')->first();

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

echo "User: {$user->name} (ID: {$user->id})\n";
echo "Email: {$user->email}\n";
echo "Marketing Officer ID: {$user->marketing_officer_id}\n";
echo "Super Admin: " . ($user->is_super_admin ? 'Yes' : 'No') . "\n";
echo str_repeat('-', 100) . "\n\n";

echo "Assigned Portals:\n";
if ($user->portals->isEmpty()) {
    echo "  ⚠️  NO PORTALS ASSIGNED!\n\n";
} else {
    foreach ($user->portals as $portal) {
        printf("  ✓ %s (key: %s, url: %s)\n", $portal->name, $portal->key, $portal->url);
    }
    echo "\n";
}

echo str_repeat('=', 100) . "\n";
echo "All Available Portals:\n";
echo str_repeat('-', 100) . "\n";

$allPortals = Portal::all();
foreach ($allPortals as $portal) {
    $assigned = $user->portals->contains('id', $portal->id) ? '✓' : ' ';
    printf("  [%s] ID: %d, Name: %s, Key: %s, URL: %s\n", 
        $assigned, $portal->id, $portal->name, $portal->key, $portal->url);
}

echo "\n" . str_repeat('=', 100) . "\n";

$immigoProPortal = Portal::where('key', 'immigopro')->first();
if ($immigoProPortal) {
    echo "✓ ImmigoPro Portal exists (ID: {$immigoProPortal->id})\n";
    
    if ($user->portals->contains('id', $immigoProPortal->id)) {
        echo "✓ User has access to ImmigoPro portal\n";
    } else {
        echo "❌ User does NOT have access to ImmigoPro portal\n";
        echo "   Need to assign portal to user!\n";
    }
} else {
    echo "❌ ImmigoPro portal does not exist in database!\n";
}

echo "\n" . str_repeat('-', 100) . "\n";
echo "Dashboard Card States:\n";
echo str_repeat('-', 100) . "\n";

foreach ($visiblePortals as $portal) {
    $hasAccess = in_array($portal->key, $userPortalKeys);
    $icon = $hasAccess ? '🔓 Accessible' : '🔒 Locked';
    $action = $hasAccess ? '(Can click to open)' : '(Shows lock overlay)';
    
    printf("  %s - %s %s\n", $icon, $portal->name, $action);
}

echo "\n" . str_repeat('=', 100) . "\n";
echo "To test:\n";
echo "1. Login as: {$user->email}\n";
echo "2. Go to: http://localhost:5180/dashboard\n";
echo "3. Accessible portals will be clickable with external link icon\n";
echo "4. Locked portals will show lock icon and display 'Access Denied' message when clicked\n";
