<?php

namespace App\Http\Controllers;

use App\Models\Room;
use App\Models\Staff;
use App\Models\StaffDepartment;
use App\Models\HousekeepingTask;
use App\Models\HousekeepingNote;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Concerns\ResolvesTenantHotel;
use Illuminate\Validation\Rule;

class HousekeepingController extends Controller
{
    use ResolvesTenantHotel;

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

    public function index()
    {
        try {
            // Get housekeeping staff with simplified data
            $housekeepingStaff = Staff::with(['department', 'position'])
                ->whereHas('department', function($query) {
                    $query->where('name', 'Housekeeping');
                })
                ->where('status', 'active')
                ->orderBy('first_name')
                ->get()
                ->map(function($staff) {
                    return [
                        'id' => $staff->id,
                        'name' => $staff->first_name . ' ' . $staff->last_name,
                        'position' => $staff->position->name ?? 'Housekeeping Staff',
                        'email' => $staff->email,
                        'phone' => $staff->phone,
                        'hire_date' => $staff->hire_date ? $staff->hire_date->format('M d, Y') : 'Not set',
                    ];
                });

            // Get all rooms with their room types
            $rooms = Room::with(['roomType'])
                ->orderBy('room_number')
                ->get();

            // Get today's tasks if HousekeepingTask model exists
            try {
                $todaysTasks = HousekeepingTask::with(['room', 'staff'])
                    ->whereDate('scheduled_date', today())
                    ->orderBy('created_at', 'desc')
                    ->get();
                
                $todaysTasksCount = $todaysTasks->count();
            } catch (\Exception $e) {
                // Fallback if HousekeepingTask model doesn't exist
                $todaysTasks = collect();
                $todaysTasksCount = 0;
            }

            // Get room status counts
            $roomStatuses = [
                'clean' => $rooms->where('housekeeping_status', 'clean')->count(),
                'in_progress' => $rooms->where('housekeeping_status', 'in_progress')->count(),
                'dirty' => $rooms->whereIn('housekeeping_status', ['dirty', 'checked_out'])->count(),
                'maintenance' => $rooms->where('housekeeping_status', 'maintenance')->count(),
                'checked_out' => $rooms->where('housekeeping_status', 'checked_out')->count(),
            ];

            // Get unique floors
            $floors = Room::select('floor')
                ->distinct()
                ->orderBy('floor')
                ->pluck('floor')
                ->toArray();

            // Calculate today's progress
            $totalRooms = $rooms->count();
            $cleanRooms = $roomStatuses['clean'];
            $progressPercentage = $totalRooms > 0 ? round(($cleanRooms / $totalRooms) * 100) : 0;

            // Calculate recent checkouts (dirty rooms + checked out rooms)
            $recentCheckoutsCount = $roomStatuses['dirty'];

            // Calculate completed today
            $completedToday = HousekeepingTask::whereDate('scheduled_date', today())
                ->where('status', 'completed')
                ->count();

            return view('housekeeping.index', [
                'housekeepingStaff' => $housekeepingStaff,
                'rooms' => $rooms,
                'todaysTasks' => $todaysTasks,
                'todaysTasksCount' => $todaysTasksCount,
                'roomStatuses' => $roomStatuses,
                'floors' => $floors,
                'totalRooms' => $totalRooms,
                'cleanRooms' => $cleanRooms,
                'completedToday' => $completedToday,
                'recentCheckoutsCount' => $recentCheckoutsCount,
                'progressPercentage' => $progressPercentage,
            ]);

        } catch (\Exception $e) {
            \Log::error('Error loading housekeeping index: ' . $e->getMessage());
            
            return view('housekeeping.index', [
                'housekeepingStaff' => collect(),
                'rooms' => collect(),
                'todaysTasks' => collect(),
                'todaysTasksCount' => 0,
                'roomStatuses' => [
                    'clean' => 0, 
                    'in_progress' => 0, 
                    'dirty' => 0, 
                    'maintenance' => 0
                ],
                'floors' => [],
                'totalRooms' => 0,
                'cleanRooms' => 0,
                'completedToday' => 0,
                'recentCheckoutsCount' => 0,
                'progressPercentage' => 0,
            ])->with('error', 'Unable to load all data: ' . $e->getMessage());
        }
    }

