<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\Realisation;
use Illuminate\Http\Request;

class RealisationController extends Controller
{
    public function index()
    {
        $realisations = Realisation::orderBy('ordre')->orderBy('created_at', 'desc')->get();
        return view('dashboard.realisations.index', compact('realisations'));
    }

    public function create()
    {
        return view('dashboard.realisations.form');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'lieu' => 'required|string|max:255',
            'type_travaux' => 'required|string|max:255',
            'description' => 'required|string',
            'duree_travaux' => 'required|string|max:255',
            'client' => 'nullable|string|max:255',
        ]);

        $validated['titre'] = $validated['lieu'];
        $validated['categorie'] = $validated['type_travaux'];
        $validated['publie'] = true;
        $validated['ordre'] = 0;

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

        Realisation::create($validated);
        return redirect()->route('dashboard.realisations.index')->with('success', 'Réalisation créée avec succès.');
    }

    public function edit(Realisation $realisation)
    {
        return view('dashboard.realisations.form', ['realisation' => $realisation]);
    }

    public function update(Request $request, Realisation $realisation)
    {
        $validated = $request->validate([
            'lieu' => 'required|string|max:255',
            'type_travaux' => 'required|string|max:255',
            'description' => 'required|string',
            'duree_travaux' => 'required|string|max:255',
            'client' => 'nullable|string|max:255',
        ]);

        $validated['titre'] = $validated['lieu'];
        $validated['categorie'] = $validated['type_travaux'];

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

        $realisation->update($validated);
        return redirect()->route('dashboard.realisations.index')->with('success', 'Réalisation mise à jour.');
    }

    public function destroy(Realisation $realisation)
    {
        $realisation->delete();
        return redirect()->route('dashboard.realisations.index')->with('success', 'Réalisation supprimée.');
    }
}
