<?php

namespace App\Http\Controllers;

use App\Models\Equipment;
use App\Models\Department;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class EquipmentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Equipment::orderBy('created_at', 'desc')
            ->with('user', 'department', 'product')
            ->whereDeletedAt(null);

        // Recherche par nom produit, référence, numéro de série ou marque
        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('reference', 'like', "%{$search}%")
                    ->orWhere('serial_number', 'like', "%{$search}%")
                    ->orWhere('brand', 'like', "%{$search}%")
                    ->orWhereHas('product', fn($p) => $p->where('name', 'like', "%{$search}%"));
            });
        }

        // Filtre par département
        if ($departmentId = $request->get('department_id')) {
            $query->where('department_id', $departmentId);
        }

        // Filtre par statut (etats)
        if ($etats = $request->get('etats')) {
            $query->where('etats', $etats);
        }

        $equipments = $query->paginate(10)->withQueryString();
        $departments = Department::whereDeletedAt(null)->get();
        $products = Product::whereDeletedAt(null)->get(['id', 'name']);
        return view('equipment.index', compact('equipments', 'departments', 'products'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'department_id' => 'required|exists:departments,id',
            'serial_number' => 'nullable|string|max:255',
            'brand' => 'nullable|string|max:255',
            'etats' => 'nullable|in:neuf,bon,defectueux,hors_service',
        ]);

        $validated['user_id'] = Auth::id();
        $equipment = Equipment::create($validated);
        return redirect()->route('equipment.index')->with('success', 'Équipement 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)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'department_id' => 'required|exists:departments,id',
            'serial_number' => 'nullable|string|max:255',
            'brand' => 'nullable|string|max:255',
            'etats' => 'nullable|in:neuf,bon,defectueux,hors_service',
        ]);

        $equipment = Equipment::findOrFail($id);
        $equipment->update($validated);
        return redirect()->route('equipment.index')->with('success', 'Équipement modifié avec succès');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $equipment = Equipment::find($id);
        $equipment->delete();
        return redirect()->route('equipment.index')->with('success', 'Équipement supprimé avec succès');
    }
}
