<?php

namespace App\Http\Controllers\Admin;

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

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

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

        $brands = Brand::orderBy('name')->paginate(15);

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

    public function store(Request $request): JsonResponse|RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:brands,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('brands', 'public');
        }

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

        $brand = Brand::create($validated);

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

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

    public function show($id)
    {
        $brand = Brand::findOrFail($id);

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

        return view('admin.products.brands.show', compact('brand'));
    }

    public function update(Request $request, $id): JsonResponse|RedirectResponse
    {
        $brand = Brand::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'])) {
            $brand->update(['is_active' => $request->boolean('is_active')]);

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

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

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:brands,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 ($brand->image) {
                Storage::disk('public')->delete($brand->image);
            }
            $validated['image'] = $request->file('image')->store('brands', 'public');
        }

        $brand->update($validated);

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

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

    public function destroy($id)
    {
        $brand = Brand::findOrFail($id);
        $brand->delete();

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

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