<?php

// Debugging script to check folder access
// Place this in the root directory and access it via browser

require 'vendor/autoload.php';
$app = require 'bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

try {
    echo "<h2>Debugging Folder Access</h2>";
    
    // Check if user is authenticated
    if (!auth()->check()) {
        echo "<p>❌ User not authenticated</p>";
        exit;
    }
    
    echo "<p>✅ User authenticated: " . auth()->user()->email . "</p>";
    
    // Check user permissions
    $user = auth()->user();
    $hasAccessSharedFolders = $user->can('Access Shared Folders');
    echo "<p>Access Shared Folders permission: " . ($hasAccessSharedFolders ? "✅ Yes" : "❌ No") . "</p>";
    
    // Check user roles
    $roles = $user->roles->pluck('name');
    echo "<p>User roles: " . $roles->implode(', ') . "</p>";
    
    // Check folder access
    $userId = $user->id;
    $userFolderIds = DB::table('folder_user_permissions')
        ->where('user_id', $userId)
        ->pluck('folder_id');
    
    $userRoles = $user->roles->pluck('id');
    $roleFolderIds = DB::table('folder_user_permissions')
        ->whereIn('role_id', $userRoles)
        ->pluck('folder_id');
    
    $allFolderIds = $userFolderIds->merge($roleFolderIds)->unique();
    
    echo "<p>Accessible folder IDs: " . $allFolderIds->implode(', ') . "</p>";
    
    if ($allFolderIds->isEmpty()) {
        echo "<p>⚠️ No folders accessible to this user</p>";
    } else {
        $folders = App\Models\Folder::whereIn('id', $allFolderIds)
            ->whereNull('parent_id')
            ->get();
        echo "<p>✅ Found " . $folders->count() . " root folders</p>";
    }
    
    echo "<p>✅ Debugging complete - if you see this, the controller logic should work</p>";
    
} catch (Exception $e) {
    echo "<p>❌ Error: " . $e->getMessage() . "</p>";
    echo "<p>File: " . $e->getFile() . ":" . $e->getLine() . "</p>";
}