<?php

namespace App\Http\Controllers\ModCP;

use App\Helpers\EntryHelpers;
use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Models\Genre;
use App\Models\Platform;
use App\Traits\ModCPSearch;
use Illuminate\Http\Request;

class GameController extends Controller
{

    use ModCPSearch;

    public function index()
    {
        $items = Game::withCount('entries')->orderBy('name')
            ->tap(fn($query) => $this->applySearch($query, ['name']))
            ->paginate(30)->withQueryString();
        $platforms = Platform::orderBy('name')->get();
        $genres = Genre::orderBy('name')->get();

        return view('modcp.games', [
            'items' => $items,
            'platforms' => $platforms,
            'genres' => $genres,
        ]);

    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'platform_id' => 'required|integer|exists:platforms,id',
            'genre_id'    => 'required|integer|exists:genres,id',
        ]);

        Game::create([
            'name' => trim($request->name),
            'platform_id' => $request->platform_id,
            'genre_id' => $request->genre_id,
            'slug' => EntryHelpers::uniqueSlug($request->name, Game::class),
        ]);

        return back()->with('success', 'Game added.');
    }

    public function update(Request $request, Game $game)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'platform_id' => 'required|integer|exists:platforms,id',
            'genre_id' => 'required|integer|exists:genres,id'
        ]);

        $game->update([
            'name' => trim($request->name),
            'platform_id' => $request->platform_id,
            'genre_id' => $request->genre_id,
            'slug' => EntryHelpers::uniqueSlug($request->name, Game::class, $game->id),
        ]);

        return back()->with('success', 'Game updated.');
    }

    public function destroy(Game $game)
    {
        $game->delete();
        return back()->with('success', 'Game deleted.');
    }
}
