<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Member;
use App\Models\Region;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RegionsController extends Controller
{
    /**
     * Display a listing of regions and their leaders.
     */
    public function index()
    {
        // Get all predefined regions
        $allRegions = Region::orderBy('name')->get();

        // Get all leaders and regional treasurers with their regions
        $leaders = User::whereIn('role', ['leader', 'regional-treasurer'])
            ->withCount('members')
            ->orderBy('region')
            ->get();

        // Group leaders by region
        $leadersByRegion = $leaders->groupBy('region');

        // Get unassigned leaders
        $unassignedLeaders = User::whereIn('role', ['leader', 'regional-treasurer'])
            ->whereNull('region')
            ->get();

        // Get all potential leaders (any user who isn't already a top-leader or admin)
        $availableLeaders = User::whereNotIn('role', ['top-leader', 'admin'])
            ->orderBy('name')
            ->get();

        return view('regions.index', compact('allRegions', 'leadersByRegion', 'unassignedLeaders', 'availableLeaders'));
    }

    /**
     * Store a new region.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|unique:regions|max:255',
            'description' => 'nullable|string|max:500',
        ]);

        Region::create($request->only('name', 'description'));

        return redirect()->route('regions.index')
            ->with('success', 'Region created successfully.');
    }

    /**
     * Assign or update a leader's region.
     */
    public function assignLeader(Request $request)
    {
        $request->validate([
            'leader_id' => 'required|exists:users,id',
            'region' => 'required|string|max:255',
            'role' => 'required|in:leader,regional-treasurer',
        ]);

        $user = User::findOrFail($request->leader_id);
        
        // Prevent upgrading admins/top-leaders if they were somehow selected
        if (in_array($user->role, ['top-leader', 'admin'])) {
            return redirect()->back()->with('error', 'Cannot reassign region for Top Leaders or Admins through this form.');
        }

        $user->update([
            'region' => $request->region,
            'role' => $request->role
        ]);

        return redirect()->route('regions.index')
            ->with('success', "User promoted to {$request->role} and assigned to {$request->region}.");
    }

    /**
     * Remove a leader's region assignment.
     */
    public function removeLeader($leaderId)
    {
        $leader = User::findOrFail($leaderId);
        $leader->update(['region' => null]);

        return redirect()->route('regions.index')
            ->with('success', 'Leader removed from region.');
    }
}
