<?php

namespace App\Http\Controllers;

use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SupplierController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $suppliers = Supplier::orderBy('created_at', 'desc')->with('user')->whereDeletedAt(null)->paginate(10);
        return view('suppliers.index', compact('suppliers'));
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'address' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'required|string|min:10',
            'status' => 'required|in:actif,archivé',
        ]);

        $validated['user_id'] = Auth::id();

        $supplier = Supplier::create($validated);

        return redirect()->route('suppliers.index')->with('success', 'Fournisseur créé avec succès');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Mise à jour du fournisseur
     */
    public function update(Request $request, string $id)
    {
        $supplier = Supplier::findOrFail($id);
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'address' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'required|string|min:10',
            'status' => 'required|in:actif,archivé',
        ]);
        $supplier->update($validated);
        return redirect()->route('suppliers.index')->with('success', 'Fournisseur modifié avec succès');
    }

    /**
     * Suppression du fournisseur.
     */
    public function destroy(string $id)
    {
        //
    }
}