<?php

namespace App\Http\Controllers;

use App\Http\Resources\RegionResource;
use App\Models\Region;
use App\Models\Role\Role;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class RegionController extends Controller
{
    public function index()
    {
        // сразу подтягиваем у каждого региона его список районов
        $regions = Region::with('districts')->get();
        return RegionResource::collection($regions);
    }
    public function forGroupAssignment(): JsonResponse
    {
        $regions = Region::with('groupManager')->get();
        $users   = User::whereIn('role_id', Role::whereIn('name',['Региональный менеджер','Менеджер группы'])->pluck('id'))->get(['id','first_name','last_name']);
        return response()->json(compact('regions','users'));
    }

    public function assignGroupManager(Request $r): JsonResponse
    {
        $r->validate(['region_id'=>'required|exists:regions,id','group_manager_id'=>'required|exists:users,id']);
        Region::find($r->region_id)->update(['group_manager_id'=>$r->group_manager_id]);
        return response()->json(['success'=>true]);
    }
}
