<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CategoryController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax() || $request->expectsJson() || $request->has('ajax')) {
            $categories = Category::where('is_active', true)
                ->when($request->search, function ($query, $search) {
                    return $query->where('name', 'like', "%{$search}%");
                })
                ->orderBy('name')
                ->get(['id', 'name']);

            return response()->json(['categories' => $categories]);
        }

        $categories = Category::orderBy('name')->paginate(15);

        return view('admin.products.categories.index', compact('categories'));
    }

    public function store(Request $request): JsonResponse|RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:categories,slug',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
            'is_active' => 'boolean',
        ]);

        // Auto-generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = \Illuminate\Support\Str::slug($validated['name']);
        }

        // Handle image upload
        if ($request->hasFile('image')) {
            $validated['image'] = $request->file('image')->store('categories', 'public');
        }

        $validated['is_active'] = $request->has('is_active') ? $request->boolean('is_active') : true;

        $category = Category::create($validated);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Category created successfully',
                'category' => $category,
            ]);
        }

        return redirect()->route('admin.products.categories.index')->with('success', 'Category created successfully');
    }

    public function show($id)
    {
        $category = Category::findOrFail($id);

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

        return view('admin.products.categories.show', compact('category'));
    }

    public function update(Request $request, $id): JsonResponse|RedirectResponse
    {
        $category = Category::findOrFail($id);

        // If only is_active is being updated (status toggle), allow partial update
        $requestData = $request->except(['_method', '_token']);
        if (count($requestData) === 1 && isset($requestData['is_active'])) {
            $category->update(['is_active' => $request->boolean('is_active')]);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Status updated successfully',
                    'category' => $category->fresh(),
                ]);
            }

            return redirect()->route('admin.products.categories.index')->with('success', 'Status updated successfully');
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:categories,slug,'.$id,
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
            'is_active' => 'boolean',
        ]);

        // Auto-generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = \Illuminate\Support\Str::slug($validated['name']);
        }

        // Handle image upload
        if ($request->hasFile('image')) {
            // Delete old image
            if ($category->image) {
                Storage::disk('public')->delete($category->image);
            }
            $validated['image'] = $request->file('image')->store('categories', 'public');
        }

        $category->update($validated);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Category updated successfully',
                'category' => $category,
            ]);
        }

        return redirect()->route('admin.products.categories.index')->with('success', 'Category updated successfully');
    }

    public function destroy($id)
    {
        $category = Category::findOrFail($id);
        $category->delete();

        if (request()->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Category deleted successfully',
            ]);
        }

        return redirect()->route('admin.products.categories.index')->with('success', 'Category deleted successfully');
    }
}
