<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use App\Models\Folder;
use App\Models\FileMetadata;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\User;
use App\Notifications\FolderSharedNotification;
use Illuminate\Support\Facades\DB;
use App\Helpers\AuditLogger;
class FolderController extends Controller
{
    // Return folder info as JSON for modal
    public function info($id)
    {
        $folder = Folder::findOrFail($id);
        $creator = $folder->created_by ? \App\Models\User::find($folder->created_by) : null;
        $parent = $folder->parent_id ? \App\Models\Folder::find($folder->parent_id) : null;
        return response()->json([
            'id' => $folder->id,
            'name' => $folder->name,
            'path' => $folder->path,
            'parent_name' => $parent ? $parent->name : null,
            'description' => $folder->description,
            'created_by' => $creator ? trim($creator->first_name . ' ' . $creator->last_name) : null,
            'created_at' => $folder->created_at ? $folder->created_at->toDateTimeString() : null,
        ]);
    }
    // Show all folders
    public function index()
    {
        $folders = Folder::whereNull('parent_id')->with('children')->get();
        
        // Add these lines to fetch users and roles
        $users = User::select('id', 'first_name', 'last_name', 'email')
                     ->orderBy('first_name')
                     ->get();
        
        $roles = Role::select('id', 'name')
                     ->orderBy('name')
                     ->get();
        
        return view('folders.index', compact('folders', 'users', 'roles'));
    }

    // Show create folder form
    public function create()
    {
        $parentFolders = Folder::all();
        return view('folders.create', compact('parentFolders'));
    }

    // Store new folder
    public function store(Request $request)
    {
        try {
            // Get folder name from either 'name' or 'folder_name' field
            $name = $request->input('name') ?: $request->input('folder_name');
            
            $request->validate([
                'parent_id' => 'nullable|exists:folders,id',
                'description' => 'nullable|string|max:1000',
            ]);
            
            // Validate folder name
            if (!$name || empty(trim($name))) {
                throw new \Illuminate\Validation\ValidationException(
                    validator([], []), 
                    ['folder_name' => ['Folder name is required.']]
                );
            }
            
            if (strlen($name) > 255) {
                throw new \Illuminate\Validation\ValidationException(
                    validator([], []), 
                    ['folder_name' => ['Folder name must not exceed 255 characters.']]
                );
            }

            $parent_id = $request->input('parent_id');
            $description = $request->input('description');
            
            // Check for duplicate names in the same parent folder
            $existingFolder = Folder::where('name', $name)
                ->where('parent_id', $parent_id)
                ->first();
                
            if ($existingFolder) {
                if ($request->expectsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => 'A folder with this name already exists in the selected location.'
                    ], 422);
                }
                return back()->withErrors(['name' => 'A folder with this name already exists in the selected location.']);
            }

            $parentFolder = $parent_id ? Folder::find($parent_id) : null;
            $folderPath = $parentFolder ? rtrim($parentFolder->path, '/') . '/' . $name : $name;

            // Create folder on network drive
            try {
                Storage::disk('network')->makeDirectory($folderPath);
            } catch (\Exception $e) {
                \Log::error('Failed to create directory on network drive: ' . $e->getMessage());
                // Continue anyway - folder might already exist on filesystem
            }

            // Save to database
            $folder = Folder::create([
                'name' => $name,
                'path' => $folderPath,
                'parent_id' => $parent_id,
                'description' => $description,
                'created_by' => Auth::id(),
            ]);

            AuditLogger::log('folder', $folder->id, 'created', null, [
                'id' => $folder->id,
                'name' => $folder->name,
                'path' => $folder->path,
                'parent_id' => $folder->parent_id,
                'description' => $folder->description,
                'created_by' => $folder->created_by,
            ]);

            // If this is a subfolder, inherit permissions from parent
            if ($parent_id) {
                $this->inheritParentPermissions($folder->id, $parent_id);
            }

