<?php

namespace App\Http\Controllers;

use App\Models\EventRoom;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use DB;
use App\Traits\DeleteModelTrait;

class EventRoomController extends Controller
{
    use DeleteModelTrait;

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $eventRooms = EventRoom::where('status', true)
            ->orderBy('name')
            ->get()
            ->map(function ($room) {
                return [
                    'id' => $room->id,
                    'name' => $room->name,
                    'primary_photo' => $room->primary_photo,
                    'price_fbu' => $room->price_fbu,
                    'price_usd' => $room->price_usd,
                    'price_eur' => $room->price_eur,
                    'short_description' => $room->short_description,
                    'capacity' => $room->capacity,
                ];
            });

        return Inertia::render('EventRooms', [
            'eventRooms' => $eventRooms,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $validatedData = $request->validate([
                'name' => 'required|string|max:255',
                'price_fbu' => 'nullable|numeric|min:0',
                'price_usd' => 'nullable|numeric|min:0',
                'price_eur' => 'nullable|numeric|min:0',
                'short_description' => 'nullable|string|min:20',
                'full_description' => 'nullable|string|min:20',
                'capacity' => 'nullable|integer|min:1',
                'layouts' => 'nullable|array',
                'layouts.*' => 'string|max:100',
                'equipment' => 'nullable|array',
                'equipment.*' => 'string|max:100',
                'gallery' => 'nullable|array',
                'gallery.*' => 'string',
                'status' => 'required|boolean',
                'primary_photo' => 'required|string',
            ]);

            // Ensure layouts, equipment, and gallery are arrays
            $validatedData['layouts'] = $validatedData['layouts'] ?? [];
            $validatedData['equipment'] = $validatedData['equipment'] ?? [];
            
            // Handle gallery - check raw input first
            $galleryInput = $request->input('gallery');
            if (is_array($galleryInput) && !empty($galleryInput)) {
                // Filter out empty values
                $validatedData['gallery'] = array_values(array_filter($galleryInput, function($item) {
                    return !empty($item) && is_string($item);
                }));
            } else {
                $validatedData['gallery'] = [];
            }

            $eventRoom = new EventRoom;
            $eventRoom->name = $validatedData['name'];
            $eventRoom->price_fbu = $validatedData['price_fbu'] ?? null;
            $eventRoom->price_usd = $validatedData['price_usd'] ?? null;
            $eventRoom->price_eur = $validatedData['price_eur'] ?? null;
            $eventRoom->short_description = $validatedData['short_description'] ?? null;
            $eventRoom->full_description = $validatedData['full_description'] ?? null;
            $eventRoom->capacity = $validatedData['capacity'] ?? null;
            $eventRoom->layouts = $validatedData['layouts'] ?? [];
            $eventRoom->equipment = $validatedData['equipment'] ?? [];
            $eventRoom->gallery = $validatedData['gallery'] ?? [];
            $eventRoom->status = $validatedData['status'];
            $eventRoom->primary_photo = $validatedData['primary_photo'];

            $eventRoom->save();

            DB::commit();
            return redirect()->route('admin.event_rooms')->with('success', [
                'message' => 'Event room added successfully',
                'check' => false
            ]);
        } catch (ValidationException $e) {
            DB::rollBack();
            return redirect()->back()
                ->withErrors($e->errors())
                ->withInput();
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', [
                'message' => 'An error occurred: ' . $e->getMessage(),
                'check' => false
            ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $eventRoom = EventRoom::where('id', $id)->firstOrFail();

        return Inertia::render('EventRoomDetail', [
            'eventRoom' => [
                'id' => $eventRoom->id,
                'name' => $eventRoom->name,
                'primary_photo' => $eventRoom->primary_photo,
                'price_fbu' => $eventRoom->price_fbu,
                'price_usd' => $eventRoom->price_usd,
                'price_eur' => $eventRoom->price_eur,
                'short_description' => $eventRoom->short_description,
                'full_description' => $eventRoom->full_description,
                'capacity' => $eventRoom->capacity,
                'layouts' => $eventRoom->layouts,
                'equipment' => $eventRoom->equipment,
                'gallery' => $eventRoom->gallery,
            ]
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $eventRoom = EventRoom::findOrFail($id);
        return response()->json([
            'id' => $eventRoom->id,
            'name' => $eventRoom->name,
            'primary_photo' => $eventRoom->primary_photo,
            'price_fbu' => $eventRoom->price_fbu,
            'price_usd' => $eventRoom->price_usd,
            'price_eur' => $eventRoom->price_eur,
            'short_description' => $eventRoom->short_description,
            'full_description' => $eventRoom->full_description,
            'capacity' => $eventRoom->capacity,
            'layouts' => $eventRoom->layouts ?? [],
            'equipment' => $eventRoom->equipment ?? [],
            'gallery' => $eventRoom->gallery ?? [],
            'status' => $eventRoom->status,
            'created_at' => $eventRoom->created_at,
            'updated_at' => $eventRoom->updated_at,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            DB::beginTransaction();
            $validatedData = $request->validate([
                'name' => 'required|string|max:255',
                'price_fbu' => 'nullable|numeric|min:0',
                'price_usd' => 'nullable|numeric|min:0',
                'price_eur' => 'nullable|numeric|min:0',
                'short_description' => 'nullable|string|min:20',
                'full_description' => 'nullable|string|min:20',
                'capacity' => 'nullable|integer|min:1',
                'layouts' => 'nullable|array',
                'layouts.*' => 'string|max:100',
                'equipment' => 'nullable|array',
                'equipment.*' => 'string|max:100',
                'gallery' => 'nullable|array',
                'gallery.*' => 'string',
                'status' => 'required|boolean',
                'primary_photo' => 'required|string',
            ]);

            // Ensure layouts, equipment, and gallery are arrays
            $validatedData['layouts'] = $validatedData['layouts'] ?? [];
            $validatedData['equipment'] = $validatedData['equipment'] ?? [];
            $validatedData['gallery'] = $validatedData['gallery'] ?? [];

            $eventRoom = EventRoom::findOrFail($id);
            $eventRoom->fill($validatedData);

            if ($eventRoom->isDirty()) {
                $eventRoom->save();
            }

            DB::commit();

            return Redirect::back()->with('success', [
                'message' => 'Event room updated successfully',
                'check' => false
            ]);
        } catch (ValidationException $e) {
            DB::rollBack();
            return redirect()->back()
                ->withErrors($e->errors())
                ->withInput();
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', [
                'message' => 'An error occurred: ' . $e->getMessage(),
                'check' => false
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        return $this->deleteModel($id, new EventRoom());
    }

    public function fetchEventRooms()
    {
        $eventRooms = EventRoom::orderBy('created_at', 'desc')->get();
        return Inertia::render('event_rooms/EventRoom', [
            'eventRooms' => $eventRooms->map(function ($room) {
                return [
                    'id' => $room->id,
                    'name' => $room->name,
                    'status' => $room->status,
                    'price_fbu' => $room->price_fbu,
                    'price_usd' => $room->price_usd,
                    'price_eur' => $room->price_eur,
                    'primary_photo' => $room->primary_photo,
                    'capacity' => $room->capacity,
                    'created_at' => $room->created_at,
                ];
            }),
        ]);
    }

    public function uploadImage(Request $request)
    {
        $request->validate([
            'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5048',
        ]);

        $path = $request->file('file')->store('event-room-images', 'public');
        $filename = basename($path);

        return response()->json(['filename' => 'event-room-images/' . $filename]);
    }

    public function uploadMultipleImages(Request $request)
    {
        $request->validate([
            'files.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5048',
        ]);

        $filenames = [];
        if ($request->hasFile('files')) {
            foreach ($request->file('files') as $file) {
                $path = $file->store('event-room-images', 'public');
                $filenames[] = 'event-room-images/' . basename($path);
            }
        }

        return response()->json(['filenames' => $filenames]);
    }
}
