<?php

namespace App\Http\Controllers\VoyagedifiantDashboard;

use App\Http\Controllers\Controller;
use App\Models\Hotel;
use App\Models\HotelImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Barryvdh\DomPDF\Facade\Pdf;

class HotelController extends Controller
{
    public function edit($id)
    {
        $hotel = Hotel::findOrFail($id);
        $hotel->load('images');
        return view('page.formeEditHotel', compact('hotel'));
    }

    public function update(Request $request, $id)
    {
        Log::debug('Début mise à jour', ['hotel_id' => $id, 'step' => 'start']);
        Log::debug('Données reçues', $request->all());

        try {
            DB::beginTransaction();

            // Normalisation des champs booléens avant validation
            $request->merge([
                'has_cleaning' => $request->has('has_cleaning') ? 1 : 0,
                'has_wifi' => $request->input('has_wifi', 0),
                'has_breakfast' => $request->input('has_breakfast', 0),
            ]);

            // Validation
            $validatedData = $request->validate([
                'name' => 'required|string|max:255',
                'new_images' => 'nullable|array',
                'new_images.*' => 'sometimes|image|mimes:jpeg,png,jpg|max:2048',
                'delete_images' => 'nullable|array',
                'delete_images.*' => 'integer|exists:hotel_images,id,hotel_id,'.$id,
                'description_fr' => 'required|string',
                'description_en' => 'required|string',
                'has_cleaning' => 'sometimes|boolean',
                'has_wifi' => 'required|boolean',
                'has_breakfast' => 'required|boolean',
                'city' => 'required|string|max:255',
                'emplacement' => 'required|string|max:255',
                'lat' => ['required', 'regex:/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/'],
                'longi' => ['required', 'regex:/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/'],
                'number_of_beds' => 'required|integer|min:1',
                'number_of_bathrooms' => 'required|integer|min:1',
                'number_of_ac' => 'required|integer|min:0',
                'details_fr' => 'required|string',
                'details_en' => 'required|string',
                'price_standard' => 'required|integer|min:10000',
                'price_premium' => 'required|integer|min:10000',
                'price_suite' => 'required|integer|min:10000',
            ]);

            $hotel = Hotel::with('images')->findOrFail($id);

            // Mise à jour des champs de base
            $hotel->update($validatedData);
            Log::debug('Données de base mises à jour', ['hotel_id' => $hotel->id]);

            // Gestion des images
            $this->handleImages($request, $hotel);

            DB::commit();
            Log::debug('Mise à jour réussie', ['hotel_id' => $id]);

            return redirect()->route('listeHotel')
                   ->with('show_success_modal', true)
                   ->with('success', 'L\'Hôtel a été modifié avec succès !');

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

            $errorMessage = $e->getMessage();
            if ($e instanceof \Illuminate\Validation\ValidationException) {
                $errorMessage = implode('<br>', $e->validator->errors()->all());
            }

            Log::error("Échec mise à jour", [
                'error' => $errorMessage,
                'trace' => $e->getTraceAsString(),
                'hotel_id' => $id,
                'request_data' => $request->all()
            ]);

            return back()
                   ->withInput()
                   ->with('error', 'Erreur: '.$errorMessage);
        }
    }

    protected function handleImages(Request $request, Hotel $hotel)
    {
        // Suppression des images sélectionnées
        if ($request->has('delete_images')) {
            Log::debug('Suppression images demandée', ['ids' => $request->delete_images]);

            $hotel->images()
                ->whereIn('id', $request->delete_images)
                ->each(function ($image) {
                    $this->deleteImageFile($image);
                    $image->delete();
                    Log::debug('Image supprimée', ['id' => $image->id]);
                });
        }

        // Ajout de nouvelles images
        if ($request->hasFile('new_images')) {
            foreach ($request->file('new_images') as $file) {
                $path = $this->storeImage($file);
                $hotel->images()->create(['images_path' => $path]);
                Log::debug('Nouvelle image ajoutée', ['path' => $path]);
            }
        }
    }

    protected function deleteImageFile(HotelImage $image)
    {
        $path = $image->images_path;
        if (Storage::disk('public')->exists($path)) {
            Storage::disk('public')->delete($path);
            Log::debug('Fichier image supprimé', ['path' => $path]);
        } else {
            Log::warning('Fichier image non trouvé', ['path' => $path]);
        }
    }

    protected function storeImage($file)
    {
        $path = $file->store('hotels/images', 'public');
        Log::debug('Image stockée', ['path' => $path]);
        return $path;
    }

    public function destroy($id)
    {
        $hotel = Hotel::findOrFail($id);
        $hotel->delete();

        return redirect()->route('listeHotel')
                       ->with('success', 'L\'hotel a été supprimé avec succès');
    }

    public function generatePdf($id)
    {
        $hotel = Hotel::with('images')->findOrFail($id);

        // Chemin de la première image si elle existe
        $imagePath = $hotel->images->isNotEmpty()
            ? storage_path('app/public/'.$hotel->images->first()->images_path)
            : null;

        $pdf = PDF::loadView('page.pdf.hotel', [
            'hotel' => $hotel,
            'imagePath' => $imagePath,
            'hasCleaningText' => $hotel->has_cleaning ? 'Oui' : 'Non',
            'hasBreakfastText' => $hotel->has_breakfast ? 'Oui' : 'Non',
            'hasWifiText' => $hotel->has_wifi ? 'Oui' : 'Non'
        ]);

        return $pdf->stream('hotel-'.$id.'.pdf');
    }
}