            // Return JSON response for AJAX requests
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Folder created successfully!',
                    'folder' => [
                        'id' => $folder->id,
                        'name' => $folder->name,
                        'path' => $folder->path
                    ]
                ]);
            }

            return redirect()->route('folders.index')->with('toast', [
                'message' => 'Folder created successfully!',
                'type' => 'success'
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed: ' . implode(', ', $e->validator->errors()->all())
                ], 422);
            }
            return back()->withErrors($e->validator)->withInput();
            
        } catch (\Exception $e) {
            \Log::error('Error creating folder: ' . $e->getMessage());
            
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error creating folder: ' . $e->getMessage()
                ], 500);
            }
            
            return back()->with('toast', [
                'message' => 'Error creating folder: ' . $e->getMessage(),
                'type' => 'error'
            ]);
        }
    }

    // Show a folder's details
    public function show($id)
    {
        $folder = Folder::findOrFail($id);
        return view('folders.show', compact('folder'));
    }

    // Delete a folder
    public function destroy($id)
    {
        $folder = Folder::findOrFail($id);
        $before = [
            'id' => $folder->id,
            'name' => $folder->name,
            'path' => $folder->path,
            'parent_id' => $folder->parent_id,
            'created_by' => $folder->created_by,
        ];
        
        // Allow only the creator, admin, or super admin to delete
        $user = Auth::user();
        $isCreator = $folder->created_by === $user->id;
        $isAdmin = $user->hasAnyRole(['Super Admin', 'super admin', 'Admin', 'admin']);
        $canDeleteFolders = $user->can('Delete Folder');
        
        if (!($isCreator || $isAdmin || $canDeleteFolders)) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to delete this folder.'
            ], 403);
        }
        
        try {
            // Get all folder IDs that will be deleted (including subfolders)
            $allFolderIds = $this->getAllSubfolderIds($id);
            
            // Delete permissions for all folders that will be deleted
            DB::table('folder_user_permissions')
                ->whereIn('folder_id', $allFolderIds)
                ->delete();
            
            // Delete all file metadata for files in these folders
            foreach ($allFolderIds as $folderId) {
                $folderToDelete = Folder::find($folderId);
                if ($folderToDelete) {
                    FileMetadata::where('file_path', 'LIKE', $folderToDelete->path . '%')->delete();
                }
            }
            
            // Delete folder from network drive (this will delete all contents recursively)
            Storage::disk('network')->deleteDirectory($folder->path);
            
            // Delete all subfolders from database (in reverse order to avoid foreign key issues)
            $subfolderIds = array_reverse(array_slice($allFolderIds, 1)); // Remove parent folder, reverse order
            foreach ($subfolderIds as $subfolderId) {
                Folder::where('id', $subfolderId)->delete();
            }
            
            // Finally delete the parent folder
            $folder->delete();

            AuditLogger::log('folder', $id, 'deleted', $before, null);
            
            $deletedCount = count($allFolderIds);
            $message = $deletedCount > 1 
                ? "Folder and {$deletedCount} subfolder(s) deleted successfully!" 
                : "Folder deleted successfully!";
                
            return response()->json([
                'success' => true,
                'message' => $message
            ]);
            
        } catch (\Exception $e) {
            \Log::error('Error deleting folder', [
                'folder_id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Error deleting folder: ' . $e->getMessage()
            ], 500);
        }
    }

    public function share(Request $request)
    {
        // Add debugging
        \Log::info('Share request received', [
            'folder_id' => $request->folder_id,
            'users' => $request->users,
            'roles' => $request->roles,
            'all_data' => $request->all(),
            'user_id' => auth()->id(),
            'user_email' => auth()->user()?->email
        ]);
        
        // Check if user is authenticated
        if (!auth()->check()) {
            \Log::error('Unauthenticated user trying to share folder');
            return response()->json(['success' => false, 'message' => 'Authentication required'], 401);
        }
        
        // Check if user has Share Folder permission
        if (!auth()->user()->can('Share Folder')) {
            \Log::error('User does not have Share Folder permission', [
                'user_id' => auth()->id(),
                'user_permissions' => auth()->user()->permissions->pluck('name')->toArray(),
                'user_roles' => auth()->user()->roles->pluck('name')->toArray()
            ]);
            return response()->json(['success' => false, 'message' => 'You do not have permission to share folders'], 403);
        }
        
        try {
            $request->validate([
                'folder_id' => 'required|exists:folders,id',
                'users' => 'nullable|array',
                'users.*' => 'exists:users,id',
                'roles' => 'nullable|array', 
                'roles.*' => 'exists:roles,id'
            ]);
            
            $folderId = $request->folder_id;
            $userIds = $request->users ?? [];
            $roleIds = $request->roles ?? [];
            
            $folder = Folder::findOrFail($folderId);
            
            // Get all folder IDs including subfolders recursively
            $allFolderIds = $this->getAllSubfolderIds($folderId);
            
            // Share with users and roles - apply to parent folder and all subfolders
            $sharedBy = auth()->user()->name ?? (auth()->user()->first_name . ' ' . auth()->user()->last_name);
            $allUserIds = collect($userIds);
            // Collect user IDs from roles
            if (!empty($roleIds)) {
                foreach ($roleIds as $roleId) {
                    $role = \Spatie\Permission\Models\Role::find($roleId);
                    if ($role) {
                        $allUserIds = $allUserIds->merge($role->users->pluck('id'));
                    }
                }
            }
            // Remove duplicates
            $allUserIds = $allUserIds->unique()->values();
            // Apply permissions for all folders and users
            foreach ($allFolderIds as $currentFolderId) {
                foreach ($allUserIds as $userId) {
                    DB::table('folder_user_permissions')->updateOrInsert([
                        'folder_id' => $currentFolderId,
                        'user_id' => $userId,
                        'role_id' => null
                    ], [
                        'created_at' => now(),
                        'updated_at' => now()
                    ]);
                }
            }
            // Notify each user only once, and only for the main folder (not for every subfolder)
            foreach ($allUserIds as $userId) {
                $user = User::find($userId);
                if ($user) {
                    // Prevent duplicate notification for same user/folder
                    $alreadyNotified = \DB::table('notifications')
                        ->where('notifiable_id', $userId)
                        ->where('notifiable_type', 'App\\Models\\User')
                        ->where('type', 'App\\Notifications\\FolderSharedNotification')
                        ->whereJsonContains('data->folder_id', $folder->id)
                        ->whereNull('read_at')
                        ->exists();
                    if (!$alreadyNotified) {
                        $user->notify(new FolderSharedNotification($folder, $sharedBy));
                    }
                }
            }
            
            \Log::info('Folder shared successfully', [
                'folder_id' => $folderId,
                'total_folders_affected' => count($allFolderIds),
                'users_count' => count($userIds),
                'roles_count' => count($roleIds)
            ]);

            AuditLogger::log('folder_share', $folder->id, 'shared', null, [
                'folder_id' => $folder->id,
                'folder_name' => $folder->name,
                'users' => array_values($userIds),
                'roles' => array_values($roleIds),
                'folders_affected' => count($allFolderIds),
            ]);
            
            // Return JSON response for AJAX
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Folder and all subfolders shared successfully!'
                ]);
            }
            
            // Regular form submission
            return redirect()->back()->with('toast', [
                'message' => 'Folder and all subfolders shared successfully!',
                'type' => 'success'
            ]);
            
        } catch (\Exception $e) {
            \Log::error('Error sharing folder', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error sharing folder: ' . $e->getMessage()
                ]);
            }
            
            return redirect()->back()->with('toast', [
                'message' => 'Error sharing folder: ' . $e->getMessage(),
                'type' => 'error'
            ]);
        }
    }

