<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserManagementController extends Controller
{
    /**
     * Display list of all users
     */
    public function index()
    {
        $users = User::orderBy('created_at', 'desc')->paginate(20);
        
        $userStats = [
            'total' => User::count(),
            'admins' => User::where('role', 'admin')->count(),
            'topLeaders' => User::where('role', 'top-leader')->count(),
            'leaders' => User::where('role', 'leader')->count(),
            'treasurers' => User::where('role', 'treasurer')->count(),
            'regionalTreasurers' => User::where('role', 'regional-treasurer')->count(),
            'members' => User::where('role', 'user')->count(),
        ];
        
        $regions = \App\Models\Region::orderBy('name')->get();
        $leaders = User::where('role', 'leader')->orderBy('name')->get();
        return view('admin.users.index', compact('users', 'userStats', 'regions', 'leaders'));
    }
    
    /**
     * Update user role
     */
    public function updateRole(Request $request, User $user)
    {
        $request->validate([
            'role' => 'required|in:user,leader,treasurer,regional-treasurer,top-leader,admin',
            'region' => 'nullable|string|max:255'
        ]);
        
        // Prevent self-demotion
        if ($user->id === auth()->id() && $request->role !== 'top-leader' && $request->role !== 'admin') {
            return redirect()->back()->with('error', 'You cannot change your own role.');
        }
        
        $oldRole = $user->role;
        $user->role = $request->role;
        
        // Update region if provided, or clear if role changed to one that doesn't usually use region
        if ($request->filled('region')) {
            $user->region = $request->region;
        } elseif (!in_array($request->role, ['leader', 'regional-treasurer'])) {
            // Optional: clear region if role demoted to plain member/treasurer/admin
            // $user->region = null; 
        }

        $user->save();
        
        return redirect()->back()->with('success', "User updated: role changed from {$oldRole} to {$request->role}" . ($user->region ? " in {$user->region} region." : "."));
    }
    
    /**
     * Delete user
     */
    public function destroy(User $user)
    {
        // Prevent self-deletion
        if ($user->id === auth()->id()) {
            return redirect()->back()->with('error', 'You cannot delete your own account.');
        }
        
        $user->delete();
        
        return redirect()->back()->with('success', 'User deleted successfully.');
    }
}
