<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class BrandController extends Controller
{
    /**
     * Display a listing of the brands.
     */
    public function index()
    {
        $brands = Brand::withCount('products', 'models')
                      ->orderBy('name')
                      ->paginate(15);
        
        return view('settings.brands.index', compact('brands'));
    }

    /**
     * Show the form for creating a new brand.
     */
    public function create()
    {
        return view('settings.brands.create');
    }

    /**
     * Store a newly created brand in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:brands',
            'slug' => 'nullable|string|max:255|unique:brands',
            'website' => 'nullable|url|max:255',
            'description' => 'nullable|string',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $data = [
            'name' => $request->name,
            'slug' => $request->slug ?? Str::slug($request->name),
            'website' => $request->website,
            'description' => $request->description,
            'status' => $request->boolean('status', true),
            'created_by' => Auth::id()
        ];

        if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $logoName = time() . '_' . Str::slug($request->name) . '.' . $logo->getClientOriginalExtension();
            $logo->storeAs('public/brands', $logoName);
            $data['logo'] = $logoName;
        }

        Brand::create($data);

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

    /**
     * Show the form for editing the specified brand.
     */
    public function edit(Brand $brand)
    {
        return view('settings.brands.edit', compact('brand'));
    }

    /**
     * Update the specified brand in storage.
     */
    public function update(Request $request, Brand $brand)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:brands,name,' . $brand->id,
            'slug' => 'nullable|string|max:255|unique:brands,slug,' . $brand->id,
            'website' => 'nullable|url|max:255',
            'description' => 'nullable|string',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $data = [
            'name' => $request->name,
            'slug' => $request->slug ?? Str::slug($request->name),
            'website' => $request->website,
            'description' => $request->description,
            'status' => $request->boolean('status', true),
            'updated_by' => Auth::id()
        ];

        if ($request->hasFile('logo')) {
            // Delete old logo
            if ($brand->logo) {
                \Storage::delete('public/brands/' . $brand->logo);
            }
            
            $logo = $request->file('logo');
            $logoName = time() . '_' . Str::slug($request->name) . '.' . $logo->getClientOriginalExtension();
            $logo->storeAs('public/brands', $logoName);
            $data['logo'] = $logoName;
        }

        $brand->update($data);

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

    /**
     * Remove the specified brand from storage.
     */
    public function destroy(Brand $brand)
    {
        // Check if brand has products
        if ($brand->products()->count() > 0) {
            return back()->with('error', 'Cannot delete brand with products.');
        }

        // Check if brand has models
        if ($brand->models()->count() > 0) {
            return back()->with('error', 'Cannot delete brand with models.');
        }

        // Delete logo
        if ($brand->logo) {
            \Storage::delete('public/brands/' . $brand->logo);
        }

        $brand->delete();

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

    /**
     * Get all brands for API
     */
    public function getAll()
    {
        $brands = Brand::active()->orderBy('name')->get(['id', 'name']);
        return response()->json($brands);
    }
}