<?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 "=== Checking User Portal Access ===\n\n";

$email = 'anuradhasampath645@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\n";

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

// Assign the default portals if not already assigned
$defaultPortalKeys = ['lms', 'payments', 'user_portal'];
$defaultPortals = Portal::whereIn('key', $defaultPortalKeys)->get();

echo "Assigning default portals (LMS, Payments, User Portal)...\n";

$assignedCount = 0;
foreach ($defaultPortals as $portal) {
    if (!$user->portals->contains('id', $portal->id)) {
        $user->portals()->attach($portal->id);
        echo "  ✓ Assigned: {$portal->name}\n";
        $assignedCount++;
    } else {
        echo "  - Already has: {$portal->name}\n";
    }
}

if ($assignedCount > 0) {
    echo "\n✅ Successfully assigned {$assignedCount} portal(s)!\n";
} else {
    echo "\n✓ User already has all default portals assigned.\n";
}

echo "\n=== Final Portal Access ===\n";
$user->load('portals');
foreach ($user->portals as $portal) {
    echo "  ✓ {$portal->name} (key: {$portal->key})\n";
}
