<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Storage;

class ProductosController extends Controller
{
    /*public function index(Request $request)
    {
        $query = $request->input('search');
        $status = $request->input('stock_status');
        $type = $request->input('type');

        $products = Product::query()
            ->when($query, function ($q) use ($query) {
                return $q->where('name', 'like', "%{$query}%");
            })
            ->when($type, function ($q) use ($type) {
                return $q->where('type', $type);
            })
            ->when($status, function ($q) use ($status) {
                if ($status === 'low') {
                    return $q->whereColumn('stock_quantity', '<', 'min_stock_alert')
                             ->where('type', '!=', 'service');
                } 
                elseif ($status === 'medium') {
                    return $q->whereColumn('stock_quantity', '>=', 'min_stock_alert')
                             ->whereRaw('stock_quantity <= (min_stock_alert + 5)')
                             ->where('type', '!=', 'service');
                } 
                elseif ($status === 'ok') {
                    return $q->whereRaw('stock_quantity > (min_stock_alert + 5)')
                             ->where('type', '!=', 'service');
                }
            })
            ->orderBy('stock_quantity', 'asc') 
            ->paginate(10) 
            ->withQueryString(); 

        return view('productos.index', compact('products'));
    }*/
        public function index()
    {
        // Traemos todos los productos ordenados (sin paginar, para que JS los pueda buscar todos)
        $products = Product::orderBy('name', 'asc')->get();

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

    public function create()
    {
        $suppliers = Supplier::orderBy('name')->get();
        return view('productos.create', compact('suppliers'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'            => 'required|string|max:255',
            'price'           => 'required|numeric|min:0',
            'cost'            => 'nullable|numeric|min:0',
            'stock_quantity'  => 'required|integer|min:0',
            'min_stock_alert' => 'required|integer|min:0',
            'type'            => 'required|in:bike,accessory,clothing,spare,service,children,skate,rollers,other', 
            'serial_number'   => 'nullable|string|max:100',
            'image'           => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'suppliers_id'    => 'required|exists:suppliers,id',
            'description'     => 'nullable|string' 
        ]);

        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('products', 'public');
            $validated['image_path'] = $path;
        }
        unset($validated['image']);

        Product::create($validated);

        return redirect()->route('productos.index')
            ->with('success', 'Producto creado correctamente.');
    }

    public function show(Product $product) 
    {
        return view('productos.show', compact('product'));
    }

    public function edit(Product $product)
    {
        $suppliers = Supplier::orderBy('name')->get();
        return view('productos.edit', compact('product', 'suppliers'));
    }

    public function update(Request $request, Product $product)
    {
        $validated = $request->validate([
            'name'            => 'required|string|max:255', 
            'type'            => 'required|in:bike,accessory,clothing,spare,service,children,skate,rollers,other', 
            'price'           => 'required|numeric|min:0',
            'cost'            => 'nullable|numeric|min:0',
            'stock_quantity'  => 'required|integer|min:0',
            'min_stock_alert' => 'required|integer|min:0',
            'serial_number'   => 'nullable|string|max:100',
            'image'           => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'suppliers_id'    => 'required|exists:suppliers,id', 
            'description'     => 'nullable|string'
        ]);

        if ($request->hasFile('image')) {
            if ($product->image_path) {
                Storage::disk('public')->delete($product->image_path);
            }

            $path = $request->file('image')->store('products', 'public');
            $validated['image_path'] = $path;
        }
        unset($validated['image']);
        
        $product->update($validated);

        return redirect()->route('productos.index')
            ->with('success', 'Producto actualizado exitosamente.');
    }

    public function destroy(Product $product)
    {
        if ($product->image_path) {
            Storage::disk('public')->delete($product->image_path);
        }
        
        $product->delete();
        return redirect()->route('productos.index')
            ->with('success', 'Producto eliminado.');
    }
}