<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreBrandRequest;
use App\Http\Requests\Admin\UpdateBrandRequest;
use App\Models\Brand;
use App\Models\Product;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\View\View;

class BrandController extends Controller
{
    public function index(Request $request): View
    {
        $query = Brand::withCount('products');

        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('slug', 'like', "%{$search}%");
            });
        }

        if ($request->filled('status')) {
            $status = $request->get('status');
            if ($status === 'active') {
                $query->where('is_active', true);
            } elseif ($status === 'inactive') {
                $query->where('is_active', false);
            }
        }

        $sortKey = $request->get('sort', 'name_asc');
        $sortMap = [
            'name_asc' => ['name', 'asc'],
            'name_desc' => ['name', 'desc'],
            'products_count_asc' => ['products_count', 'asc'],
            'products_count_desc' => ['products_count', 'desc'],
            'updated_at_desc' => ['updated_at', 'desc'],
            'updated_at_asc' => ['updated_at', 'asc'],
        ];
        [$sort, $order] = $sortMap[$sortKey] ?? ['name', 'asc'];
        if (!isset($sortMap[$sortKey])) {
            $sortKey = 'name_asc';
        }

        $query->orderBy($sort, $order);
        if ($sort !== 'name') {
            $query->orderBy('name', 'asc');
        }

        $brands = $query
            ->paginate(10)
            ->withQueryString();

        $stats = [
            'total' => Brand::count(),
            'active' => Brand::where('is_active', true)->count(),
            'unused' => Brand::doesntHave('products')->count(),
            'products' => Product::whereNotNull('brand_id')->count(),
        ];

        return view('admin.brands.index', compact('brands', 'stats', 'sortKey'));
    }

    public function create(): View
    {
        return view('admin.brands.create');
    }

    public function store(StoreBrandRequest $request): RedirectResponse
    {
        $data = $request->validated();
        
        // Auto-generate slug from name if not provided
        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
            
            // Ensure slug is unique
            $originalSlug = $data['slug'];
            $counter = 1;
            while (Brand::where('slug', $data['slug'])->exists()) {
                $data['slug'] = $originalSlug . '-' . $counter;
                $counter++;
            }
        }

        // Handle logo upload
        if ($request->hasFile('logo')) {
            $data['logo_path'] = $request->file('logo')->store('brands', 'public');
        }

        Brand::create($data);

        return redirect()->route('admin.brands.index')->with('success', 'Brand created successfully!');
    }

    public function edit(Brand $brand): View
    {
        return view('admin.brands.edit', compact('brand'));
    }

    public function update(UpdateBrandRequest $request, Brand $brand): RedirectResponse
    {
        $data = $request->validated();

        // Auto-generate slug if name changed
        if (isset($data['name']) && $data['name'] !== $brand->name) {
            $newSlug = Str::slug($data['name']);
            
            // Ensure slug is unique
            $originalSlug = $newSlug;
            $counter = 1;
            while (Brand::where('slug', $newSlug)->where('id', '!=', $brand->id)->exists()) {
                $newSlug = $originalSlug . '-' . $counter;
                $counter++;
            }
            $data['slug'] = $newSlug;
        }

        // Handle logo upload
        if ($request->hasFile('logo')) {
            // Delete old logo
            if ($brand->logo_path) {
                Storage::disk('public')->delete($brand->logo_path);
            }

            $data['logo_path'] = $request->file('logo')->store('brands', 'public');
        }

        $brand->update($data);

        return redirect()->route('admin.brands.index')->with('success', 'Brand updated successfully!');
    }

    public function destroy(Brand $brand): RedirectResponse
    {
        // Check if brand has products
        $productCount = $brand->products()->count();
        if ($productCount > 0) {
            return redirect()->route('admin.brands.index')
                ->with('error', "Cannot delete brand. It is assigned to {$productCount} product(s). Please remove or reassign products first.");
        }

        // Delete logo if exists
        if ($brand->logo_path) {
            Storage::disk('public')->delete($brand->logo_path);
        }

        $brand->delete();

        return redirect()->route('admin.brands.index')->with('success', 'Brand deleted successfully!');
    }
}