    public function floorPlan(Request $request)
    {
        try {
            $floor = $request->get('floor', 1);

            $rooms = Room::with(['roomType'])
                ->where('floor', $floor)
                ->orderBy('room_number')
                ->get()
                ->map(function($room) {
                    return [
                        'id' => $room->id,
                        'room_number' => $room->room_number,
                        'room_type' => $room->roomType->name ?? 'Standard',
                        'housekeeping_status' => $room->housekeeping_status,
                        'housekeeping_notes' => $room->housekeeping_notes,
                        'assigned_staff' => 'Unassigned'
                    ];
                });

            return response()->json([
                'success' => true,
                'rooms' => $rooms->toArray()
            ]);
        } catch (\Exception $e) {
            \Log::error('Error loading floor plan: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error loading floor plan'
            ], 500);
        }
    }

    /**
     * Update room status and sync with housekeeping tasks
     */
    public function updateRoom(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            $hotelId = $this->getHotelId();
            $request->validate([
                'housekeeping_status' => 'required|in:clean,dirty,in_progress,maintenance',
                'status' => 'sometimes|in:available,occupied,cleaning,maintenance',
                'notes' => 'nullable|string',
                'assigned_staff_id' => [
                    'nullable',
                    Rule::exists('staff', 'id')->where(function ($query) use ($hotelId) {
                        $query->where('hotel_id', $hotelId);
                    }),
                ]
            ]);

            $room = Room::where('hotel_id', $hotelId)->findOrFail($id);

            $updateData = [
                'housekeeping_status' => $request->housekeeping_status,
                'housekeeping_notes' => $request->notes ?: $room->housekeeping_notes,
            ];

            // Automatically set room management status based on housekeeping status
            switch ($request->housekeeping_status) {
                case 'clean':
                    $updateData['status'] = 'available';
                    $updateData['last_cleaned_at'] = now();
                    $updateData['is_available'] = true;
                    break;
                case 'in_progress':
                    $updateData['status'] = 'cleaning';
                    $updateData['is_available'] = false;
                    break;
                case 'dirty':
                    $updateData['status'] = 'cleaning';
                    $updateData['is_available'] = false;
                    break;
                case 'maintenance':
                    $updateData['status'] = 'maintenance';
                    $updateData['is_available'] = false;
                    break;
            }

            // Override with explicit status if provided
            if ($request->has('status')) {
                $updateData['status'] = $request->status;
                $updateData['is_available'] = ($request->status === 'available');
            }

            $room->update($updateData);

            // Sync housekeeping tasks
            $this->syncHousekeepingTasksWithRoomStatus($room->id, $request->housekeeping_status);

            // Handle task assignment if HousekeepingTask model exists and staff is assigned
            if ($request->assigned_staff_id && class_exists(HousekeepingTask::class) && in_array($request->housekeeping_status, ['dirty', 'in_progress'])) {
                try {
                    // Find or create task
                    $task = HousekeepingTask::where('room_id', $id)
                        ->whereDate('scheduled_date', today())
                        ->whereIn('status', ['pending', 'in_progress'])
                        ->first();
                    
                    if (!$task) {
                        $task = HousekeepingTask::create([
                            'room_id' => $id,
                            'task_name' => 'Room Cleaning',
                            'task_type' => $room->housekeeping_status === 'dirty' ? 'checkout' : 'daily',
                            'assigned_staff_id' => $request->assigned_staff_id,
                            'assigned_to' => $request->assigned_staff_id,
                            'assigned_at' => now(),
                            'priority' => 'medium',
                            'notes' => $request->notes,
                            'scheduled_date' => today(),
                            'status' => 'pending',
                            'estimated_duration' => 30
                        ]);
                    } else {
                        $task->update([
                            'assigned_staff_id' => $request->assigned_staff_id,
                            'assigned_to' => $request->assigned_staff_id,
                            'assigned_at' => now(),
                            'notes' => $request->notes ?: $task->notes,
                        ]);
                    }
                } catch (\Exception $taskError) {
                    \Log::warning('Task assignment failed: ' . $taskError->getMessage());
                    // Continue without task assignment
                }
            }

            DB::commit();

            // FIXED: Convert room to array for clean JSON
            $roomData = $room->fresh(['roomType'])->toArray();
            
            return response()->json([
                'success' => true,
                'message' => 'Room updated successfully!',
                'room' => $roomData
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Error updating room: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error updating room: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Quick update room status and sync with tasks
     */
    public function quickUpdateRoom(Request $request)
    {
        DB::beginTransaction();
        try {
            $hotelId = $this->getHotelId();
            $request->validate([
                'room_id' => [
                    'required',
                    Rule::exists('rooms', 'id')->where(function ($query) use ($hotelId) {
                        $query->where('hotel_id', $hotelId);
                    }),
                ],
                'housekeeping_status' => 'required|in:clean,dirty,in_progress,maintenance'
            ]);

            $room = Room::where('hotel_id', $hotelId)->findOrFail($request->room_id);

            $updateData = [
                'housekeeping_status' => $request->housekeeping_status,
            ];

            // Automatically set room management status based on housekeeping status
            switch ($request->housekeeping_status) {
                case 'clean':
                    $updateData['status'] = 'available';
                    $updateData['last_cleaned_at'] = now();
                    break;
                case 'in_progress':
                    $updateData['status'] = 'cleaning';
                    break;
                case 'dirty':
                case 'maintenance':
                    $updateData['status'] = 'cleaning';
                    break;
            }

            $room->update($updateData);

            // Sync housekeeping tasks
            $this->syncHousekeepingTasksWithRoomStatus($room->id, $request->housekeeping_status);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Room status updated successfully!'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Error quick updating room: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error updating room status'
            ], 500);
        }
    }

    /**
     * Update housekeeping tasks based on room status change
     */
    public function updateTasksByRoomStatus(Request $request)
    {
        try {
            $this->syncHousekeepingTasksWithRoomStatus($request->room_id, $request->room_status);
            
            return response()->json([
                'success' => true,
                'message' => 'Tasks updated successfully'
            ]);
            
        } catch (\Exception $e) {
            \Log::error('Error updating tasks by room status: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error updating tasks: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Helper method to sync housekeeping tasks with room status
     */
    private function syncHousekeepingTasksWithRoomStatus($roomId, $roomStatus)
    {
        // Check if HousekeepingTask model exists
        if (!class_exists(HousekeepingTask::class)) {
            return;
        }

        try {
            $tasks = HousekeepingTask::where('room_id', $roomId)
                                ->whereIn('status', ['pending', 'in_progress'])
                                ->get();
            
            foreach ($tasks as $task) {
                switch ($roomStatus) {
                    case 'clean':
                        if ($task->status !== 'completed') {
                            $task->update([
                                'status' => 'completed',
                                'completed_time' => now(),
                                'actual_duration' => $task->estimated_duration ?: 30 // default 30 minutes
                            ]);
                        }
                        break;
                        
                    case 'in_progress':
                        if ($task->status === 'pending') {
                            $task->update([
                                'status' => 'in_progress',
                                'started_at' => now()
                            ]);
                        }
                        break;
                        
                    case 'dirty':
                        if ($task->status === 'completed') {
                            $task->update([
                                'status' => 'pending',
                                'completed_time' => null,
                                'started_at' => null,
                                'actual_duration' => null
                            ]);
                        }
                        break;

                    case 'maintenance':
                        // For maintenance status, we might want to cancel pending tasks
                        if ($task->status === 'pending') {
                            $task->update([
                                'status' => 'cancelled',
                                'notes' => ($task->notes ?? '') . " [Cancelled due to room maintenance]"
                            ]);
                        }
                        break;
                        
                    case 'checked_out':
                        // Create a new task for checked out room
                        $existingTask = HousekeepingTask::where('room_id', $roomId)
                            ->whereDate('scheduled_date', today())
                            ->where('task_type', 'checkout')
                            ->first();
                        
                        if (!$existingTask) {
                            HousekeepingTask::create([
                                'room_id' => $roomId,
                                'task_name' => 'Checkout Cleaning',
                                'task_type' => 'checkout',
                                'priority' => 'high',
                                'status' => 'pending',
                                'scheduled_date' => today(),
                                'estimated_duration' => 45 // 45 minutes for checkout cleaning
                            ]);
                        }
                        break;
                }
            }
        } catch (\Exception $e) {
            \Log::warning('Error syncing housekeeping tasks: ' . $e->getMessage());
            // Don't throw error, just log it
        }
    }

    public function updateTask(Request $request, $id)
    {
        // Check if HousekeepingTask model exists
        if (!class_exists(HousekeepingTask::class)) {
            return response()->json([
                'success' => false,
                'message' => 'Task management not available'
            ], 501);
        }

        DB::beginTransaction();
        try {
            $hotelId = $this->getHotelId();
            $request->validate([
                'status' => 'required|in:pending,in_progress,completed,cancelled',
                'priority' => 'required|in:low,medium,high,critical',
                'assigned_staff_id' => [
                    'nullable',
                    Rule::exists('staff', 'id')->where(function ($query) use ($hotelId) {
                        $query->where('hotel_id', $hotelId);
                    }),
                ],
                'notes' => 'nullable|string',
                'update_room_status' => 'sometimes|boolean'
            ]);

            $task = HousekeepingTask::findOrFail($id);

            $updateData = [
                'status' => $request->status,
                'priority' => $request->priority,
                'assigned_staff_id' => $request->assigned_staff_id,
                'notes' => $request->notes ?: $task->notes,
            ];

            // Handle timestamps based on status
            if ($request->status === 'completed') {
                $updateData['completed_time'] = now();
            } elseif ($request->status === 'in_progress' && !$task->started_at) {
                $updateData['started_at'] = now();
            } elseif ($request->status === 'pending') {
                $updateData['started_at'] = null;
                $updateData['completed_time'] = null;
            }

            $task->update($updateData);

            // Automatically update room status if task is completed and flag is set
            if ($request->has('update_room_status') && $request->update_room_status && $request->status === 'completed') {
                $room = $task->room;
                if ($room) {
                    $room->update([
                        'housekeeping_status' => 'clean',
                        'status' => 'available',
                        'last_cleaned_at' => now(),
                        'is_available' => true
                    ]);
                }
            } elseif ($request->status === 'in_progress') {
                // Update room status to in_progress when task starts
                $task->room->update([
                    'housekeeping_status' => 'in_progress',
                    'status' => 'cleaning',
                    'is_available' => false
                ]);
            } elseif ($request->status === 'pending') {
                // Update room status to dirty when task is reset to pending
                $task->room->update([
                    'housekeeping_status' => 'dirty',
                    'status' => 'cleaning',
                    'is_available' => false
                ]);
            }

            DB::commit();

            // FIXED: Convert task to array for clean JSON
            $taskData = $task->load(['room', 'staff'])->toArray();

            return response()->json([
                'success' => true,
                'message' => 'Task updated successfully!',
                'task' => $taskData
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Error updating task: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error updating task: ' . $e->getMessage()
            ], 500);
        }
    }

    public function storeTask(Request $request)
    {
        // Check if HousekeepingTask model exists
        if (!class_exists(HousekeepingTask::class)) {
            return response()->json([
                'success' => false,
                'message' => 'Task management not available'
            ], 501);
        }

        DB::beginTransaction();
        try {
            $hotelId = $this->getHotelId();
            \Log::info('=== STORE TASK DEBUG ===');
            \Log::info('Request Data: ', $request->all());
            \Log::info('User: ' . auth()->id());

            $request->validate([
                'room_id' => [
                    'required',
                    Rule::exists('rooms', 'id')->where(function ($query) use ($hotelId) {
                        $query->where('hotel_id', $hotelId);
                    }),
                ],
                'task_name' => 'required|string|max:255',
                'task_type' => 'required|in:daily,checkout,deep,maintenance',
                'assigned_staff_id' => [
                    'required',
                    Rule::exists('staff', 'id')->where(function ($query) use ($hotelId) {
                        $query->where('hotel_id', $hotelId);
                    }),
                ],
                'priority' => 'required|in:low,medium,high,critical',
                'notes' => 'nullable|string'
            ]);

            // Check if room exists
            $room = Room::where('hotel_id', $hotelId)->find($request->room_id);
            if (!$room) {
                throw new \Exception('Room not found');
            }

            // Check if staff exists
            $staff = Staff::where('hotel_id', $hotelId)->find($request->assigned_staff_id);
            if (!$staff) {
                throw new \Exception('Staff member not found');
            }

            $taskData = [
                'room_id' => $request->room_id,
                'task_name' => $request->task_name,
                'task_type' => $request->task_type,
                'assigned_staff_id' => $request->assigned_staff_id,
                'assigned_to' => $request->assigned_staff_id,
                'assigned_at' => now(),
                'priority' => $request->priority,
                'scheduled_date' => now()->format('Y-m-d'),
                'notes' => $request->notes,
                'status' => 'pending',
            ];

            $task = HousekeepingTask::create($taskData);

            // Update room status to in_progress when task is assigned
            $room->update([
                'housekeeping_status' => 'in_progress',
                'status' => 'cleaning',
                'is_available' => false
            ]);

            DB::commit();

            // FIXED: Ensure proper JSON structure by converting to array
            $cleanTaskData = [
                'id' => $task->id,
                'task_name' => $task->task_name,
                'task_type' => $task->task_type,
                'assigned_staff_id' => $task->assigned_staff_id,
                'assigned_to' => $task->assigned_to,
                'assigned_at' => $task->assigned_at,
                'priority' => $task->priority,
                'status' => $task->status,
                'notes' => $task->notes,
                'created_at' => $task->created_at,
                'room' => [
                    'id' => $room->id,
                    'room_number' => $room->room_number,
                    'floor' => $room->floor,
                    'room_type' => $room->roomType->name ?? 'Standard',
                ],
                'staff' => [
                    'id' => $staff->id,
                    'name' => $staff->first_name . ' ' . $staff->last_name,
                ]
            ];

            return response()->json([
                'success' => true,
                'message' => 'Task assigned successfully!',
                'task' => $cleanTaskData
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Error storing task: ' . $e->getMessage());
            \Log::error('Error trace: ' . $e->getTraceAsString());
            return response()->json([
                'success' => false,
                'message' => 'Error assigning task: ' . $e->getMessage()
            ], 500);
        }
    }

    public function storeNote(Request $request)
    {
        // Check if HousekeepingNote model exists
        if (!class_exists(HousekeepingNote::class)) {
            return response()->json([
                'success' => false,
                'message' => 'Notes functionality not available'
            ], 501);
        }

        try {
            $hotelId = $this->getHotelId();
            $request->validate([
                'title' => 'required|string|max:255',
                'content' => 'required|string',
                'priority' => 'required|in:low,medium,high',
                'is_pinned' => 'boolean',
                'room_id' => [
                    'nullable',
                    Rule::exists('rooms', 'id')->where(function ($query) use ($hotelId) {
                        $query->where('hotel_id', $hotelId);
                    }),
                ]
            ]);

            $note = HousekeepingNote::create([
                'title' => $request->title,
                'content' => $request->content,
                'priority' => $request->priority,
                'is_pinned' => $request->is_pinned ?? false,
                'room_id' => $request->room_id,
                'created_by' => auth()->id(),
            ]);

            // FIXED: Convert note to array for clean JSON
            return response()->json([
                'success' => true,
                'message' => 'Note added successfully!',
                'note' => $note->toArray()
            ]);
        } catch (\Exception $e) {
            \Log::error('Error storing note: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error adding note: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getRoom($id)
    {
        try {
            $hotelId = $this->getHotelId();
            $room = Room::with(['roomType'])
                ->where('hotel_id', $hotelId)
                ->findOrFail($id);

            // FIXED: Convert room to array for clean JSON
            return response()->json([
                'success' => true,
                'room' => $room->toArray()
            ]);
        } catch (\Exception $e) {
            \Log::error('Error getting room: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error loading room details'
            ], 500);
        }
    }

    public function getTask($id)
    {
        // Check if HousekeepingTask model exists
        if (!class_exists(HousekeepingTask::class)) {
            return response()->json([
                'success' => false,
                'message' => 'Task management not available'
            ], 501);
        }

        try {
            $task = HousekeepingTask::with(['room', 'staff'])
                ->findOrFail($id);

            // FIXED: Convert task to array for clean JSON
            return response()->json([
                'success' => true,
                'task' => $task->toArray()
            ]);
        } catch (\Exception $e) {
            \Log::error('Error getting task: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error loading task details'
            ], 500);
        }
    }

    public function report()
    {
        try {
            $rooms = Room::with(['roomType'])
                ->orderBy('floor')
                ->orderBy('room_number')
                ->get();

            // Get today's tasks if available
            $todayTasks = collect();
            if (class_exists(HousekeepingTask::class)) {
                $todayTasks = HousekeepingTask::with(['room', 'staff'])
                    ->whereDate('scheduled_date', today())
                    ->get();
            }

            // Get housekeeping staff with clean, simple data
            $housekeepingStaff = Staff::with(['department', 'position'])
                ->whereHas('department', function($query) {
                    $query->where('name', 'Housekeeping');
                })
                ->where('status', 'active')
                ->orderBy('first_name')
                ->get()
                ->map(function($staff) {
                    return [
                        'id' => $staff->id,
                        'name' => $staff->first_name . ' ' . $staff->last_name,
                        'position' => $staff->position->name ?? 'Housekeeping Staff',
                        'email' => $staff->email,
                    ];
                });

            return view('housekeeping.report', [
                'rooms' => $rooms,
                'todayTasks' => $todayTasks,
                'housekeepingStaff' => $housekeepingStaff,
                'reportDate' => now()->format('F j, Y')
            ]);
        } catch (\Exception $e) {
            \Log::error('Error loading housekeeping report: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Error loading housekeeping report.');
        }
    }

    public function staff()
    {
        try {
            // Get housekeeping staff with clean, simple data
            $housekeepingStaff = Staff::with(['department', 'position'])
                ->whereHas('department', function($query) {
                    $query->where('name', 'Housekeeping');
                })
                ->where('status', 'active')
                ->orderBy('first_name')
                ->get()
                ->map(function($staff) {
                    return [
                        'id' => $staff->id,
                        'name' => $staff->first_name . ' ' . $staff->last_name,
                        'position' => $staff->position->name ?? 'Housekeeping Staff',
                        'email' => $staff->email,
                        'phone' => $staff->phone,
                        'hire_date' => $staff->hire_date ? $staff->hire_date->format('M d, Y') : 'Not set',
                        'status' => $staff->status,
                    ];
                });

            return view('housekeeping.staff', [
                'housekeepingStaff' => $housekeepingStaff
            ]);
        } catch (\Exception $e) {
            \Log::error('Error loading housekeeping staff: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Error loading staff management page.');
        }
    }

    public function storeStaff(Request $request)
    {
        return response()->json([
            'success' => false,
            'message' => 'Staff management is handled through the main Staff Management module.'
        ], 403);
    }

    public function updateStaff(Request $request, $id)
    {
        return response()->json([
            'success' => false,
            'message' => 'Staff management is handled through the main Staff Management module.'
        ], 403);
    }

    /**
     * Get staff performance metrics for housekeeping staff
     */
    public function getStaffPerformance()
    {
        try {
            // Get housekeeping staff with performance data
            $housekeepingStaff = Staff::with(['department', 'position'])
                ->whereHas('department', function($query) {
                    $query->where('name', 'Housekeeping');
                })
                ->where('status', 'active')
                ->withCount([
                    'housekeepingTasks as today_tasks_count' => function($query) {
                        $query->whereDate('scheduled_date', today());
                    },
                    'housekeepingTasks as completed_tasks_count' => function($query) {
                        $query->whereDate('scheduled_date', today())
                              ->where('status', 'completed');
                    }
                ])
                ->orderBy('first_name')
                ->get()
                ->map(function($staff) {
                    $totalTasks = $staff->today_tasks_count ?? 0;
                    $completedTasks = $staff->completed_tasks_count ?? 0;
                    $completionRate = $totalTasks > 0 ? round(($completedTasks / $totalTasks) * 100) : 0;
                    
                    return [
                        'id' => $staff->id,
                        'name' => $staff->first_name . ' ' . $staff->last_name,
                        'position' => $staff->position->name ?? 'Housekeeping',
                        'total_tasks' => $totalTasks,
                        'completed_tasks' => $completedTasks,
                        'completion_rate' => $completionRate,
                        'performance_badge' => $completionRate >= 80 ? 'success' : 
                                             ($completionRate >= 60 ? 'primary' : 
                                             ($completionRate >= 40 ? 'warning' : 'danger'))
                    ];
                });

            return response()->json([
                'success' => true,
                'staffPerformance' => $housekeepingStaff->toArray()
            ]);
        } catch (\Exception $e) {
            \Log::error('Error getting staff performance: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error loading staff performance data'
            ], 500);
        }
    }

    /**
     * Get housekeeping dashboard statistics
     */
    public function getDashboardStats()
    {
        try {
            $hotelId = $this->getHotelId();
            $totalRooms = Room::where('hotel_id', $hotelId)->count();
            $cleanRooms = Room::where('hotel_id', $hotelId)->where('housekeeping_status', 'clean')->count();
            $inProgressRooms = Room::where('hotel_id', $hotelId)->where('housekeeping_status', 'in_progress')->count();
            $dirtyRooms = Room::where('hotel_id', $hotelId)->where('housekeeping_status', 'dirty')->count();
            $maintenanceRooms = Room::where('hotel_id', $hotelId)->where('housekeeping_status', 'maintenance')->count();
            
            $housekeepingStaffCount = Staff::with(['department'])
                ->whereHas('department', function($query) {
                    $query->where('name', 'Housekeeping');
                })
                ->where('status', 'active')
                ->count();

            $todayTasksCount = 0;
            if (class_exists(HousekeepingTask::class)) {
                $todayTasksCount = HousekeepingTask::where('hotel_id', $hotelId)
                    ->whereDate('scheduled_date', today())
                    ->count();
            }

            $progressPercentage = $totalRooms > 0 ? round(($cleanRooms / $totalRooms) * 100) : 0;

            return response()->json([
                'success' => true,
                'stats' => [
                    'total_rooms' => $totalRooms,
                    'clean_rooms' => $cleanRooms,
                    'in_progress_rooms' => $inProgressRooms,
                    'dirty_rooms' => $dirtyRooms,
                    'maintenance_rooms' => $maintenanceRooms,
                    'staff_count' => $housekeepingStaffCount,
                    'today_tasks_count' => $todayTasksCount,
                    'productivity_rate' => $progressPercentage
                ]
            ]);
        } catch (\Exception $e) {
            \Log::error('Error getting dashboard stats: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error loading dashboard statistics'
            ], 500);
        }
    }

    /**
     * Debug method to check staff and departments
     */
    public function debugStaff()
    {
        try {
            $allStaff = Staff::with('department')->get();
            $debugInfo = [];
            
            foreach ($allStaff as $staff) {
                $debugInfo[] = [
                    'id' => $staff->id,
                    'name' => $staff->first_name . ' ' . $staff->last_name,
                    'department_id' => $staff->department_id,
                    'department_name' => $staff->department->name ?? 'None',
                    'status' => $staff->status
                ];
            }

            return response()->json([
                'success' => true,
                'staff' => $debugInfo,
                'housekeeping_departments' => StaffDepartment::where('name', 'like', '%housekeeping%')->get()->toArray()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Debug error: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Check if JSON response is valid
     */
    private function ensureValidJson($data)
    {
        // Try to encode to check for JSON errors
        $json = json_encode($data);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            \Log::error('JSON encoding error: ' . json_last_error_msg());
            return ['error' => 'Data encoding error'];
        }
        
        return json_decode($json, true);
    }
}