<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
    
    @hotelSettings
     <title>Housekeeping Management - {{ hotelName() }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        :root {
            --primary-green: #1a936f;
            --secondary-green: #88d498;
            --light-green: #c6dabf;
            --dark-green: #114b5f;
            --accent: #f3e9d2;
            --available-room: #d4edda;
            --in-progress-orange: #ff9800; /* Orange for In Progress */
            --maintenance-blue: #17a2b8; /* Blue for Maintenance */
        }
        
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .navbar {
            background: linear-gradient(90deg, var(--dark-green) 0%, var(--primary-green) 100%);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
          /* Back to Dashboard button */
        .back-to-dashboard {
            background: linear-gradient(135deg, var(--dark-green) 0%, var(--primary-green) 100%);
            color: white;
            border: none;
            border-radius: 10px;
            padding: 10px 20px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .back-to-dashboard:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(26, 147, 111, 0.3);
            color: white;
        }
        
        /* Dashboard Card */
        .dashboard-card {
            border-radius: 16px;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            border: none;
            overflow: hidden;
            background: white;
            box-shadow: 0 6px 25px rgba(0, 0, 0, 0.08);
        }
        
        .dashboard-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
        }
      
        .sidebar {
            background-color: white;
            box-shadow: 3px 0 10px rgba(0, 0, 0, 0.1);
            height: calc(100vh - 56px);
            position: fixed;
            top: 56px;
            padding: 15px;
            z-index: 1000;
            overflow-y: auto;
            width: 250px;
        }
        
        .sidebar .nav-link {
            color: #495057;
            padding: 15px 20px;
            border-left: 4px solid transparent;
            transition: all 0.3s;
        }
        
        .sidebar .nav-link:hover {
            background-color: #f8f9fa;
            border-left: 4px solid var(--secondary-green);
        }
        
        .sidebar .nav-link.active {
            background-color: var(--light-green);
            color: var(--dark-green);
            border-left: 4px solid var(--primary-green);
            font-weight: 600;
        }
        
        .sidebar .nav-link i {
            margin-right: 10px;
            color: var(--primary-green);
        }
        
        .main-content {
            margin-left: 150px;
            margin-right: 150px;
            padding: 20px;
            margin-top: 56px;
        }
        
        .housekeeping-card {
            border-radius: 10px;
            transition: transform 0.3s, box-shadow 0.3s;
            border: none;
        }
        
        .housekeeping-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            background: linear-gradient(90deg, var(--primary-green) 0%, var(--secondary-green) 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
        }
        
        .bg-primary {
            background-color: var(--primary-green) !important;
        }
        
        .text-primary {
            color: var(--primary-green) !important;
        }
        
        .btn-primary {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
        }
        
        .btn-outline-primary {
            color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-green);
            color: white;
        }
        
        /* Status colors - Updated to match image requirements */
        .status-clean {
            background-color: #d4edda; /* Light green */
            border-left: 4px solid #28a745;
        }
        
        .status-in-progress {
            background-color: #fff3cd; /* Light orange */
            border-left: 4px solid var(--in-progress-orange);
        }
        
        .status-dirty {
            background-color: #f8d7da; /* Light red */
            border-left: 4px solid #dc3545;
        }
        
        .status-maintenance {
            background-color: #d1ecf1; /* Light blue */
            border-left: 4px solid var(--maintenance-blue);
        }
        
        .status-checked-out {
            background-color: #f8d7da; /* Light red */
            border-left: 4px solid #dc3545;
            animation: pulse 2s infinite;
        }
        
        .status-occupied {
            background-color: #e9d7f5; /* Light purple */
            border-left: 4px solid #9c27b0;
        }
        
        @keyframes pulse {
            0% { background-color: #f8d7da; }
            50% { background-color: #f1b0b7; }
            100% { background-color: #f8d7da; }
        }
        
        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background-color: #dc3545;
            color: white;
            border-radius: 50%;
            padding: 3px 8px;
            font-size: 0.7rem;
        }
        
        .notification-icon {
            position: relative;
        }
        
        .table th {
            background-color: var(--light-green);
            color: white;
        }
        
        .room-card {
            border-radius: 8px;
            transition: all 0.3s;
            cursor: pointer;
            height: 100%;
        }
        
        .room-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .room-status-badge {
            position: absolute;
            top: 10px;
            right: 10px;
        }
        
        .floor-plan {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 15px;
            padding: 20px;
        }
        
        .floor-indicator {
            background: linear-gradient(90deg, var(--dark-green) 0%, var(--primary-green) 100%);
            color: white;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        
        .cleaning-schedule {
            border-left: 4px solid var(--primary-green);
        }
        
        .ajax-loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
        
        .ajax-loading.show {
            display: flex;
        }
        
        .staff-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--primary-green);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
        }
        
        .recent-checkout-badge {
            background-color: #dc3545;
            color: white;
            font-size: 0.7rem;
            padding: 2px 6px;
            border-radius: 4px;
            margin-left: 5px;
        }
        
        /* Custom badge colors - Updated to match image requirements */
        .bg-success { background-color: #28a745 !important; }
        .bg-danger { background-color: #dc3545 !important; }
        .bg-info { background-color: var(--maintenance-blue) !important; } /* Updated to match maintenance color */
        
        .bg-in-progress {
            background-color: var(--in-progress-orange) !important; /* Orange for In Progress */
        }
        
        .bg-warning {
            background-color: var(--in-progress-orange) !important; /* Orange for In Progress */
        }
        
        .bg-occupied {
            background-color: #9c27b0 !important; /* Purple for Occupied */
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                height: auto;
                top: 0;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .floor-plan {
                grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            }
        }
    </style>
</head>
<body>
    <!-- Loading Spinner -->
    <div class="ajax-loading" id="loadingSpinner">
        <div class="spinner-border text-light" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0 text-gray-800">House Keeping </h1>
            <div>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#assignTaskModal">
                    <i class="fas fa-tasks me-2"></i>Assign Task
                </button>
                   <a href="{{ route('dashboard') }}" class="back-to-dashboard">
                    <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
                </a>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card housekeeping-card cleaning-schedule">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Rooms to Clean Today</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $todaysTasksCount ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-broom fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card housekeeping-card cleaning-schedule">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Rooms</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $totalRooms ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-door-closed fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card housekeeping-card cleaning-schedule">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Completed Today</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $completedToday ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card housekeeping-card cleaning-schedule">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Recent Checkouts</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $recentCheckoutsCount ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-sign-out-alt fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters and Actions -->
        <div class="card housekeeping-card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3 mb-2">
                        <input type="text" class="form-control" placeholder="Search rooms..." id="searchInput">
                    </div>
                    <div class="col-md-2 mb-2">
                        <select class="form-select" id="statusFilter">
                            <option value="">All Status</option>
                            <option value="clean">Clean</option>
                            <option value="in_progress">In Progress</option>
                            <option value="dirty">Dirty</option>
                            <option value="checked_out">Recently Checked Out</option>
                            <option value="maintenance">Maintenance</option>
                            <option value="occupied">Occupied</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <select class="form-select" id="floorFilter">
                            <option value="">All Floors</option>
                            @foreach($floors ?? [] as $floor)
                                <option value="{{ $floor }}">Floor {{ $floor }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <select class="form-select" id="staffFilter">
                            <option value="">All Staff</option>
                            @foreach($housekeepingStaff ?? [] as $staff)
                                @php
                                    $staffId = is_object($staff) ? $staff->id : ($staff['id'] ?? '');
                                    $staffName = is_object($staff) ? $staff->name : ($staff['name'] ?? '');
                                @endphp
                                @if($staffName)
                                    <option value="{{ $staffId }}">{{ $staffName }}</option>
                                @endif
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3 mb-2 text-end">
                        <button class="btn btn-outline-primary" id="refreshBtn">
                            <i class="fas fa-sync-alt me-2"></i>Refresh
                        </button>
                        <button class="btn btn-primary ms-2" id="applyFiltersBtn">
                            <i class="fas fa-filter me-2"></i>Apply Filters
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs Navigation -->
        <ul class="nav nav-tabs mb-4" id="housekeepingTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="floor-plan-tab" data-bs-toggle="tab" data-bs-target="#floor-plan" type="button" role="tab">
                    <i class="fas fa-layer-group me-2"></i>Floor Plan
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="list-view-tab" data-bs-toggle="tab" data-bs-target="#list-view" type="button" role="tab">
                    <i class="fas fa-list me-2"></i>List View
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="schedule-tab" data-bs-toggle="tab" data-bs-target="#schedule" type="button" role="tab">
                    <i class="fas fa-calendar me-2"></i>Schedule
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="staff-tab" data-bs-toggle="tab" data-bs-target="#staff" type="button" role="tab">
                    <i class="fas fa-users me-2"></i>Staff
                </button>
            </li>
        </ul>

        <!-- Tabs Content -->
        <div class="tab-content" id="housekeepingTabsContent">
            <!-- Floor Plan Tab -->
            <div class="tab-pane fade show active" id="floor-plan" role="tabpanel">
                <div class="card housekeeping-card">
                    <div class="card-header">
                        <h5 class="m-0 font-weight-bold" id="floorTitle">Floor 1 - Room Status</h5>
                    </div>
                    <div class="card-body">
                        <div class="floor-plan" id="floorPlanContainer">
                            <div class="text-center py-4">
                                <i class="fas fa-door-open fa-3x text-muted mb-3"></i>
                                <p class="text-muted">Select a floor to view rooms</p>
                            </div>
                        </div>
                        
                        <!-- Floor Selector -->
                        <div class="mt-4">
                            <h6 class="mb-3">Select Floor</h6>
                            <div class="btn-group" role="group" id="floorSelector">
                                @foreach($floors ?? [1, 2, 3, 4, 5] as $floor)
                                    <button type="button" class="btn btn-outline-primary {{ $loop->first ? 'active' : '' }}" data-floor="{{ $floor }}">Floor {{ $floor }}</button>
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- List View Tab -->
            <div class="tab-pane fade" id="list-view" role="tabpanel">
                <div class="card housekeeping-card">
                    <div class="card-header">
                        <h5 class="m-0 font-weight-bold">Room Cleaning Status</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover" id="roomsTable">
                                <thead>
                                    <tr>
                                        <th>Room</th>
                                        <th>Type</th>
                                        <th>Housekeeping Status</th>
                                        <th>Room Management Status</th>
                                        <th>Floor</th>
                                        <th>Last Cleaned</th>
                                        <th>Notes</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse($rooms ?? [] as $room)
                                        @php
                                            $roomStatus = $room->housekeeping_status ?? 'dirty';
                                            $roomManagementStatus = $room->status ?? 'cleaning';
                                            $isRecentlyCheckedOut = $room->recently_checked_out ?? false;
                                            if ($isRecentlyCheckedOut) {
                                                $roomStatus = 'checked_out';
                                                $roomManagementStatus = 'cleaning';
                                            }
                                            
                                            // Updated badge classes to match image requirements
                                            $housekeepingBadgeClass = match($roomStatus) {
                                                'clean' => 'success',
                                                'in_progress' => 'warning', // Changed to warning for orange
                                                'dirty' => 'danger',
                                                'checked_out' => 'danger',
                                                'maintenance' => 'info', // Blue for maintenance
                                                'occupied' => 'occupied',
                                                default => 'secondary'
                                            };
                                            
                                            $managementBadgeClass = match($roomManagementStatus) {
                                                'available' => 'success',
                                                'occupied' => 'occupied',
                                                'cleaning' => 'warning', // Orange for cleaning
                                                'maintenance' => 'info', // Blue for maintenance
                                                default => 'secondary'
                                            };
                                        @endphp
                                        <tr class="status-{{ $roomStatus }}" data-room-id="{{ $room->id ?? '' }}" data-room-status="{{ $roomStatus }}">
                                            <td>
                                                {{ $room->room_number ?? 'N/A' }}
                                                @if($isRecentlyCheckedOut)
                                                    <span class="recent-checkout-badge">Checked Out</span>
                                                @endif
                                            </td>
                                            <td>
                                                @if(isset($room->roomType) && $room->roomType)
                                                    {{ $room->roomType->name ?? 'Standard' }}
                                                @else
                                                    Standard
                                                @endif
                                            </td>
                                            <td>
                                                <span class="badge bg-{{ $housekeepingBadgeClass }}">
                                                    {{ $roomStatus == 'checked_out' ? 'Recently Checked Out' : ucfirst(str_replace('_', ' ', $roomStatus)) }}
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-{{ $managementBadgeClass }}">
                                                    {{ ucfirst($roomManagementStatus) }}
                                                </span>
                                            </td>
                                            <td>{{ $room->floor ?? 'N/A' }}</td>
                                            <td>{{ isset($room->last_cleaned_at) ? \Carbon\Carbon::parse($room->last_cleaned_at)->format('M j, g:i A') : 'N/A' }}</td>
                                            <td>{{ isset($room->housekeeping_notes) ? \Illuminate\Support\Str::limit($room->housekeeping_notes, 30) : 'No notes' }}</td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-primary update-room-btn" 
                                                        data-room-id="{{ $room->id ?? '' }}"
                                                        data-room-number="{{ $room->room_number ?? '' }}"
                                                        data-room-type="{{ $room->roomType->name ?? 'Standard' }}"
                                                        data-room-status="{{ $roomStatus }}"
                                                        data-room-management-status="{{ $roomManagementStatus }}"
                                                        data-room-notes="{{ $room->housekeeping_notes ?? '' }}"
                                                        data-room-last-cleaned="{{ isset($room->last_cleaned_at) ? \Carbon\Carbon::parse($room->last_cleaned_at)->format('M j, g:i A') : 'N/A' }}"
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#roomDetailModal">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-success update-status-btn ms-1" 
                                                        data-room-id="{{ $room->id ?? '' }}"
                                                        data-room-number="{{ $room->room_number ?? '' }}"
                                                        data-current-status="{{ $roomStatus }}">
                                                    <i class="fas fa-sync-alt"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="8" class="text-center py-4">
                                                <i class="fas fa-door-closed fa-2x text-muted mb-2"></i>
                                                <p class="text-muted mb-0">No rooms found</p>
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Schedule Tab -->
            <div class="tab-pane fade" id="schedule" role="tabpanel">
                <div class="card housekeeping-card">
                    <div class="card-header">
                        <h5 class="m-0 font-weight-bold">Today's Cleaning Schedule</h5>
                    </div>
                    <div class="card-body">
                        @if(isset($todaysTasks) && $todaysTasks->count() > 0)
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Room</th>
                                            <th>Task Type</th>
                                            <th>Assigned To</th>
                                            <th>Priority</th>
                                            <th>Status</th>
                                            <th>Created</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($todaysTasks as $task)
                                            <tr>
                                                <td>{{ $task->room->room_number ?? 'N/A' }}</td>
                                                <td>{{ ucfirst($task->task_type ?? 'daily') }} Cleaning</td>
                                                <td>
                                                    @if($task->staff)
                                                        <div class="d-flex align-items-center">
                                                            <div class="staff-avatar">
                                                                {{ substr($task->staff->first_name ?? 'U', 0, 1) }}{{ substr($task->staff->last_name ?? '', 0, 1) }}
                                                            </div>
                                                            {{ $task->staff->first_name ?? '' }} {{ $task->staff->last_name ?? '' }}
                                                        </div>
                                                    @else
                                                        <span class="text-muted">-</span>
                                                    @endif
                                                </td>
                                                <td>
                                                    <span class="badge bg-{{ ($task->priority ?? 'medium') == 'high' ? 'danger' : (($task->priority ?? 'medium') == 'medium' ? 'warning' : 'secondary') }}">
                                                        {{ ucfirst($task->priority ?? 'medium') }}
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="badge bg-{{ ($task->status ?? 'pending') == 'completed' ? 'success' : (($task->status ?? 'pending') == 'in_progress' ? 'warning' : (($task->status ?? 'pending') == 'pending' ? 'secondary' : 'danger')) }}">
                                                        {{ ucfirst($task->status ?? 'pending') }}
                                                    </span>
                                                </td>
                                                <td>{{ isset($task->created_at) ? $task->created_at->format('g:i A') : 'N/A' }}</td>
                                                <td>
                                                    @if($task->id ?? false)
                                                        <button class="btn btn-sm btn-outline-primary update-task-btn" 
                                                                data-task-id="{{ $task->id }}"
                                                                data-task-room="{{ $task->room->room_number ?? 'N/A' }}"
                                                                data-task-type="{{ $task->task_type ?? 'daily' }}"
                                                                data-task-priority="{{ $task->priority ?? 'medium' }}"
                                                                data-task-status="{{ $task->status ?? 'pending' }}"
                                                                data-task-staff="{{ $task->staff ? $task->staff->first_name . ' ' . $task->staff->last_name : '' }}"
                                                                data-task-notes="{{ $task->notes ?? '' }}"
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#taskDetailModal">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                    @else
                                                        <span class="text-muted">N/A</span>
                                                    @endif
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <div class="text-center py-4">
                                <i class="fas fa-tasks fa-3x text-muted mb-3"></i>
                                <h5>No Tasks Today</h5>
                                <p class="text-muted">There are no housekeeping tasks scheduled for today.</p>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#assignTaskModal">
                                    <i class="fas fa-plus me-2"></i>Assign First Task
                                </button>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Staff Tab -->
            <div class="tab-pane fade" id="staff" role="tabpanel">
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <div class="card housekeeping-card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="m-0 font-weight-bold">Housekeeping Department Staff</h5>
                                <span class="badge bg-primary">{{ $housekeepingStaff->count() ?? 0 }} Members</span>
                            </div>
                            <div class="card-body">
                                @if(isset($housekeepingStaff) && $housekeepingStaff->count() > 0)
                                    <div class="list-group list-group-flush">
                                        @foreach($housekeepingStaff as $staffMember)
                                            @php
                                                $staffName = is_object($staffMember) ? $staffMember->name : ($staffMember['name'] ?? '');
                                                $staffPosition = is_object($staffMember) ? ($staffMember->position ?? 'Housekeeping Staff') : ($staffMember['position'] ?? 'Housekeeping Staff');
                                                $staffEmail = is_object($staffMember) ? ($staffMember->email ?? '') : ($staffMember['email'] ?? '');
                                                $staffPhone = is_object($staffMember) ? ($staffMember->phone ?? '') : ($staffMember['phone'] ?? '');
                                                $staffActive = is_object($staffMember) ? ($staffMember->active ?? true) : ($staffMember['active'] ?? true);
                                            @endphp
                                            @if($staffName)
                                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                                    <div class="d-flex align-items-center">
                                                        <div class="staff-avatar me-3">
                                                            {{ substr($staffName, 0, 1) }}
                                                        </div>
                                                        <div>
                                                            <h6 class="mb-0">{{ $staffName }}</h6>
                                                            <small class="text-muted">
                                                                {{ $staffPosition }}
                                                            </small>
                                                            <div class="mt-1">
                                                                @if($staffEmail)
                                                                    <small class="text-muted">
                                                                        <i class="fas fa-envelope me-1"></i>{{ $staffEmail }}
                                                                    </small>
                                                                    <br>
                                                                @endif
                                                                @if($staffPhone)
                                                                    <small class="text-muted">
                                                                        <i class="fas fa-phone me-1"></i>{{ $staffPhone }}
                                                                    </small>
                                                                @endif
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="text-end">
                                                        <span class="badge bg-{{ $staffActive ? 'success' : 'secondary' }} mb-2">
                                                            {{ $staffActive ? 'Active' : 'Inactive' }}
                                                        </span>
                                                    </div>
                                                </div>
                                            @endif
                                        @endforeach
                                    </div>
                                @else
                                    <div class="text-center py-4">
                                        <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                        <h5>No Housekeeping Staff Found</h5>
                                        <p class="text-muted">There are currently no staff members assigned to the housekeeping department.</p>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6 mb-4">
                        <div class="card housekeeping-card">
                            <div class="card-header">
                                <h5 class="m-0 font-weight-bold">Department Overview</h5>
                            </div>
                            <div class="card-body">
                                <div class="text-center">
                                    <div class="mb-4">
                                        <h6>Today's Progress</h6>
                                        @php
                                            $totalRooms = $rooms->count() ?? 0;
                                            $completedRooms = $completedToday ?? 0;
                                            $productivity = $totalRooms > 0 ? round(($completedRooms / $totalRooms) * 100) : 0;
                                        @endphp
                                        <div class="progress" style="height: 25px;">
                                            <div class="progress-bar 
                                                @if($productivity >= 80) bg-success
                                                @elseif($productivity >= 60) bg-primary
                                                @elseif($productivity >= 40) bg-warning
                                                @else bg-danger
                                                @endif" 
                                                role="progressbar" 
                                                style="width: {{ $productivity }}%;" 
                                                aria-valuenow="{{ $productivity }}" 
                                                aria-valuemin="0" 
                                                aria-valuemax="100">
                                                {{ $productivity }}%
                                            </div>
                                        </div>
                                        <small class="text-muted">{{ $completedRooms }} of {{ $totalRooms }} rooms completed</small>
                                    </div>
                                    
                                    <div class="row text-center mb-4">
                                        <div class="col-4">
                                            <div class="border rounded p-2 bg-light">
                                                <div class="h5 mb-0 text-primary">{{ $totalRooms }}</div>
                                                <small>Total Rooms</small>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="border rounded p-2 bg-light">
                                                <div class="h5 mb-0 text-success">{{ $completedToday ?? 0 }}</div>
                                                <small>Completed Today</small>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="border rounded p-2 bg-light">
                                                <div class="h5 mb-0 text-warning">{{ $roomStatuses['in_progress'] ?? 0 }}</div>
                                                <small>In Progress</small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <h6>Room Status Distribution</h6>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-borderless">
                                                <thead>
                                                    <tr>
                                                        <th>Status</th>
                                                        <th>Count</th>
                                                        <th>Percentage</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @foreach($roomStatuses ?? [] as $status => $count)
                                                        @php
                                                            $badgeClass = match($status) {
                                                                'clean' => 'success',
                                                                'in_progress' => 'warning', // Orange for in progress
                                                                'dirty' => 'danger',
                                                                'checked_out' => 'danger',
                                                                'maintenance' => 'info', // Blue for maintenance
                                                                'occupied' => 'occupied',
                                                                default => 'secondary'
                                                            };
                                                            $percentage = $totalRooms > 0 ? round(($count / $totalRooms) * 100) : 0;
                                                        @endphp
                                                        <tr>
                                                            <td class="text-start">
                                                                <span class="badge bg-{{ $badgeClass }}">
                                                                    {{ $status == 'checked_out' ? 'Recently Checked Out' : ucfirst(str_replace('_', ' ', $status)) }}
                                                                </span>
                                                            </td>
                                                            <td>{{ $count }}</td>
                                                            <td>
                                                                {{ $percentage }}%
                                                            </td>
                                                        </tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Room Detail Modal -->
        <div class="modal fade" id="roomDetailModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Room <span id="roomNumber">101</span> Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form id="roomDetailForm" method="POST">
                        @csrf
                        <input type="hidden" name="_method" value="PUT">
                        <input type="hidden" name="room_id" id="modalRoomId">
                        <div class="modal-body">
                            <div class="mb-3">
                                <strong>Room Type:</strong> <span id="roomType">Standard King</span>
                            </div>
                            <div class="mb-3">
                                <strong>Current Housekeeping Status:</strong> <span id="roomStatus" class="badge bg-danger">Dirty</span>
                            </div>
                            <div class="mb-3">
                                <strong>Current Room Management Status:</strong> <span id="roomManagementStatus" class="badge bg-warning">Cleaning</span>
                            </div>
                            <div class="mb-3">
                                <strong>Last Cleaned:</strong> <span id="lastCleaned">Yesterday, 3:45 PM</span>
                            </div>
                            <div class="mb-3">
                                <strong>Current Notes:</strong> 
                                <p id="roomNotes">Checkout cleaning needed. Guest checked out at 11:00 AM.</p>
                            </div>
                            <div class="mb-3">
                                <label for="statusUpdate" class="form-label">Update Housekeeping Status</label>
                                <select class="form-select" id="statusUpdate" name="housekeeping_status">
                                    <option value="dirty">Dirty</option>
                                    <option value="in_progress">In Progress</option>
                                    <option value="clean">Clean</option>
                                    <option value="maintenance">Maintenance</option>
                                    <option value="occupied">Occupied</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="assignStaff" class="form-label">Assign to Staff</label>
                                <select class="form-select" id="assignStaff" name="assigned_staff_id">
                                    <option value="">Select Staff</option>
                                    @foreach($housekeepingStaff ?? [] as $staff)
                                        @php
                                            $staffId = is_object($staff) ? $staff->id : ($staff['id'] ?? '');
                                            $staffName = is_object($staff) ? $staff->name : ($staff['name'] ?? '');
                                        @endphp
                                        @if($staffName)
                                            <option value="{{ $staffId }}">{{ $staffName }}</option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="roomNote" class="form-label">Add Note</label>
                                <textarea class="form-control" id="roomNote" name="notes" rows="3" placeholder="Add any additional notes..."></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Task Detail Modal -->
        <div class="modal fade" id="taskDetailModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Task Details - Room <span id="taskRoomNumber">101</span></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form id="taskDetailForm" method="POST">
                        @csrf
                        @method('PUT')
                        <input type="hidden" name="task_id" id="modalTaskId">
                        <div class="modal-body">
                            <div class="mb-3">
                                <strong>Task Type:</strong> <span id="taskType">Daily Service</span>
                            </div>
                            <div class="mb-3">
                                <strong>Current Status:</strong> <span id="taskStatus" class="badge bg-secondary">Pending</span>
                            </div>
                            <div class="mb-3">
                                <strong>Assigned To:</strong> <span id="taskStaff">John Doe</span>
                            </div>
                            <div class="mb-3">
                                <strong>Priority:</strong> <span id="taskPriority" class="badge bg-warning">Medium</span>
                            </div>
                            <div class="mb-3">
                                <strong>Notes:</strong> 
                                <p id="taskNotes">No special instructions.</p>
                            </div>
                            <div class="mb-3">
                                <label for="taskStatusUpdate" class="form-label">Update Status</label>
                                <select class="form-select" id="taskStatusUpdate" name="status">
                                    <option value="pending">Pending</option>
                                    <option value="in_progress">In Progress</option>
                                    <option value="completed">Completed</option>
                                    <option value="cancelled">Cancelled</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="taskPriorityUpdate" class="form-label">Update Priority</label>
                                <select class="form-select" id="taskPriorityUpdate" name="priority">
                                    <option value="low">Low</option>
                                    <option value="medium">Medium</option>
                                    <option value="high">High</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="taskStaffUpdate" class="form-label">Reassign Staff</label>
                                <select class="form-select" id="taskStaffUpdate" name="assigned_staff_id">
                                    <option value="">Select Staff</option>
                                    @foreach($housekeepingStaff ?? [] as $staff)
                                        @php
                                            $staffId = is_object($staff) ? $staff->id : ($staff['id'] ?? '');
                                            $staffName = is_object($staff) ? $staff->name : ($staff['name'] ?? '');
                                        @endphp
                                        @if($staffName)
                                            <option value="{{ $staffId }}">{{ $staffName }}</option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="taskNoteUpdate" class="form-label">Update Notes</label>
                                <textarea class="form-control" id="taskNoteUpdate" name="notes" rows="3" placeholder="Add any additional notes..."></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Assign Task Modal -->
        <div class="modal fade" id="assignTaskModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Assign Cleaning Task</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form id="assignTaskForm" method="POST" action="{{ route('housekeeping.tasks.store') }}">
                        @csrf
                        <div class="modal-body">
                            <div class="mb-3">
                                <label for="taskRoom" class="form-label">Room *</label>
                                <select class="form-select" id="taskRoom" name="room_id" required>
                                    <option value="">Select Room</option>
                                    @foreach($rooms ?? [] as $room)
                                        <option value="{{ $room->id }}">Room {{ $room->room_number }} 
                                            ({{ $room->roomType->name ?? 'Standard' }})
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="taskName" class="form-label">Task Name *</label>
                                <input type="text" class="form-control" id="taskName" name="task_name" required 
                                       value="Room Cleaning" placeholder="Enter task name">
                            </div>
                            <div class="mb-3">
                                <label for="taskType" class="form-label">Task Type *</label>
                                <select class="form-select" id="taskType" name="task_type" required>
                                    <option value="daily">Daily Service</option>
                                    <option value="checkout">Checkout Cleaning</option>
                                    <option value="deep">Deep Cleaning</option>
                                    <option value="maintenance">Maintenance</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="taskStaff" class="form-label">Assign to Staff *</label>
                                <select class="form-select" id="taskStaff" name="assigned_staff_id" required>
                                    <option value="">Select Staff</option>
                                    @foreach($housekeepingStaff ?? [] as $staff)
                                        @php
                                            $staffId = is_object($staff) ? $staff->id : ($staff['id'] ?? '');
                                            $staffName = is_object($staff) ? $staff->name : ($staff['name'] ?? '');
                                        @endphp
                                        @if($staffName)
                                            <option value="{{ $staffId }}">{{ $staffName }}</option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="taskPriority" class="form-label">Priority</label>
                                <select class="form-select" id="taskPriority" name="priority">
                                    <option value="low">Low</option>
                                    <option value="medium" selected>Medium</option>
                                    <option value="high">High</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="taskDescription" class="form-label">Description / Special Instructions</label>
                                <textarea class="form-control" id="taskDescription" name="description" rows="3" placeholder="Add any special instructions..."></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary">Assign Task</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // CSRF token for AJAX requests
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    document.addEventListener('DOMContentLoaded', function() {
        // Initialize floor plan with first available floor
        @if(isset($floors) && count($floors) > 0)
            loadFloorPlan({{ $floors[0] }});
        @else
            loadFloorPlan(1);
        @endif
        
        // Floor selector event listeners
        document.querySelectorAll('#floorSelector button').forEach(button => {
            button.addEventListener('click', function() {
                const floor = this.getAttribute('data-floor');
                loadFloorPlan(floor);
                
                // Update active state
                document.querySelectorAll('#floorSelector button').forEach(btn => {
                    btn.classList.remove('active');
                });
                this.classList.add('active');
            });
        });
        
        // Room update buttons
        document.querySelectorAll('.update-room-btn').forEach(button => {
            button.addEventListener('click', function() {
                const roomId = this.getAttribute('data-room-id');
                const roomNumber = this.getAttribute('data-room-number');
                const roomType = this.getAttribute('data-room-type');
                const roomStatus = this.getAttribute('data-room-status');
                const roomManagementStatus = this.getAttribute('data-room-management-status');
                const roomNotes = this.getAttribute('data-room-notes');
                const lastCleaned = this.getAttribute('data-room-last-cleaned');
                
                document.getElementById('roomNumber').textContent = roomNumber;
                document.getElementById('roomType').textContent = roomType;
                document.getElementById('roomStatus').textContent = roomStatus === 'checked_out' ? 'Recently Checked Out' : roomStatus.charAt(0).toUpperCase() + roomStatus.slice(1).replace('_', ' ');
                document.getElementById('roomStatus').className = `badge bg-${getHousekeepingStatusBadgeClass(roomStatus)}`;
                document.getElementById('roomManagementStatus').textContent = roomManagementStatus.charAt(0).toUpperCase() + roomManagementStatus.slice(1);
                document.getElementById('roomManagementStatus').className = `badge bg-${getRoomManagementStatusBadgeClass(roomManagementStatus)}`;
                document.getElementById('lastCleaned').textContent = lastCleaned;
                document.getElementById('roomNotes').textContent = roomNotes || 'No notes available';
                document.getElementById('modalRoomId').value = roomId;
                document.getElementById('statusUpdate').value = roomStatus === 'checked_out' ? 'dirty' : roomStatus;
                
                // Reset form
                document.getElementById('roomNote').value = '';
            });
        });
        
        // Task update buttons
        document.querySelectorAll('.update-task-btn').forEach(button => {
            button.addEventListener('click', function() {
                const taskId = this.getAttribute('data-task-id');
                const taskRoom = this.getAttribute('data-task-room');
                const taskType = this.getAttribute('data-task-type');
                const taskPriority = this.getAttribute('data-task-priority');
                const taskStatus = this.getAttribute('data-task-status');
                const taskStaff = this.getAttribute('data-task-staff');
                const taskNotes = this.getAttribute('data-task-notes');
                
                document.getElementById('taskRoomNumber').textContent = taskRoom;
                document.getElementById('taskType').textContent = taskType.charAt(0).toUpperCase() + taskType.slice(1) + ' Cleaning';
                document.getElementById('taskStatus').textContent = taskStatus.charAt(0).toUpperCase() + taskStatus.slice(1);
                document.getElementById('taskStatus').className = `badge bg-${getTaskStatusBadgeClass(taskStatus)}`;
                document.getElementById('taskStaff').textContent = taskStaff || '-';
                document.getElementById('taskPriority').textContent = taskPriority.charAt(0).toUpperCase() + taskPriority.slice(1);
                document.getElementById('taskPriority').className = `badge bg-${getPriorityBadgeClass(taskPriority)}`;
                document.getElementById('taskNotes').textContent = taskNotes || 'No notes available';
                document.getElementById('modalTaskId').value = taskId;
                document.getElementById('taskStatusUpdate').value = taskStatus;
                document.getElementById('taskPriorityUpdate').value = taskPriority;
                
                // Reset form
                document.getElementById('taskNoteUpdate').value = '';
            });
        });
        
        // Quick status update buttons
        document.querySelectorAll('.update-status-btn').forEach(button => {
            button.addEventListener('click', function() {
                const roomId = this.getAttribute('data-room-id');
                const roomNumber = this.getAttribute('data-room-number');
                const currentStatus = this.getAttribute('data-current-status');
                
                if (confirm(`Update status for Room ${roomNumber}?`)) {
                    quickUpdateRoomStatus(roomId, currentStatus, roomNumber);
                }
            });
        });
        
        // Room detail form submission
        document.getElementById('roomDetailForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const roomId = document.getElementById('modalRoomId').value;
            const roomNumber = document.getElementById('roomNumber').textContent;
            if (!roomId) {
                alert('Error: Room ID not found');
                return;
            }
            
            submitRoomForm(this, '/housekeeping/rooms/' + roomId, roomNumber);
        });
        
        // Task detail form submission
        document.getElementById('taskDetailForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const taskRoomNumber = document.getElementById('taskRoomNumber').textContent;
            submitTaskForm(this, '/housekeeping/tasks/' + document.getElementById('modalTaskId').value, taskRoomNumber);
        });
        
        // Assign task form submission - AJAX version with redirect to floor plan
        document.getElementById('assignTaskForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const form = this;
            const formData = new FormData(form);
            
            showLoading();
            
            fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success === true || data.success === "true") {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('assignTaskModal'));
                    if (modal) {
                        modal.hide();
                    }
                    
                    showNotification(data.message || 'Task assigned successfully!', 'success');
                    
                    // Redirect to floor plan tab
                    setTimeout(() => {
                        // Switch to floor plan tab
                        const floorPlanTab = document.querySelector('#floor-plan-tab');
                        if (floorPlanTab) {
                            const tab = new bootstrap.Tab(floorPlanTab);
                            tab.show();
                        }
                        
                        // Refresh the floor plan
                        const activeFloorBtn = document.querySelector('#floorSelector button.active');
                        if (activeFloorBtn) {
                            const floor = activeFloorBtn.getAttribute('data-floor');
                            loadFloorPlan(floor);
                        }
                    }, 1000);
                } else {
                    throw new Error(data.message || 'Unknown error occurred');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('An error occurred while assigning task: ' + error.message, 'danger');
            })
            .finally(() => {
                hideLoading();
            });
        });
        
        // Refresh button
        document.getElementById('refreshBtn').addEventListener('click', function() {
            showLoading();
            setTimeout(() => {
                location.reload();
            }, 500);
        });
        
        // Apply filters button
        document.getElementById('applyFiltersBtn').addEventListener('click', function() {
            applyFilters();
        });
        
        // Search input
        document.getElementById('searchInput').addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                applyFilters();
            }
        });
        
        // Filter change events
        document.getElementById('statusFilter').addEventListener('change', applyFilters);
        document.getElementById('floorFilter').addEventListener('change', applyFilters);
        document.getElementById('staffFilter').addEventListener('change', applyFilters);
    });
    
    function loadFloorPlan(floor) {
        showLoading();
        
        fetch(`/housekeeping/floor-plan?floor=${floor}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success === true || data.success === "true") {
                const container = document.getElementById('floorPlanContainer');
                const floorTitle = document.getElementById('floorTitle');
                
                floorTitle.textContent = `Floor ${floor} - Room Status`;
                
                let roomsHtml = '';
                
                if (data.rooms && data.rooms.length > 0) {
                    data.rooms.forEach(room => {
                        const statusText = room.housekeeping_status === 'checked_out' ? 
                            'Recently Checked Out' : 
                            room.housekeeping_status.charAt(0).toUpperCase() + 
                            room.housekeeping_status.slice(1).replace('_', ' ');
                        
                        const staffName = room.assigned_staff || '';
                        
                        roomsHtml += `
                            <div class="card room-card status-${room.housekeeping_status}" 
                                 data-room-id="${room.id}" 
                                 data-room-status="${room.housekeeping_status}">
                                <div class="card-body text-center p-2">
                                    <h6 class="card-title mb-1">${room.room_number}</h6>
                                    <span class="badge bg-${getHousekeepingStatusBadgeClass(room.housekeeping_status)} room-status-badge">
                                        ${statusText}
                                    </span>
                                    <div class="mt-2">
                                        <small class="text-muted">
                                            <i class="fas fa-user me-1"></i>
                                            ${staffName || '-'}
                                        </small>
                                        <br>
                                        <small class="text-muted">
                                            ${room.room_type || 'Standard'}
                                        </small>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    roomsHtml = `
                        <div class="text-center py-4">
                            <i class="fas fa-door-closed fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No rooms found on this floor</p>
                        </div>
                    `;
                }
                
                container.innerHTML = roomsHtml;
                
                // Add click events to room cards
                document.querySelectorAll('.room-card').forEach(card => {
                    card.addEventListener('click', function() {
                        const roomId = this.getAttribute('data-room-id');
                        // You can implement room detail view here
                        console.log('Clicked room:', roomId);
                    });
                });
            } else {
                throw new Error(data.message || 'Failed to load floor plan');
            }
            hideLoading();
        })
        .catch(error => {
            console.error('Error:', error);
            hideLoading();
            showNotification('Error loading floor plan: ' + error.message, 'danger');
        });
    }
    
    function submitRoomForm(form, url, roomNumber) {
        showLoading();
        
        const formData = new FormData(form);
        const newHousekeepingStatus = formData.get('housekeeping_status');
        
        // Automatically set room management status
        if (newHousekeepingStatus === 'clean') {
            formData.append('status', 'available');
            showNotification(`Room ${roomNumber} marked as clean and available for booking!`, 'success');
        } else if (newHousekeepingStatus === 'in_progress') {
            formData.append('status', 'cleaning');
            showNotification(`Room ${roomNumber} cleaning in progress!`, 'info');
        } else if (newHousekeepingStatus === 'dirty') {
            formData.append('status', 'cleaning');
            showNotification(`Room ${roomNumber} marked as dirty and needs cleaning!`, 'warning');
        } else if (newHousekeepingStatus === 'occupied') {
            formData.append('status', 'occupied');
            showNotification(`Room ${roomNumber} marked as occupied!`, 'info');
        }
        
        fetch(url, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': csrfToken
            },
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
                    try {
                        const errorData = JSON.parse(text);
                        errorMessage = errorData.message || errorMessage;
                    } catch (e) {
                        if (text) errorMessage += ` - ${text}`;
                    }
                    throw new Error(errorMessage);
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success === true || data.success === "true") {
                const modalElement = document.getElementById('roomDetailModal');
                const modal = bootstrap.Modal.getInstance(modalElement);
                if (modal) {
                    modal.hide();
                }
                
                showNotification(data.message || `Room ${roomNumber} status updated successfully!`, 'success');
                
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                throw new Error(data.message || 'Unknown error occurred');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('An error occurred while processing your request: ' + error.message, 'danger');
        })
        .finally(() => {
            hideLoading();
        });
    }

    function submitTaskForm(form, url, roomNumber) {
        showLoading();
        
        const formData = new FormData(form);
        const newTaskStatus = formData.get('status');
        
        // Automatically update room status when task is completed
        if (newTaskStatus === 'completed') {
            formData.append('update_room_status', 'true');
            showNotification(`Task completed for Room ${roomNumber}! Room status updated to available.`, 'success');
        } else if (newTaskStatus === 'in_progress') {
            showNotification(`Task started for Room ${roomNumber}!`, 'info');
        }
        
        fetch(url, {
            method: form.method,
            headers: {
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success === true || data.success === "true") {
                const modal = bootstrap.Modal.getInstance(form.closest('.modal'));
                modal.hide();
                
                showNotification(data.message || `Task for Room ${roomNumber} updated successfully!`, 'success');
                
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } else {
                throw new Error(data.message || 'Unknown error occurred');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('An error occurred while processing your request: ' + error.message, 'danger');
        })
        .finally(() => {
            hideLoading();
        });
    }

    function quickUpdateRoomStatus(roomId, currentStatus, roomNumber) {
        showLoading();
        
        let newStatus;
        let newRoomManagementStatus = null;
        let notificationMessage = '';
        
        switch(currentStatus) {
            case 'dirty': 
            case 'checked_out': 
                newStatus = 'in_progress'; 
                newRoomManagementStatus = 'cleaning';
                notificationMessage = `Room ${roomNumber} cleaning started!`;
                break;
            case 'in_progress': 
                newStatus = 'clean'; 
                newRoomManagementStatus = 'available';
                notificationMessage = `Room ${roomNumber} cleaned and now available for booking!`;
                break;
            case 'clean': 
                newStatus = 'dirty'; 
                newRoomManagementStatus = 'cleaning';
                notificationMessage = `Room ${roomNumber} marked as dirty and needs cleaning!`;
                break;
            case 'occupied':
                newStatus = 'clean';
                newRoomManagementStatus = 'available';
                notificationMessage = `Room ${roomNumber} vacated and cleaned!`;
                break;
            default: 
                newStatus = 'dirty';
                newRoomManagementStatus = 'cleaning';
        }
        
        const formData = new FormData();
        formData.append('_token', csrfToken);
        formData.append('_method', 'PUT');
        formData.append('housekeeping_status', newStatus);
        formData.append('status', newRoomManagementStatus);
        
        fetch(`/housekeeping/rooms/${roomId}`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json'
            },
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success === true || data.success === "true") {
                showNotification(notificationMessage, 'success');
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } else {
                throw new Error(data.message || 'Update failed');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('Error updating status: ' + error.message, 'danger');
        })
        .finally(() => {
            hideLoading();
        });
    }
    
    // JavaScript helper functions - Updated to match image requirements
    function getHousekeepingStatusBadgeClass(status) {
        switch(status) {
            case 'clean': return 'success';
            case 'in_progress': return 'warning'; // Orange for in progress
            case 'dirty': return 'danger';
            case 'checked_out': return 'danger';
            case 'maintenance': return 'info'; // Blue for maintenance
            case 'occupied': return 'occupied';
            default: return 'secondary';
        }
    }

    function getRoomManagementStatusBadgeClass(status) {
        switch(status) {
            case 'available': return 'success';
            case 'occupied': return 'occupied';
            case 'cleaning': return 'warning'; // Orange for cleaning
            case 'maintenance': return 'info'; // Blue for maintenance
            default: return 'secondary';
        }
    }
    
    function getTaskStatusBadgeClass(status) {
        switch(status) {
            case 'completed': return 'success';
            case 'in_progress': return 'warning'; // Orange for in progress
            case 'pending': return 'secondary';
            case 'cancelled': return 'danger';
            default: return 'secondary';
        }
    }
    
    function getPriorityBadgeClass(priority) {
        switch(priority) {
            case 'high': return 'danger';
            case 'medium': return 'warning'; // Orange for medium priority
            case 'low': return 'secondary';
            default: return 'secondary';
        }
    }

    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 5000);
    }
    
    function applyFilters() {
        const search = document.getElementById('searchInput').value.toLowerCase();
        const status = document.getElementById('statusFilter').value;
        const floor = document.getElementById('floorFilter').value;
        const staff = document.getElementById('staffFilter').value;
        
        const rows = document.querySelectorAll('#roomsTable tbody tr');
        
        rows.forEach(row => {
            const roomNumber = row.cells[0].textContent.toLowerCase();
            const roomStatus = row.getAttribute('data-room-status');
            const roomFloor = row.cells[4].textContent;
            
            let showRow = true;
            
            if (search && !roomNumber.includes(search)) {
                showRow = false;
            }
            
            if (status && roomStatus !== status) {
                showRow = false;
            }
            
            if (floor && roomFloor !== floor) {
                showRow = false;
            }
            
            row.style.display = showRow ? '' : 'none';
        });
    }
    
    function showLoading() {
        document.getElementById('loadingSpinner').classList.add('show');
    }
    
    function hideLoading() {
        document.getElementById('loadingSpinner').classList.remove('show');
    }
</script>
 <script src="{{ asset('js/theme-applier.js') }}"></script>
</body>
</html>

