<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Room;
use App\Models\RoomType;
use App\Models\Maintenance;
use App\Exports\RoomsExport;
use App\Imports\RoomsImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

use App\Http\Controllers\Concerns\ResolvesTenantHotel;

class RoomController extends Controller
{
    use ResolvesTenantHotel;

    protected function getHotelId()
    {
        return $this->tenantHotelIdOrAbort();
    }

    public function index(Request $request)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        // Get filter parameters
        $status = $request->get('status');
        $roomType = $request->get('room_type');
        $floor = $request->get('floor');
        $category = $request->get('category');
        $housekeepingStatus = $request->get('housekeeping_status');
        
        // Start building the query with hotel filter
        $query = Room::with(['roomType', 'activeMaintenanceRequests'])
            ->where('hotel_id', $hotelId)
            ->select('rooms.*');
        
        // Apply filters
        if ($status && $status !== 'all') {
            if ($status === 'under_maintenance') {
                $query->underMaintenance();
            } else {
                $query->where('rooms.status', $status);
            }
        }
        
        if ($roomType && $roomType !== 'all') {
            $query->where('rooms.room_type_id', $roomType);
        }
        
        if ($floor && $floor !== 'all') {
            $query->where('rooms.floor', $floor);
        }
        
        if ($category && $category !== 'all') {
            $query->where('rooms.category', $category);
        }
        
        if ($housekeepingStatus && $housekeepingStatus !== 'all') {
            $query->where('rooms.housekeeping_status', $housekeepingStatus);
        }
        
