<?php

namespace App\Http\Controllers\ModCP;

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

class LanguageController extends Controller
{

    use ModCPSearch;

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

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

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

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

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

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

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

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

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