<?php

namespace App\Http\Controllers\ModCP;

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

class GenreController extends Controller
{

    use ModCPSearch;

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

        return view('modcp.resources', [
            'items' => $items,
            'title' => 'Genres',
            'singular' => 'Genre',
            'storeRoute' => 'modcp.genres.store',
            'updateRoute' => 'modcp.genres.update',
            'destroyRoute' => 'modcp.genres.destroy'
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:genres,name',
        ]);

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

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

    public function update(Request $request, Genre $genre)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:genres,name,' . $genre->id,
        ]);

        $genre->update([
            'name' => trim($request->name),
            'slug' => EntryHelpers::uniqueSlug( $request->name, Genre::class, $genre->id ),
        ]);

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

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