<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Clan;
use App\Models\EthnicGroup;
use Illuminate\Http\Request;

class ClanController extends Controller
{
    public function index(Request $request)
    {
        $gid = (int) $request->query('ethnic_group_id', 0);
        $groups = EthnicGroup::orderBy('name')->get(['id','name','country_code']);
        $query = Clan::query()->with(['ethnicGroup','ethnicGroups']);
        if ($gid > 0) {
            $query->where(function($q) use ($gid){
                $q->where('ethnic_group_id', $gid)
                  ->orWhereHas('ethnicGroups', function($r) use ($gid){ $r->where('ethnic_group_id', $gid); });
            });
        }
        $clans = $query->orderBy('name')->paginate(20);

        return view('admin.clans.index', compact('clans', 'groups', 'gid'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'ethnic_group_ids' => ['required','array','min:1'],
            'ethnic_group_ids.*' => ['integer','exists:ethnic_groups,id'],
            'name' => ['required','string','max:255'],
            'description' => ['nullable','string'],
        ]);
        $primary = (int) $data['ethnic_group_ids'][0];
        $clan = Clan::create([
            'ethnic_group_id' => $primary,
            'name' => $data['name'],
            'description' => $data['description'] ?? null,
        ]);
        $clan->ethnicGroups()->sync($data['ethnic_group_ids']);
        return redirect()->route('admin.clans.index', ['ethnic_group_id' => $primary]);
    }

    public function update(Request $request, Clan $clan)
    {
        $data = $request->validate([
            'ethnic_group_ids' => ['required','array','min:1'],
            'ethnic_group_ids.*' => ['integer','exists:ethnic_groups,id'],
            'name' => ['required','string','max:255'],
            'description' => ['nullable','string'],
        ]);
        $primary = (int) $data['ethnic_group_ids'][0];
        $clan->update([
            'ethnic_group_id' => $primary,
            'name' => $data['name'],
            'description' => $data['description'] ?? null,
        ]);
        $clan->ethnicGroups()->sync($data['ethnic_group_ids']);
        return redirect()->route('admin.clans.index', ['ethnic_group_id' => $primary]);
    }

    public function destroy(Request $request, Clan $clan)
    {
        $gid = $clan->ethnic_group_id;
        $clan->delete();
        return redirect()->route('admin.clans.index', ['ethnic_group_id' => $gid]);
    }
}