public function sharedAccess($folderId)
{
    // Get permissions with user/role details
    $userPermissions = DB::table('folder_user_permissions')
        ->select('folder_user_permissions.user_id', 'users.first_name', 'users.last_name', 'users.email')
        ->leftJoin('users', 'folder_user_permissions.user_id', '=', 'users.id')
        ->where('folder_user_permissions.folder_id', $folderId)
        ->whereNotNull('folder_user_permissions.user_id')
        ->get();

    $rolePermissions = DB::table('folder_user_permissions')
        ->select('folder_user_permissions.role_id', 'roles.name')
        ->leftJoin('roles', 'folder_user_permissions.role_id', '=', 'roles.id')
        ->where('folder_user_permissions.folder_id', $folderId)
        ->whereNotNull('folder_user_permissions.role_id')
        ->get();

    // Format the data for the frontend
    $users = $userPermissions->map(function ($permission) {
        return [
            'id' => $permission->user_id,
            'first_name' => $permission->first_name,
            'last_name' => $permission->last_name,
            'email' => $permission->email
        ];
    });

    $roles = $rolePermissions->map(function ($permission) {
        return [
            'id' => $permission->role_id,
            'name' => $permission->name
        ];
    });

    // Return as JSON for AJAX
    return response()->json([
        'users' => $users,
        'roles' => $roles,
    ]);
}

