<?php

namespace App\Http\Controllers;

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

class TagController extends Controller
{
    public function index()
    {
        $tags = Tag::latest()->get();
        return view('admin.blog.tag', compact('tags'));
    }

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

        Tag::create(['name' => $request->name]);

        return response()->json([
            'success' => true,
            'message' => 'Tag created successfully'
        ]);
    }

    public function destroy(Tag $tag)
    {
        // Optional: check if tag is used in blogs before deletion
        if ($tag->blogs()->exists()) {
            return response()->json([
                'success' => false,
                'message' => 'Cannot delete tag with associated blogs.'
            ], 400);
        }

        $tag->delete();

        return response()->json([
            'success' => true,
            'message' => 'Tag deleted successfully'
        ]);
    }
}
