<?php

namespace App\Http\Controllers\VoyagedifiantDashboard;

use App\Http\Controllers\Controller;
use App\Models\Vehicule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class formVehiculeController extends Controller
{
     public function showformVehicule()
    {
     return view('page.formVehicule');
    }

    public function formVehicule(Request $request)
{
    // Validation des données
    $validated = $request->validate([
    'name' => 'required|string|max:255',
    'luggage' => 'required|string|max:255',
    'number_of_seats' => 'required|integer|min:1',
    'air_conditioning' => 'sometimes|accepted',
    'price_economy' => 'required|integer|min:0',
    'price_business' => 'required|integer|min:0',
    'images' => 'required|array|min:1',
    'images.*' => 'image|mimes:jpeg,png,jpg|max:2048',
]);


    try {
        DB::beginTransaction();

        // Conversion des valeurs booléennes
        // $validated['has_cleaning'] = $request->has('has_cleaning') ? 1 : 0;
        $validated['air_conditioning'] = (bool)$request->input('air_conditioning');
        // $validated['has_breakfast'] = (bool)$request->input('has_breakfast');

        // Création de l'hôtel
        $vehicule = Vehicule::create($validated);
// Traitement des images
        if ($request->hasFile('images')) {
    foreach ($request->file('images') as $image) {
        $path = $image->store('vehicules/images', 'public');
        $vehicule->images()->create(['images_path' => $path]);

        // Debug
        Log::debug('Image enregistrée', [
            'vehicule_id' => $vehicule->id,
            'path' => $path,
            'full_path' => storage_path('app/public/'.$path)
        ]);
    }
}

        DB::commit();


    // return redirect()->back()->with('success', 'Véhicule créé avec succès');
    return redirect()->route('listeVehicule')
            ->with('show_success_modal', true)
           ->with('modal_message', 'Le Véhicule a été créé avec succès !');
}

catch (\Exception $e) {
        DB::rollBack();

        Log::error("Erreur création hôtel", [
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString(),
            'data' => $request->all()
        ]);

        return back()
               ->withInput()
               ->with('error', 'Une erreur est survenue lors de la création de l\'hôtel');
    }
}




}