public function myFolders()
{
    $userId = auth()->id();

    // Get folder IDs where the user is assigned directly
    $userFolderIds = DB::table('folder_user_permissions')
        ->where('user_id', $userId)
        ->pluck('folder_id');

    // Get folder IDs where the user has access through roles
    $userRoles = auth()->user()->roles->pluck('id');
    $roleFolderIds = DB::table('folder_user_permissions')
        ->whereIn('role_id', $userRoles)
        ->pluck('folder_id');

    // Combine both sets of folder IDs
    $allFolderIds = $userFolderIds->merge($roleFolderIds)->unique();


    if ($allFolderIds->isEmpty()) {
        $folders = collect([]);
    } else {
        // 1. Get all root folders the user can access
        $rootFolders = Folder::whereIn('id', $allFolderIds)
            ->where(function($query) {
                $query->whereNull('parent_id')->orWhere('parent_id', 0);
            })
            ->with(['children' => function($query) use ($allFolderIds) {
                $query->whereIn('id', $allFolderIds)
                      ->withCount('children');
            }])
            ->withCount(['children' => function($query) use ($allFolderIds) {
                $query->whereIn('id', $allFolderIds);
            }])
            ->orderBy('name')
            ->get();

        // 2. Get all non-root folders the user can access whose parent is NOT accessible (orphans)
        $accessibleParentIds = $rootFolders->pluck('id');
        $orphanSubfolders = Folder::whereIn('id', $allFolderIds)
            ->where(function($query) {
                $query->whereNotNull('parent_id')->where('parent_id', '!=', 0);
            })
            ->where(function($query) use ($allFolderIds) {
                $query->whereNotIn('parent_id', $allFolderIds);
            })
            ->withCount(['children' => function($query) use ($allFolderIds) {
                $query->whereIn('id', $allFolderIds);
            }])
            ->orderBy('name')
            ->get();

        // 3. Merge both collections for a mixed list
        $folders = $rootFolders->concat($orphanSubfolders);
    }

    // Ensure $folders is always a collection (even if empty)
    if (!$folders) {
        $folders = collect([]);
    }

    // Get users and roles for sharing functionality
    $users = User::select('id', 'first_name', 'last_name', 'email')
        ->orderBy('first_name')
        ->orderBy('last_name')
        ->get();
    
    $roles = Role::select('id', 'name')
        ->orderBy('name')
        ->get();

    $files = [];
    return view('folders.my_folder', compact('folders', 'users', 'roles', 'files'));
}

// Get shared access for a folder
public function getSharedAccess($folderId)
{
    // Get users with their permission levels (where user_id is not null)
    $users = DB::table('folder_user_permissions')
        ->join('users', 'folder_user_permissions.user_id', '=', 'users.id')
        ->where('folder_user_permissions.folder_id', $folderId)
        ->whereNotNull('folder_user_permissions.user_id')
        ->select(
            'users.id',
            'users.first_name',
            'users.last_name',
            'users.email'
        )
        ->get();
        
    // Get roles (where role_id is not null)
    $roles = DB::table('folder_user_permissions')
        ->join('roles', 'folder_user_permissions.role_id', '=', 'roles.id')
        ->where('folder_user_permissions.folder_id', $folderId)
        ->whereNotNull('folder_user_permissions.role_id')
        ->select(
            'roles.id',
            'roles.name'
        )
        ->get();
    
    return response()->json([
        'users' => $users,
        'roles' => $roles
    ]);
}

