<?php

namespace App\Http\Controllers\ModCP;

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

class AuthorController extends Controller
{

    use ModCPSearch;

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

        return view('modcp.authors', [
            'items' => $items
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:authors,name',
            'owner_user_id' => [ 'nullable', 'integer', new XfUserExists ],
            'website' => 'nullable|string|max:255',
        ]);

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

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

    public function update(Request $request, Author $author)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:authors,name,' . $author->id,
            'owner_user_id' => [ 'nullable', 'integer', new XfUserExists ],
            'website' => 'nullable|string|max:255',
        ]);

        $author->update([
            'name' => trim($request->name),
            'slug' => EntryHelpers::uniqueSlug( $request->name, Author::class, $author->id ),
            'user_id' => $request->owner_user_id,
            'website' => $request->website,
        ]);

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

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