<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $query = Product::with('category');

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('marque', 'like', "%{$search}%")
                  ->orWhere('sku', 'like', "%{$search}%");
            });
        }

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        $products = $query->orderBy('id', 'desc')->paginate(20)->withQueryString();
        $categories = Category::all();
        
        return view('admin.pneus.index', compact('products', 'categories'));
    }

    public function create()
    {
        $categories = Category::all();
        return view('admin.pneus.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'marque' => 'required|string|max:255',
            'type_pneu' => 'nullable|in:Tourisme,4x4 / SUV,Camionnette / Utilitaire',
            'saison' => 'nullable|in:4 Saisons,Été,Hiver',
            'prix_actuel' => 'required|numeric|min:0',
            'dimension' => 'nullable|string|max:50',
            'en_stock' => 'required|integer|min:0',
            'dot_annee' => 'nullable|integer|min:2000|max:2099',
            'prix_ancien' => 'nullable|numeric|min:0',
            'pays_fabrication' => 'nullable|string|max:100',
            'largeur' => 'nullable|integer',
            'hauteur' => 'nullable|integer',
            'diametre' => 'nullable|string|max:10',
            'charge_index' => 'nullable|integer',
            'vitesse_index' => 'nullable|in:L,M,N,P,Q,R,S,T,U,H,V,W,Y,(Y),ZR',
            'vitesse_kmh' => 'nullable|string|max:50',
            'runflat' => 'nullable',
            'renforce' => 'nullable',
            'conso_carburant' => 'nullable|string|max:1',
            'adherence_sol_mouille' => 'nullable|string|max:1',
            'bruit_externe_db' => 'nullable|integer',
            'sku' => 'nullable|string|max:100',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        // Fix checkboxes - allow null if not checked
        $validated['runflat'] = $request->has('runflat') ? 1 : null;
        $validated['renforce'] = $request->has('renforce') ? 1 : null;
        
        // Ensure dimension is at least an empty string if null, to avoid DB null constraint if it exists (though migration didn't show it as nullable)
        if (empty($validated['dimension'])) {
            $validated['dimension'] = ''; 
        }

        $productData = $validated;
        unset($productData['image']);
        
        $product = Product::create($productData);

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $marque = Str::slug($product->marque, '_');
            $nom = Str::slug($product->name, '_');
            $extension = $image->getClientOriginalExtension();
            $filename = "{$marque}_{$nom}_{$product->id}." . time() . ".{$extension}";
            $image->storeAs('pneus', $filename, 'public');
            $product->update(['image' => $filename]);
        }

        return redirect()->route('admin.pneus.index')->with('success', 'Produit ajouté avec succès !');
    }

    public function edit($id)
    {
        $product = Product::findOrFail($id);
        $categories = Category::all();
        return view('admin.pneus.edit', compact('product', 'categories'));
    }

    public function update(Request $request, $id)
    {
        $product = Product::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'marque' => 'required|string|max:255',
            'type_pneu' => 'nullable|string|max:100',
            'saison' => 'nullable|string|max:50',
            'prix_actuel' => 'required|numeric|min:0',
            'dimension' => 'nullable|string|max:50',
            'en_stock' => 'required|integer|min:0',
            'dot_annee' => 'nullable|integer',
            'prix_ancien' => 'nullable|numeric|min:0',
            'pays_fabrication' => 'nullable|string|max:100',
            'largeur' => 'nullable|integer',
            'hauteur' => 'nullable|integer',
            'diametre' => 'nullable|string|max:10',
            'charge_index' => 'nullable|integer',
            'vitesse_index' => 'nullable|string|max:10',
            'vitesse_kmh' => 'nullable|string|max:50',
            'runflat' => 'nullable',
            'renforce' => 'nullable',
            'conso_carburant' => 'nullable|string|max:1',
            'adherence_sol_mouille' => 'nullable|string|max:1',
            'bruit_externe_db' => 'nullable|integer',
            'sku' => 'nullable|string|max:100',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        // Specific handling for Tire Category slug check if needed, but keeping it flexible
        $validated['runflat'] = $request->has('runflat') ? 1 : null;
        $validated['renforce'] = $request->has('renforce') ? 1 : null;

        if ($request->hasFile('image')) {
            // Delete old image
            if ($product->image && Storage::disk('public')->exists('pneus/' . $product->image)) {
                Storage::disk('public')->delete('pneus/' . $product->image);
            }
            
            $image = $request->file('image');
            $marque = Str::slug($request->marque, '_');
            $nom = Str::slug($request->name, '_');
            $extension = $image->getClientOriginalExtension();
            $filename = "{$marque}_{$nom}_{$product->id}." . time() . ".{$extension}";
            
            $image->storeAs('pneus', $filename, 'public');
            $validated['image'] = $filename;
        }

        $product->update($validated);

        return redirect()->route('admin.pneus.index')->with('success', 'Produit mis à jour avec succès !');
    }

    public function destroy($id)
    {
        $product = Product::findOrFail($id);
        $product->delete();

        return redirect()->route('admin.pneus.index')->with('success', 'Produit supprimé avec succès!');
    }
}