// Remove user access
public function removeUserAccess(Request $request, $folderId)
{
    try {
        $folder = Folder::findOrFail($folderId);

        // Get all folder IDs including subfolders
        $allFolderIds = $this->getAllSubfolderIds($folderId);
        
        // Remove user access from all folders and subfolders
        foreach ($allFolderIds as $currentFolderId) {
            DB::table('folder_user_permissions')
                ->where('folder_id', $currentFolderId)
                ->where('user_id', $request->user_id)
                ->whereNotNull('user_id')
                ->delete();
        }

        AuditLogger::log('folder_share', $folderId, 'access_removed', null, [
            'folder_id' => $folderId,
            'folder_name' => $folder->name,
            'user_id_removed' => (int) $request->user_id,
            'folders_affected' => count($allFolderIds),
        ]);
            
        return response()->json(['success' => true, 'message' => 'User access removed from folder and all subfolders']);
    } catch (\Exception $e) {
        return response()->json(['success' => false, 'message' => $e->getMessage()]);
    }
}

// Remove role access
public function removeRoleAccess(Request $request, $folderId)
{
    try {
        $folder = Folder::findOrFail($folderId);

        // Get all folder IDs including subfolders
        $allFolderIds = $this->getAllSubfolderIds($folderId);
        
        // Remove role access from all folders and subfolders
        foreach ($allFolderIds as $currentFolderId) {
            DB::table('folder_user_permissions')
                ->where('folder_id', $currentFolderId)
                ->where('role_id', $request->role_id)
                ->whereNotNull('role_id')
                ->delete();
        }

        AuditLogger::log('folder_share', $folderId, 'access_removed', null, [
            'folder_id' => $folderId,
            'folder_name' => $folder->name,
            'role_id_removed' => (int) $request->role_id,
            'folders_affected' => count($allFolderIds),
        ]);
            
        return response()->json(['success' => true, 'message' => 'Role access removed from folder and all subfolders']);
    } catch (\Exception $e) {
        return response()->json(['success' => false, 'message' => $e->getMessage()]);
    }
}

public function getFolderContents($id)
{
    try {
        $user = Auth::user();
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized'
            ], 401);
        }

        $isPrivilegedRole = $user->hasAnyRole(['Super Admin', 'super admin', 'Admin', 'admin']);
        $canViewFolders = $user->can('View Folder') || $user->can('View My Folder');

        if (!$isPrivilegedRole && !$canViewFolders) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to view folder contents.'
            ], 403);
        }

        $folder = Folder::findOrFail($id);
        
        // Get subfolders of this folder from database
        $subfolders = Folder::where('parent_id', $id)
            ->withCount('children')
            ->orderBy('name')
            ->get();
        
        $contents = [];
        
        // Add subfolders to contents
        foreach ($subfolders as $subfolder) {
            $contents[] = [
                'id' => $subfolder->id,
                'name' => $subfolder->name,
                'type' => 'folder',
                'items_count' => $subfolder->children_count,
                'created_by' => $subfolder->created_by,
                'can_delete' => $subfolder->created_by === Auth::id(),
                'created_at' => $subfolder->created_at->format('M d, Y'),
                'updated_at' => $subfolder->updated_at->format('M d, Y')
            ];
        }
        
        // List all files in this folder from the database (the source of truth for
        // which files belong to a folder). Files are stored on the public disk under
        // "uploads/", so sizes are read from there via each record's file_path.
        $fileRows = \App\Models\FileMetadata::where('folder_id', $id)
            ->orderByDesc('created_at')
            ->get()
            ->unique('file_name'); // metadata may have several tag rows per file

        foreach ($fileRows as $meta) {
            $fileName = $meta->file_name;
            $filePath = $meta->file_path ?: ('uploads/' . $fileName);
            $fileSize = 'Unknown size';
            try {
                if (\Storage::disk('public')->exists($filePath)) {
                    $fileSize = $this->formatFileSize(\Storage::disk('public')->size($filePath));
                }
            } catch (\Exception $e) {}

            $contents[] = [
                'name' => $fileName,
                'type' => 'file',
                'file_size' => $fileSize,
                'created_by' => $meta->uploaded_by,
                'can_delete' => $meta->uploaded_by === Auth::id(),
                'created_at' => $meta->created_at ? $meta->created_at->format('M d, Y') : null,
                'updated_at' => $meta->updated_at ? $meta->updated_at->format('M d, Y') : null,
            ];
        }
        
        return response()->json([
            'success' => true,
            'folder' => [
                'id' => $folder->id,
                'name' => $folder->name,
                'path' => $folder->path
            ],
            'contents' => $contents
        ]);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error loading folder contents: ' . $e->getMessage()
        ], 500);
    }
}

