<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Supplier;
class SupplierController extends Controller
{
    /**
     *   grilla de proveedores con buscador
     */
    public function index(Request $request)
    {
        $query = $request->input('search');

        $suppliers = Supplier::query()
            ->when($query, function ($q) use ($query) {
                return $q->where('name', 'like', "%{$query}%");
            })
            ->orderBy('name', 'asc') 
            ->paginate(10)
            ->withQueryString(); 

        return view('suppliers.index', compact('suppliers'));
    }

    /**
     * para crear un proveedor
     */
    public function create()
    {
        return view('suppliers.create');
    }


    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'    => 'required|string|max:255',
            'phone'   => 'nullable|string|max:50',
            'email'   => 'nullable|email|max:255|unique:suppliers,email',
            'address' => 'nullable|string|max:255',
        ]);

        Supplier::create($validated);

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

    /**
     * muestra un proveedor
     */
    public function show(Supplier $supplier)
    {
        return view('suppliers.show', compact('supplier'));
    }

    public function edit(Supplier $supplier)
    {
        return view('suppliers.edit', compact('supplier'));
    }
    
    public function update(Request $request, Supplier $supplier)
    {
        $validated = $request->validate([
            'name'    => 'required|string|max:255',
            'phone'   => 'nullable|string|max:50',
            'email'   => 'nullable|email|max:255|unique:suppliers,email,' . $supplier->id, 
            'address' => 'nullable|string|max:255',
        ]);

        $supplier->update($validated);

        return redirect()->route('suppliers.index')
            ->with('success', 'Proveedor actualizado correctamente.');
    }

    /**
     * elimina (solo si no tiene productos asociados)
     */
    public function destroy(Supplier $supplier)
    {
        try {
            $supplier->delete();
            return redirect()->route('suppliers.index')
                ->with('success', 'Proveedor eliminado correctamente.');
                
        } catch (\Illuminate\Database\QueryException $e) {
            // Si el proveedor tiene productos asociados, va a tirar un error de llave foránea.
            return back()->with('error', 'No se puede eliminar el proveedor porque tiene productos registrados en el inventario.');
        }
    }
    /**
     * trae todos los productos de un proveedor
     */
    public function order(Supplier $supplier)
    {
        $products = $supplier->products()->orderBy('name')->get();
        
        return view('suppliers.order', compact('supplier', 'products'));
    }
}