<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\ChampionshipGroupDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Championship\StoreChampionshipGroupRequest;
use App\Http\Requests\Admin\Championship\UpdateChampionshipGroupRequest;
use App\Models\Championship;
use App\Models\ChampionshipGroup;
use App\Services\ChampionshipGroupService;

class ChampionshipGroupController extends Controller
{
    public function __construct(protected ChampionshipGroupService $groupService) {}

    public function index(ChampionshipGroupDataTable $dataTable)
    {
        return view('admin.championship-groups.index', ['dataTable' => $dataTable->html()]);
    }

    public function datatable(ChampionshipGroupDataTable $dataTable)
    {
        return $dataTable->ajax();
    }

    public function create()
    {
        $championships = Championship::query()->orderByDesc('id')->get(['id', 'name']);
        return view('admin.championship-groups.create', compact('championships'));
    }

    public function store(StoreChampionshipGroupRequest $request)
    {
        $payload = $request->validated();

        $this->groupService->createGroup($payload);

        return response()->json([
            'message' => __('Group created successfully'),
            'redirect_url' => route('admin.championship-groups.index'),
        ]);
    }

    public function show(ChampionshipGroup $championship_group)
    {
        $group = $championship_group->load(['championship', 'teams']);
        return view('admin.championship-groups.show', compact('group'));
    }

    public function edit(ChampionshipGroup $championship_group)
    {
        $group = $championship_group;
        $championships = Championship::query()->orderByDesc('id')->get(['id', 'name']);
        return view('admin.championship-groups.edit', compact('group', 'championships'));
    }

    public function update(UpdateChampionshipGroupRequest $request, ChampionshipGroup $championship_group)
    {
        $payload = $request->validated();

        $this->groupService->updateGroup($championship_group, $payload);

        return response()->json([
            'message' => __('Group updated successfully'),
            'redirect_url' => route('admin.championship-groups.index'),
        ]);
    }

    public function destroy(ChampionshipGroup $championship_group)
    {
        $championship_group->delete();
        return response()->json(['success' => true, 'message' => __('Group deleted successfully')]);
    }
}
