<?php

namespace App\Http\Controllers;

use App\Models\Tag;
use Illuminate\Http\Request;
use Inertia\Inertia;

class TagController extends Controller
{
    public function index()
    {
        $tags = Tag::when(request('search'), fn($q, $s) => $q->where('title', 'like', "%{$s}%"))
            ->latest()
            ->orderByDesc('id')
            ->paginate(10)
            ->withQueryString();

        return Inertia::render('Audience/Tags', [
            'tags' => $tags,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title'       => 'required|string|max:255',
            'slug'        => 'required|string|max:255|unique:tags,slug',
            'description' => 'nullable|string',
            'color'       => 'nullable|string|max:20',
        ]);

        $tag = Tag::create($validated);

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'tag' => $tag]);
        }

        return redirect()->route('tags.index')->with('success', 'Tag created successfully.');
    }

    public function update(Request $request, Tag $tag)
    {
        $validated = $request->validate([
            'title'       => 'required|string|max:255',
            'slug'        => 'required|string|max:255|unique:tags,slug,' . $tag->id,
            'description' => 'nullable|string',
            'color'       => 'nullable|string|max:20',
        ]);

        $tag->update($validated);

        return redirect()->route('tags.index')->with('success', 'Tag updated successfully.');
    }

    public function destroy(Tag $tag)
    {
        $tag->delete();

        return redirect()->route('tags.index')->with('success', 'Tag deleted successfully.');
    }

    public function bulkDestroy(Request $request)
    {
        $ids = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:tags,id'
        ])['ids'];

        Tag::whereIn('id', $ids)->delete();

        return redirect()->route('tags.index')->with('success', 'Selected tags deleted.');
    }
}
