<?php

namespace App\Http\Controllers;

use App\Models\District;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Resources\DistrictResource;
use App\Http\Resources\ManagerResource;

class DistrictController extends Controller
{
    /**
     * Отдать все районы + список активных «Менеджеров группы»
     */
    public function forGroupAssignment(Request $r): JsonResponse
    {
        $q = District::query()
            ->when($r->boolean('only_free'),
                fn ($q) => $q->whereNull('group_manager_id'))
            ->when($r->filled('region_id'),
                fn ($q) => $q->where('region_id', $r->region_id))
            ->with(['region', 'groupManager']);

        return response()->json([
            'districts' => DistrictResource::collection($q->get()),
            'managers'  => ManagerResource::collection(
                User::query()
                    ->where('role_id', 4)
                    ->where('is_active', true)
                    ->get()
            ),
        ]);
    }
    /**
     * Назначить Менеджера группы на Район
     */
    public function assignGroupManager(Request $r): JsonResponse
    {
        $data = $r->validate([
            'district_id'      => 'required|exists:districts,id',
            'group_manager_id' => 'nullable|exists:users,id', // nullable = «снять»
        ]);

        District::findOrFail($data['district_id'])
            ->update(['group_manager_id' => $data['group_manager_id']]);

        return response()->json(['success' => true]);
    }

    public function forSubgroupAssignment(Request $r): JsonResponse
    {
        $q = District::with(['region','subgroupManager'])
            ->whereNotNull('group_manager_id');

        if ($r->filled('group_manager_id'))   // фильтр по конкретному group‑менеджеру
            $q->where('group_manager_id', $r->group_manager_id);

        $districts = $q->get();

        // id роли «Менеджер подгруппы» = 5
        $users = User::where('role_id', 5)
            ->where('is_active', true)
            ->get(['id','first_name','middle_name','last_name']);

        return response()->json(compact('districts','users'));
    }
    public function assignSubgroupManager(Request $r): JsonResponse
    {
        $data = $r->validate([
            'district_id'         => 'required|exists:districts,id',
            'subgroup_manager_id' => 'nullable|exists:users,id',
        ]);

        District::findOrFail($data['district_id'])
            ->update(['subgroup_manager_id' => $data['subgroup_manager_id']]);

        return response()->json(['success'=>true]);
    }

    public function getDistrictsForGroupAssignment(): JsonResponse
    {
        $districts = District::with('region')->get();
        $managers  = User::where('role_id', /* id роли “Менеджер группы” */)->get();

        return response()->json([
            'districts' => $districts,
            'managers'  => $managers,
        ]);
    }
}
