<?php

namespace App\Http\Controllers;

use App\Http\Requests\RoomRequest;
use App\Models\Addon;
use App\Models\Facility;
use App\Models\Image;
use App\Models\MealPackage;
use App\Models\Room;
use App\Models\RoomCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class RoomController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Fetch all rooms with only the thumbnail image
        $rooms = Room::with([
            'images' => function ($query) {
                $query->where('role', 'thumbnail')->orderBy('sort_order');
            },
            'roomCategory'
        ])->get();

        $rooms = $rooms->map(function ($room) {
            return [
                'id' => $room->id,
                'room_number' => $room->room_number,
                'price_override' => $room->price_override,
                'is_published' => $room->is_published,
                'room_category_name' => $room->roomCategory?->name ?? '—',
            ];
        });

        return Inertia::render('dashboard/rooms/index', [
            'rooms' => $rooms
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {

        $facilities = Facility::select('id', 'name', 'is_icon', 'icon_value')->where('scope', 'room')->orderBy('name')->get();
        $meal_packages = MealPackage::select('id', 'title', 'is_icon', 'icon_value', 'price')->where('scope', 'room')->orderBy('title')->get();
        $add_ons = Addon::select('id', 'title', 'is_icon', 'icon_value', 'price')->where('scope', 'room')->orderBy('title')->get();
        $catagories = RoomCategory::select('id', 'name')->orderBy('sort_order', 'asc')->get();

        return Inertia::render('dashboard/rooms/room', [
            'facilities' => $facilities,
            'meal_packages' => $meal_packages,
            'add_ons' => $add_ons,
            'room_catagories' => $catagories,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(RoomRequest $request)
    {
        $data = $request->validated();

        DB::beginTransaction();

        try {
            // 1️⃣ Create room
            $room = Room::create($data);

            // 2️⃣ Attach images if any
            if (!empty($data['images'])) {
                foreach ($data['images'] as $index => $img) {
                    $image = Image::find('id', $img['id'] ?? 0);
                    if (!$image) continue;

                    // Attach via morphToMany pivot table
                    $room->images()->attach($image->id, [
                        'role' => $index === 0 ? 'thumbnail' : 'gallery',
                        'sort_order' => $index,
                    ]);
                }
            }

            // 3️⃣ Attach facilities (IDs only)
            if (!empty($data['facilities']) && is_array($data['facilities'])) {
                $room->facilities()->sync($data['facilities']);
            }

            // 4️⃣ Attach meal packages (IDs only)
            if (!empty($data['meal_packages']) && is_array($data['meal_packages'])) {
                $room->mealPackages()->sync($data['meal_packages']);
            }
            // 4️⃣ Attach Add-Ons (IDs only)
            if (!empty($data['add_ons']) && is_array($data['add_ons'])) {
                $room->addOns()->sync($data['add_ons']);
            }

            // ✅ Commit transaction if all succeeds
            DB::commit();

            return redirect()->route('rooms.index')
                ->with('success', 'Room created successfully!');
        } catch (\Exception $e) {
            // ❌ Rollback if anything fails
            DB::rollBack();

            return redirect()->back()
                ->withErrors(['error' => 'Failed to create room: ' . $e->getMessage()])
                ->withInput();
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Room $room)
    {
        $room->load([
            'images' => fn($q) => $q->orderBy('sort_order'),
            'facilities:id,name,is_icon,icon_value',
            'mealPackages:id,title,is_icon,icon_value,price',
            'addOns:id,title,is_icon,icon_value,price',
        ]);

        $facilities = Facility::select('id', 'name', 'is_icon', 'icon_value')->where('scope', 'room')->orderBy('name')->get();
        $meal_packages = MealPackage::select('id', 'title', 'is_icon', 'icon_value', 'price')->where('scope', 'room')->orderBy('title')->get();
        $add_ons = Addon::select('id', 'title', 'is_icon', 'icon_value', 'price')->where('scope', 'room')->orderBy('title')->get();
        $catagories = RoomCategory::select('id', 'name')->orderBy('sort_order', 'asc')->get();


        return Inertia::render('dashboard/rooms/room', [
            'room' => $room,
            'facilities' => $facilities,
            'facilities_data' => $room->facilities->pluck('id'),
            'meal_packages' => $meal_packages,
            'meal_packages_data' => $room->mealPackages->pluck('id'),
            'add_ons' => $add_ons,
            'add_ons_data' => $room->addOns->pluck('id'),
            'room_catagories' => $catagories,
            'mode' => 'view'
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Room $room)
    {
        $room->load([
            'images' => fn($q) => $q->orderBy('sort_order'),
            'facilities:id,name,is_icon,icon_value',
            'mealPackages:id,title,is_icon,icon_value,price',
            'addOns:id,title,is_icon,icon_value,price',
        ]);

        $facilities = Facility::select('id', 'name', 'is_icon', 'icon_value')->where('scope', 'room')->orderBy('name')->get();
        $meal_packages = MealPackage::select('id', 'title', 'is_icon', 'icon_value', 'price')->where('scope', 'room')->orderBy('title')->get();
        $add_ons = Addon::select('id', 'title', 'is_icon', 'icon_value', 'price')->where('scope', 'room')->orderBy('title')->get();
        $catagories = RoomCategory::select('id', 'name')->orderBy('sort_order', 'asc')->get();


        return Inertia::render('dashboard/rooms/room', [
            'room' => $room,
            'facilities' => $facilities,
            'facilities_data' => $room->facilities->pluck('id'),
            'meal_packages' => $meal_packages,
            'meal_packages_data' => $room->mealPackages->pluck('id'),
            'add_ons' => $add_ons,
            'add_ons_data' => $room->addOns->pluck('id'),
            'room_catagories' => $catagories,
            'mode' => 'edit'
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(RoomRequest $request, Room $room)

    {
        $validated = $request->validated();


        // 1️⃣ Update room basic data
        $room->update($validated);

        // 2️⃣ Sync images
        if (isset($validated['images'])) {

            $syncData = [];

            foreach ($validated['images'] as $img) {
                $syncData[$img['id']] = [
                    'role' => $img['role'],
                    'sort_order' => $img['sort_order'],
                ];
            }

            // This will:
            // - Attach new ones
            // - Update existing pivot data
            // - Remove images not in array
            $room->images()->sync($syncData);
        } else {
            // If no images sent, detach all
            $room->images()->detach();
        }

        // 3️⃣ Sync facilities (IDs only)
        if (isset($validated['facilities']) && is_array($validated['facilities'])) {
            // Sync facilities: attach new, remove unselected
            $room->facilities()->sync($validated['facilities']);
        } else {
            // If no facilities sent, remove all
            $room->facilities()->sync([]);
        }

        // 4️⃣ Sync meal packages (IDs only)
        if (isset($validated['meal_packages']) && is_array($validated['meal_packages'])) {
            $room->mealPackages()->sync($validated['meal_packages']);
        } else {
            $room->mealPackages()->sync([]);
        }

        // 4️⃣ Sync add-ons (IDs only)
        if (isset($validated['add_ons']) && is_array($validated['add_ons'])) {
            $room->addOns()->sync($validated['add_ons']);
        } else {
            $room->addOns()->sync([]);
        }


        return redirect()->route('rooms.index')->with('success', 'Room updated successfully.');
    }



    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Room $room)
    {
        // 1️⃣ Detach all facilities (pivot table)
        $room->facilities()->sync([]); // removes all facility links

        // 2️⃣ Detach all meal-packages (pivot table)
        // $room->mealPackages()->sync([]); // removes all meal-packages links

        // 2️⃣ Detach all add-ons (pivot table)
        $room->addOns()->sync([]); // removes all add-ons links

        // 3️⃣ Detach all images (pivot table)
        $room->images()->detach(); // removes all image links

        // 4️⃣ Delete the room
        $room->delete();

        return redirect()->route('rooms.index')->with('success', 'Room deleted successfully.');
    }
}
