<?php

namespace App\Modules\Blog\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Blog\Models\Tag;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;

class TagsController extends Controller
{
    use AuthorizesRequests;
    public function getTags(Request $request) : \Illuminate\Http\JsonResponse
    {
        $this->authorize('read', Tag::class);

        if ($request->input('search')) {
            $query = Tag::where('name', 'like', '%' . $request->input('search') . '%');
        } else {
            $query = Tag::query();
        }

        $tags = $request->has('page')
            ? $query->paginate($request->input('per_page', config('app.per_page', 2)))
            : $query->get();

        $tags->transform(function ($tag) {
            $tag_json = json_decode($tag->name);
            return [
                'id' => $tag->id,
                'name' => [
                    'en' => $tag_json->en ?? null,
                    'ru' => $tag_json->ru ?? null,
                ],
            ];
        });

        return response()->success('Tags list received successfully', $tags);
    }

    public function createTag(Request $request) : \Illuminate\Http\JsonResponse
    {
        $this->authorize('create', Tag::class);

        $request->validate([
            'tag_en' => 'required|string|min:3|max:255',
            'tag_ru' => 'required|string|min:3|max:255',
        ]);

        $tag = new Tag();
        $tag->name = json_encode(['ru' => $request->tag_ru, 'en' => $request->tag_en], JSON_UNESCAPED_UNICODE);
        $tag->save();

        return response()->success('Tag created successful', $tag);
    }

    public function deleteTag($id) : \Illuminate\Http\JsonResponse
    {
        $this->authorize('delete', Tag::class);

        $tag = Tag::find($id);

        if (!$tag) {
            return response()->error('Tag not found', [], 422);
        }

        $tag->delete();

        return response()->success('Tag deleted successful');
    }
}
