<?php

namespace App\Http\Controllers\ModCP;

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

class PlatformController extends Controller
{

    use ModCPSearch;

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

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

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

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

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

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

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

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

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