        // Search functionality
        if ($request->has('search') && !empty($request->search)) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('rooms.room_number', 'like', "%{$search}%")
                  ->orWhere('rooms.category', 'like', "%{$search}%")
                  ->orWhereHas('roomType', function($q) use ($search) {
                      $q->where('name', 'like', "%{$search}%");
                  })
                  ->orWhereHas('activeMaintenanceRequests', function($q) use ($search) {
                      $q->where('title', 'like', "%{$search}%");
                  });
            });
        }
        
        // Get rooms with pagination
        $rooms = $query->orderBy('rooms.floor')->orderBy('rooms.room_number')->paginate(10);
        
        // Get statistics for the dashboard cards - WITH HOTEL FILTER
        $totalRoomsCount = Room::where('hotel_id', $hotelId)->count();
        $availableRoomsCount = Room::where('hotel_id', $hotelId)->where('status', 'available')->count();
        $maintenanceRoomsCount = Room::where('hotel_id', $hotelId)->where('status', 'maintenance')->count();
        
        // Get active maintenance requests count with error handling - WITH HOTEL FILTER
        try {
            $activeMaintenanceCount = Maintenance::where('hotel_id', $hotelId)
                ->whereNotIn('status', ['completed', 'cancelled'])
                ->count();
        } catch (\Exception $e) {
            $activeMaintenanceCount = 0;
        }
        
        // Get filter options - WITH HOTEL FILTER
        $floors = Room::where('hotel_id', $hotelId)->whereNotNull('floor')->distinct()->orderBy('floor')->pluck('floor');
        $categories = Room::where('hotel_id', $hotelId)->whereNotNull('category')->distinct()->orderBy('category')->pluck('category');
        $roomTypes = RoomType::where('hotel_id', $hotelId)->orderBy('name')->get(['id', 'name']);
        
        $statuses = [
            'available' => 'Available',
            'occupied' => 'Occupied', 
            'maintenance' => 'Maintenance',
            'cleaning' => 'Cleaning',
            'under_maintenance' => 'Under Maintenance'
        ];
        
        $housekeepingStatuses = [
            'clean' => 'Clean',
            'dirty' => 'Dirty',
            'in_progress' => 'In Progress',
            'inspected' => 'Inspected'
        ];
        
        return view('rooms.index', compact(
            'rooms', 
            'floors',
            'categories',
            'roomTypes',
            'statuses',
            'housekeepingStatuses',
            'status',
            'roomType',
            'floor',
            'category',
            'housekeepingStatus',
            'totalRoomsCount',
            'availableRoomsCount',
            'maintenanceRoomsCount',
            'activeMaintenanceCount'
        ));
    }
    
    public function create()
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        try {
            // Get room types from database - WITH HOTEL FILTER
            $roomTypes = RoomType::where('hotel_id', $hotelId)->orderBy('name')->get();
            
            // Get floors and categories with error handling - WITH HOTEL FILTER
            try {
                $floors = Room::where('hotel_id', $hotelId)->whereNotNull('floor')->distinct()->orderBy('floor')->pluck('floor');
            } catch (\Exception $e) {
                $floors = collect([]);
            }
            
            try {
                $categories = Room::where('hotel_id', $hotelId)->whereNotNull('category')->distinct()->orderBy('category')->pluck('category');
            } catch (\Exception $e) {
                $categories = collect([]);
            }
            
            // Define amenities array
            $amenities = [
                'Wi-Fi',
                'Air Conditioning',
                'TV',
                'Mini Bar',
                'Safe',
                'Hair Dryer',
                'Coffee Maker',
                'Iron',
                'Desk',
                'Balcony',
                'Ocean View',
                'Mountain View',
                'City View',
                'Bathtub',
                'Shower',
                'Room Service',
                'Daily Housekeeping',
                'Wake-up Service'
            ];
            
            return view('rooms.create', compact('roomTypes', 'floors', 'categories', 'amenities'));
        } catch (\Exception $e) {
            // If there's an error, provide empty collections
            $roomTypes = collect([]);
            $floors = collect([]);
            $categories = collect([]);
            $amenities = [];
            
            return view('rooms.create', compact('roomTypes', 'floors', 'categories', 'amenities'));
        }
    }
    
    public function store(Request $request)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }

        $hotel = \App\Models\Hotel::find($hotelId);
        if ($hotel && $hotel->hasReachedRoomLimit()) {
            return back()->with('error', 'Room limit reached for your current plan (' . $hotel->max_rooms . ' rooms). Please upgrade your package to add more rooms.')->withInput();
        }
        
        // Debug: Check what's coming in the request
        Log::info('Room Store Request:', $request->all());
        
        // Base validation rules
        $validationRules = [
            'room_number' => 'required|unique:rooms,room_number,NULL,id,hotel_id,' . $hotelId,
            'floor' => 'required|string|max:10',
            'room_type_id' => [
                'required',
                Rule::exists('room_types', 'id')->where(function ($query) use ($hotelId) {
                    $query->where('hotel_id', $hotelId);
                }),
            ],
            'category' => 'required|string|max:100',
            'price_per_night' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'capacity' => 'required|integer|min:1',
            'status' => 'sometimes|in:available,occupied,maintenance,cleaning',
            'housekeeping_status' => 'sometimes|in:clean,dirty,in_progress,inspected',
            'amenities' => 'nullable|array',
        ];

        // Image validation
        if ($request->hasFile('images')) {
            $validationRules['images'] = 'sometimes|array';
            $validationRules['images.*'] = 'image|mimes:jpeg,png,jpg,gif,webp|max:5120';
        }

        $validated = $request->validate($validationRules);

        try {
            // Handle amenities - ensure it's stored as JSON string
            $amenitiesJson = null;
            if (!empty($validated['amenities'])) {
                $amenitiesJson = json_encode($validated['amenities']);
            }
            
            // Handle image uploads
            $imagesArray = [];
            if ($request->hasFile('images')) {
                foreach ($request->file('images') as $image) {
                    if ($image->isValid() && $image->getSize() > 0) {
                        $path = $image->store('room-images', 'public');
                        $imagesArray[] = $path;
                        Log::info('Image stored: ' . $path);
                    }
                }
            }
            $imagesJson = !empty($imagesArray) ? json_encode($imagesArray) : null;
            
            // Set default values if not provided in request
            $status = $validated['status'] ?? 'available';
            $housekeepingStatus = $validated['housekeeping_status'] ?? 'clean';
            
            // Ensure price is properly cast to float
            $price = floatval($validated['price_per_night']);
            
            // Create room using Eloquent - WITH HOTEL_ID
            $room = Room::create([
                'hotel_id' => $hotelId,
                'room_number' => $validated['room_number'],
                'floor' => $validated['floor'],
                'room_type_id' => $validated['room_type_id'],
                'category' => $validated['category'],
                'price_per_night' => $price,
                'description' => $validated['description'],
                'capacity' => $validated['capacity'],
                'status' => $status,
                'housekeeping_status' => $housekeepingStatus,
                'is_available' => $status === 'available',
                'amenities' => $amenitiesJson,
                'images' => $imagesJson,
            ]);
            
            Log::info('Room Created Successfully with ID: ' . $room->id . ' for Hotel: ' . $hotelId);
            
            return redirect()->route('rooms.index')->with('success', 'Room created successfully.');
        } catch (\Exception $e) {
            Log::error('Error creating room: ' . $e->getMessage());
            Log::error('Error trace: ' . $e->getTraceAsString());
            return back()->with('error', 'Error creating room: ' . $e->getMessage())->withInput();
        }
    } 
    
    public function show($id)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        $room = Room::with(['roomType', 'maintenanceRequests' => function($query) {
                $query->orderBy('created_at', 'desc');
            }])
            ->where('hotel_id', $hotelId)
            ->findOrFail($id);
        
        // Safely decode amenities and images
        if ($room->amenities) {
            $room->amenities = is_string($room->amenities) ? json_decode($room->amenities, true) : $room->amenities;
        }
        
        if ($room->images) {
            $room->images = is_string($room->images) ? json_decode($room->images, true) : $room->images;
        }
        
        return view('rooms.show', compact('room'));
    }
    
    public function edit($id)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        $room = Room::where('hotel_id', $hotelId)->findOrFail($id);
        
        // Safely decode amenities and images
        if ($room->amenities) {
            $room->amenities = is_string($room->amenities) ? json_decode($room->amenities, true) : $room->amenities;
        }
        
        if ($room->images) {
            $room->images = is_string($room->images) ? json_decode($room->images, true) : $room->images;
        }
        
        $roomTypes = RoomType::where('hotel_id', $hotelId)->orderBy('name')->get();
        $floors = Room::where('hotel_id', $hotelId)->whereNotNull('floor')->distinct()->orderBy('floor')->pluck('floor');
        $categories = Room::where('hotel_id', $hotelId)->whereNotNull('category')->distinct()->orderBy('category')->pluck('category');
        
        $amenities = [
            'Wi-Fi',
            'Air Conditioning',
            'TV',
            'Mini Bar',
            'Safe',
            'Hair Dryer',
            'Coffee Maker',
            'Iron',
            'Desk',
            'Balcony',
            'Ocean View',
            'Mountain View',
            'City View',
            'Bathtub',
            'Shower',
            'Room Service',
            'Daily Housekeeping',
            'Wake-up Service'
        ];
        
        return view('rooms.edit', compact('room', 'roomTypes', 'floors', 'categories', 'amenities'));
    }
    
    public function update(Request $request, $id)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        Log::info('Room Update Request:', $request->all());

        // Validation rules
        $validationRules = [
            'room_number' => 'required|unique:rooms,room_number,' . $id . ',id,hotel_id,' . $hotelId,
            'floor' => 'required|string|max:10',
            'room_type_id' => [
                'required',
                Rule::exists('room_types', 'id')->where(function ($query) use ($hotelId) {
                    $query->where('hotel_id', $hotelId);
                }),
            ],
            'category' => 'required|string|max:100',
            'price_per_night' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'capacity' => 'required|integer|min:1',
            'status' => 'sometimes|in:available,occupied,maintenance,cleaning',
            'housekeeping_status' => 'sometimes|in:clean,dirty,in_progress,inspected',
            'amenities' => 'nullable|array',
            'existing_images' => 'nullable|array',
            'existing_images.*' => 'string',
            'main_image_index' => 'nullable|integer',
            'removed_images' => 'nullable|string',
        ];

        // Image validation
        if ($request->hasFile('images')) {
            $validationRules['images'] = 'sometimes|array';
            $validationRules['images.*'] = 'image|mimes:jpeg,png,jpg,gif,webp|max:5120';
        }

        $validated = $request->validate($validationRules);

        try {
            $room = Room::where('hotel_id', $hotelId)->findOrFail($id);
            
            // Convert amenities array to JSON string
            $amenitiesJson = null;
            if (!empty($validated['amenities'])) {
                $amenitiesJson = json_encode($validated['amenities']);
            }
            
            // Handle removed images
            $removedImages = [];
            if ($request->has('removed_images') && !empty($request->removed_images)) {
                $removedImages = json_decode($request->removed_images, true) ?? [];
                
                // Delete removed images from storage
                foreach ($removedImages as $removedImage) {
                    if (Storage::disk('public')->exists($removedImage)) {
                        Storage::disk('public')->delete($removedImage);
                        Log::info('Removed image from storage: ' . $removedImage);
                    }
                }
            }
            
            // Start with existing images (excluding removed ones)
            $imagesArray = [];
            if (!empty($validated['existing_images'])) {
                foreach ($validated['existing_images'] as $existingImage) {
                    if (!in_array($existingImage, $removedImages)) {
                        $imagesArray[] = $existingImage;
                    }
                }
            }
            
            // Add new uploaded images
            if ($request->hasFile('images')) {
                foreach ($request->file('images') as $image) {
                    if ($image->isValid() && $image->getSize() > 0) {
                        $path = $image->store('room-images', 'public');
                        $imagesArray[] = $path;
                        Log::info('New image stored: ' . $path);
                    }
                }
            }
            
            // Handle main image reordering
            if (!empty($imagesArray) && $request->has('main_image_index')) {
                $mainIndex = $request->main_image_index;
                
                // If it's a numeric index for existing images
                if (is_numeric($mainIndex) && isset($imagesArray[$mainIndex])) {
                    $currentMainImage = $imagesArray[$mainIndex];
                    // Remove from current position
                    $imagesArray = array_filter($imagesArray, function($image) use ($currentMainImage) {
                        return $image !== $currentMainImage;
                    });
                    // Add to beginning
                    array_unshift($imagesArray, $currentMainImage);
                    $imagesArray = array_values($imagesArray);
                }
            }
            
            $imagesJson = !empty($imagesArray) ? json_encode(array_values($imagesArray)) : null;
            
            Log::info('Final images array:', ['images' => $imagesArray]);
            
            // Ensure price is properly cast to float
            $price = floatval($validated['price_per_night']);
            
            // Prepare update data
            $updateData = [
                'room_number' => $validated['room_number'],
                'floor' => $validated['floor'],
                'room_type_id' => $validated['room_type_id'],
                'category' => $validated['category'],
                'price_per_night' => $price,
                'description' => $validated['description'],
                'capacity' => $validated['capacity'],
                'amenities' => $amenitiesJson,
                'images' => $imagesJson,
            ];
            
            // Only update status if provided
            if (isset($validated['status'])) {
                $updateData['status'] = $validated['status'];
                $updateData['is_available'] = $validated['status'] === 'available';
            }
            
            // Only update housekeeping_status if provided
            if (isset($validated['housekeeping_status'])) {
                $updateData['housekeeping_status'] = $validated['housekeeping_status'];
            }
            
            $room->update($updateData);
            
            Log::info('Room updated successfully with ID: ' . $id);
            
            return redirect()->route('rooms.index')->with('success', 'Room updated successfully.');
        } catch (\Exception $e) {
            Log::error('Error updating room: ' . $e->getMessage());
            Log::error('Error trace: ' . $e->getTraceAsString());
            return back()->with('error', 'Error updating room: ' . $e->getMessage())->withInput();
        }
    }
 
    public function destroy($id)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        try {
            $room = Room::where('hotel_id', $hotelId)->findOrFail($id);
            
            // Delete images from storage
            if ($room->images) {
                $images = is_string($room->images) ? json_decode($room->images, true) : $room->images;
                foreach ($images as $image) {
                    Storage::disk('public')->delete($image);
                }
            }
            
            $room->delete();
            return redirect()->route('rooms.index')->with('success', 'Room deleted successfully.');
        } catch (\Exception $e) {
            return back()->with('error', 'Error deleting room: ' . $e->getMessage());
        }
    }

    public function importExport()
    {
        return view('rooms.import-export');
    }

    public function export()
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        return Excel::download(new RoomsExport($hotelId), 'rooms-' . date('Y-m-d') . '.xlsx');
    }

    public function import(Request $request)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv'
        ]);

        $hotel = \App\Models\Hotel::find($hotelId);
        if ($hotel && $hotel->max_rooms > 0) {
            // This is a bit tricky with import since we don't know how many rooms are in the file yet
            // But we can check if they are already at the limit
            if ($hotel->hasReachedRoomLimit()) {
                return back()->with('error', 'Room limit reached for your current plan (' . $hotel->max_rooms . ' rooms). Please upgrade your package to import more rooms.');
            }
        }

        try {
            Excel::import(new RoomsImport($hotelId), $request->file('file'));
            return redirect()->route('rooms.index')->with('success', 'Rooms imported successfully.');
        } catch (\Exception $e) {
            Log::error('Import Error: ' . $e->getMessage());
            return back()->with('error', 'Error importing rooms: ' . $e->getMessage());
        }
    }

    public function downloadTemplate()
    {
        $templatePath = public_path('templates/rooms-import-template.xlsx');
        
        if (!file_exists($templatePath)) {
            if (!is_dir(public_path('templates'))) {
                mkdir(public_path('templates'), 0755, true);
            }
            
            return back()->with('error', 'Template file not found. Please contact administrator.');
        }
        
        return response()->download($templatePath);
    }

    public function byStatus($status)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        $rooms = Room::where('hotel_id', $hotelId)->where('status', $status)->paginate(10);
        
        // Get statistics for the dashboard cards - WITH HOTEL FILTER
        $totalRoomsCount = Room::where('hotel_id', $hotelId)->count();
        $availableRoomsCount = Room::where('hotel_id', $hotelId)->where('status', 'available')->count();
        $maintenanceRoomsCount = Room::where('hotel_id', $hotelId)->where('status', 'maintenance')->count();
        
        try {
            $activeMaintenanceCount = Maintenance::where('hotel_id', $hotelId)
                ->whereNotIn('status', ['completed', 'cancelled'])
                ->count();
        } catch (\Exception $e) {
            $activeMaintenanceCount = 0;
        }
        
        // Get filter options - WITH HOTEL FILTER
        $floors = Room::where('hotel_id', $hotelId)->whereNotNull('floor')->distinct()->orderBy('floor')->pluck('floor');
        $categories = Room::where('hotel_id', $hotelId)->whereNotNull('category')->distinct()->orderBy('category')->pluck('category');
        $roomTypes = RoomType::where('hotel_id', $hotelId)->orderBy('name')->get(['id', 'name']);
        
        $statuses = [
            'available' => 'Available',
            'occupied' => 'Occupied', 
            'maintenance' => 'Maintenance',
            'cleaning' => 'Cleaning',
            'under_maintenance' => 'Under Maintenance'
        ];
        
        $housekeepingStatuses = [
            'clean' => 'Clean',
            'dirty' => 'Dirty',
            'in_progress' => 'In Progress',
            'inspected' => 'Inspected'
        ];
        
        return view('rooms.index', compact(
            'rooms', 
            'floors',
            'categories',
            'roomTypes',
            'statuses',
            'housekeepingStatuses',
            'totalRoomsCount',
            'availableRoomsCount',
            'maintenanceRoomsCount',
            'activeMaintenanceCount'
        ));
    }

    public function updateStatus(Request $request, $id)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return response()->json(['success' => false, 'message' => 'Hotel ID not found'], 400);
        }
        
        $request->validate([
            'status' => 'required|in:available,occupied,maintenance,cleaning'
        ]);

        $room = Room::where('hotel_id', $hotelId)->findOrFail($id);
        $room->update([
            'status' => $request->status,
            'is_available' => $request->status === 'available'
        ]);

        if ($request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Room status updated successfully.']);
        }

        return redirect()->back()->with('success', 'Room status updated successfully.');
    }

    public function updateHousekeepingStatus(Request $request, $id)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return response()->json(['success' => false, 'message' => 'Hotel ID not found'], 400);
        }
        
        $request->validate([
            'housekeeping_status' => 'required|in:clean,dirty,in_progress,inspected'
        ]);

        $room = Room::where('hotel_id', $hotelId)->findOrFail($id);
        $room->update([
            'housekeeping_status' => $request->housekeeping_status
        ]);

        if ($request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Housekeeping status updated successfully.']);
        }

        return redirect()->back()->with('success', 'Housekeeping status updated successfully.');
    }

    public function floorPlan()
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        $rooms = Room::with('roomType')
            ->where('hotel_id', $hotelId)
            ->orderBy('floor')
            ->orderBy('room_number')
            ->get();
        
        // Safely decode amenities and images for all rooms
        $rooms->each(function ($room) {
            if ($room->amenities) {
                $room->amenities = is_string($room->amenities) ? json_decode($room->amenities, true) : $room->amenities;
            }
            if ($room->images) {
                $room->images = is_string($room->images) ? json_decode($room->images, true) : $room->images;
            }
        });
        
        return view('rooms.floor-plan', compact('rooms'));
    }

    public function bulkActions(Request $request)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return response()->json(['success' => false, 'message' => 'Hotel ID not found'], 400);
        }
        
        $request->validate([
            'room_ids' => 'required|array',
            'room_ids.*' => [
                Rule::exists('rooms', 'id')->where(function ($query) use ($hotelId) {
                    $query->where('hotel_id', $hotelId);
                }),
            ],
            'action' => 'required|in:update_status,update_housekeeping_status,delete',
            'status' => 'required_if:action,update_status|in:available,occupied,maintenance,cleaning',
            'housekeeping_status' => 'required_if:action,update_housekeeping_status|in:clean,dirty,in_progress,inspected'
        ]);

        try {
            // Ensure all rooms belong to this hotel
            $rooms = Room::where('hotel_id', $hotelId)->whereIn('id', $request->room_ids)->get();
            $roomIds = $rooms->pluck('id')->toArray();
            
            if (empty($roomIds)) {
                throw new \Exception('No valid rooms found for this hotel.');
            }
            
            if ($request->action === 'update_status') {
                Room::whereIn('id', $roomIds)->update([
                    'status' => $request->status,
                    'is_available' => $request->status === 'available'
                ]);
                $message = 'Room statuses updated successfully.';
            } elseif ($request->action === 'update_housekeeping_status') {
                Room::whereIn('id', $roomIds)->update([
                    'housekeeping_status' => $request->housekeeping_status
                ]);
                $message = 'Housekeeping statuses updated successfully.';
            } elseif ($request->action === 'delete') {
                // Delete associated images first
                foreach ($rooms as $room) {
                    if ($room->images) {
                        $images = is_string($room->images) ? json_decode($room->images, true) : $room->images;
                        foreach ($images as $image) {
                            Storage::disk('public')->delete($image);
                        }
                    }
                }
                
                Room::whereIn('id', $roomIds)->delete();
                $message = 'Rooms deleted successfully.';
            }

            if ($request->ajax()) {
                return response()->json(['success' => true, 'message' => $message]);
            }

            return redirect()->back()->with('success', $message);

        } catch (\Exception $e) {
            Log::error('Bulk action error: ' . $e->getMessage());
            
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => 'Error: ' . $e->getMessage()], 500);
            }
            
            return redirect()->back()->with('error', 'Error performing bulk action: ' . $e->getMessage());
        }
    }

    public function roomMaintenance($id)
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
        }
        
        $room = Room::with(['roomType', 'maintenanceRequests.assignedTechnician'])
            ->where('hotel_id', $hotelId)
            ->findOrFail($id);
        
        $maintenanceRequests = $room->maintenanceRequests()
            ->with('assignedTechnician')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('rooms.maintenance', compact('room', 'maintenanceRequests'));
    }

    public function getAvailableRooms()
    {
        $hotelId = $this->getHotelId();
        
        if (!$hotelId) {
            return response()->json(['success' => false, 'message' => 'Hotel ID not found'], 400);
        }
        
        $rooms = Room::where('hotel_id', $hotelId)
            ->where('status', 'available')
            ->where('housekeeping_status', 'clean')
            ->with('roomType')
            ->orderBy('floor')
            ->orderBy('room_number')
            ->get();
        
        return response()->json($rooms);
    }
}