<?php

namespace App\Http\Controllers;

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

class TagController extends Controller
{
    /**
     * Display a listing of tags.
     */
    public function index(Request $request)
    {
        $tags = $request->user()
            ->tags()
            ->withCount('transactions')
            ->orderBy('name')
            ->get();

        return view('tags.index', compact('tags'));
    }

    /**
     * Store a newly created tag.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'color' => 'nullable|string|regex:/^#[0-9A-Fa-f]{6}$/',
        ]);

        $tag = Tag::create([
            'user_id' => $request->user()->id,
            'name' => $validated['name'],
            'slug' => Str::slug($validated['name']),
            'color' => $validated['color'] ?? '#8B5CF6',
        ]);

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

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

    /**
     * Update the specified tag.
     */
    public function update(Request $request, Tag $tag)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'color' => 'nullable|string|regex:/^#[0-9A-Fa-f]{6}$/',
        ]);

        $tag->update([
            'name' => $validated['name'],
            'slug' => Str::slug($validated['name']),
            'color' => $validated['color'] ?? $tag->color,
        ]);

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

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

    /**
     * Remove the specified tag.
     */
    public function destroy(Tag $tag)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $tag->delete();

        if (request()->expectsJson()) {
            return response()->json(['success' => true]);
        }

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

    /**
     * Get tags for autocomplete (AJAX).
     */
    public function search(Request $request)
    {
        $query = $request->get('q', '');

        $tags = $request->user()
            ->tags()
            ->where('name', 'like', "%{$query}%")
            ->limit(10)
            ->get();

        return response()->json($tags);
    }
}