/**
 * Format file size in human readable format
 */
private function formatFileSize($bytes)
{
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

/**
 * Recursively get all subfolder IDs including the parent folder
 */
private function getAllSubfolderIds($folderId)
{
    $folderIds = [$folderId]; // Include the parent folder itself
    
    // Get direct children
    $children = Folder::where('parent_id', $folderId)->pluck('id');
    
    // Recursively get all descendants
    foreach ($children as $childId) {
        $folderIds = array_merge($folderIds, $this->getAllSubfolderIds($childId));
    }
    
    return array_unique($folderIds);
}

/**
 * Inherit permissions from parent folder when creating a new subfolder
 */
private function inheritParentPermissions($childFolderId, $parentFolderId)
{
    // Get all permissions from parent folder
    $parentPermissions = DB::table('folder_user_permissions')
        ->where('folder_id', $parentFolderId)
        ->get();
    
    // Apply each permission to the child folder
    foreach ($parentPermissions as $permission) {
        DB::table('folder_user_permissions')->updateOrInsert([
            'folder_id' => $childFolderId,
            'user_id' => $permission->user_id,
            'role_id' => $permission->role_id
        ], [
            'created_at' => now(),
            'updated_at' => now()
        ]);
    }
    
    \Log::info('Inherited permissions for new subfolder', [
        'child_folder_id' => $childFolderId,
        'parent_folder_id' => $parentFolderId,
        'permissions_inherited' => count($parentPermissions)
    ]);
}

/**
 * Rename a folder
 */
public function renameFolder(Request $request, $id)
{
    try {
        $request->validate([
            'folder_name' => 'required|string|max:255',
        ]);

        $folder = Folder::findOrFail($id);
        
        // Check if user has access to this folder (either created by them or shared with them)
        $hasAccess = $folder->created_by === Auth::id() || 
                     DB::table('folder_user_permissions')
                         ->where('folder_id', $id)
                         ->where(function($query) {
                             $query->where('user_id', Auth::id())
                                   ->orWhereIn('role_id', Auth::user()->roles->pluck('id'));
                         })
                         ->exists();
        
        if (!$hasAccess) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to rename this folder.'
            ], 403);
        }

        $oldName = $folder->name;
        $before = [
            'id' => $folder->id,
            'name' => $folder->name,
            'path' => $folder->path,
            'parent_id' => $folder->parent_id,
        ];
        $newName = $request->input('folder_name');

        // Check if the name is actually different
        if ($oldName === $newName) {
            return response()->json([
                'success' => false,
                'message' => 'The new name is the same as the current name.'
            ], 400);
        }

        // Check for duplicate names in the same parent folder
        $duplicateCheck = Folder::where('parent_id', $folder->parent_id)
            ->where('name', $newName)
            ->where('id', '!=', $id)
            ->first();

        if ($duplicateCheck) {
            return response()->json([
                'success' => false,
                'message' => 'A folder with this name already exists in the same location.'
            ], 400);
        }

        // Update the folder name
        $folder->name = $newName;
        $folder->save();

        AuditLogger::log('folder', $folder->id, 'renamed', $before, [
            'id' => $folder->id,
            'name' => $folder->name,
            'path' => $folder->path,
            'parent_id' => $folder->parent_id,
        ]);

        \Log::info('Folder renamed successfully', [
            'folder_id' => $id,
            'old_name' => $oldName,
            'new_name' => $newName,
            'user_id' => Auth::id()
        ]);

        return response()->json([
            'success' => true,
            'message' => "Folder renamed from '{$oldName}' to '{$newName}' successfully!",
            'folder' => [
                'id' => $folder->id,
                'name' => $folder->name,
                'old_name' => $oldName
            ]
        ]);

    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Validation failed: ' . implode(', ', $e->validator->errors()->all())
        ], 422);
    } catch (\Exception $e) {
        \Log::error('Error renaming folder', [
            'folder_id' => $id,
            'error' => $e->getMessage(),
            'user_id' => Auth::id()
        ]);

        return response()->json([
            'success' => false,
            'message' => 'An error occurred while renaming the folder. Please try again.'
        ], 500);
    }
}

}
