<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Rooms Dashboard - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 1) - should go up one level to root
$base_path = dirname(__DIR__, 1);

// Method 2: If init.php doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/init.php')) {
    // Manual calculation: /HMSPOS/rooms/ -> /HMSPOS/
    $base_path = dirname(__DIR__);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/init.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('dashboard.rooms');
// }

// Set page title
$page_title = 'Rooms Dashboard';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Get today's date
$today = date('Y-m-d');
$tomorrow = date('Y-m-d', strtotime('+1 day'));

// Initialize stats array with default values
$stats = [
    'total_rooms' => 0,
    'occupied' => 0,
    'available' => 0,
    'maintenance' => 0,
    'housekeeping' => 0,
    'blocked' => 0,
    'clean' => 0,
    'dirty' => 0,
    'inspected' => 0,
    'out_of_service' => 0,
    'occupancy_rate' => 0
];

// Get room statistics
try {
    $stats['total_rooms'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE is_active = 1") ?: 0;
    $stats['occupied'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE status = 'occupied'") ?: 0;
    $stats['available'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE status = 'available'") ?: 0;
    $stats['maintenance'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE status = 'maintenance'") ?: 0;
    $stats['housekeeping'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE status = 'housekeeping'") ?: 0;
    $stats['blocked'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE status = 'blocked'") ?: 0;
    $stats['clean'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'clean'") ?: 0;
    $stats['dirty'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'dirty'") ?: 0;
    $stats['inspected'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'inspected'") ?: 0;
    $stats['out_of_service'] = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'out_of_service'") ?: 0;
} catch (Exception $e) {
    error_log("Error fetching room stats: " . $e->getMessage());
}

// Calculate occupancy rate
$stats['occupancy_rate'] = $stats['total_rooms'] > 0 
    ? round(($stats['occupied'] / $stats['total_rooms']) * 100, 1) 
    : 0;

// Get room type breakdown
$room_types = [];
try {
    $room_types = db_fetch_all("
        SELECT rt.*, 
               COUNT(r.room_id) as total_rooms,
               SUM(CASE WHEN r.status = 'occupied' THEN 1 ELSE 0 END) as occupied,
               SUM(CASE WHEN r.status = 'available' THEN 1 ELSE 0 END) as available
        FROM room_types rt
        LEFT JOIN rooms r ON rt.room_type_id = r.room_type_id AND r.is_active = 1
        GROUP BY rt.room_type_id
        ORDER BY rt.type_name
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
}

// Get today's expected check-ins/outs by room type
$expected = [
    'checkins' => [],
    'checkouts' => []
];

try {
    $expected['checkins'] = db_fetch_all("
        SELECT rt.type_name, rt.room_type_id, COUNT(*) as count
        FROM reservations r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        WHERE r.check_in_date = ?
        AND r.booking_status IN ('confirmed', 'pending')
        GROUP BY rt.room_type_id
    ", [$today]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching checkins: " . $e->getMessage());
}

try {
    $expected['checkouts'] = db_fetch_all("
        SELECT rt.type_name, rt.room_type_id, COUNT(*) as count
        FROM reservations r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        WHERE r.check_out_date = ?
        AND r.booking_status = 'checked_in'
        GROUP BY rt.room_type_id
    ", [$today]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching checkouts: " . $e->getMessage());
}

// Get upcoming reservations by room type (next 7 days)
$upcoming = [];
try {
    $upcoming = db_fetch_all("
        SELECT 
            rt.type_name,
            DATE(r.check_in_date) as date,
            COUNT(*) as arrivals,
            SUM(CASE WHEN r.booking_status = 'confirmed' THEN 1 ELSE 0 END) as confirmed
        FROM reservations r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        WHERE r.check_in_date BETWEEN ? AND ?
        AND r.booking_status IN ('confirmed', 'pending')
        GROUP BY rt.room_type_id, DATE(r.check_in_date)
        ORDER BY r.check_in_date
    ", [$today, date('Y-m-d', strtotime('+7 days'))]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching upcoming: " . $e->getMessage());
}

// Get rooms needing attention (dirty, maintenance)
$attention_rooms = [];
try {
    $attention_rooms = db_fetch_all("
        SELECT r.*, rt.type_name,
               CASE 
                   WHEN r.status = 'maintenance' THEN 'Maintenance Required'
                   WHEN r.housekeeping_status = 'dirty' THEN 'Needs Cleaning'
                   WHEN r.housekeeping_status = 'out_of_service' THEN 'Out of Service'
               END as reason
        FROM rooms r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        WHERE r.status = 'maintenance' 
           OR r.housekeeping_status IN ('dirty', 'out_of_service')
        ORDER BY 
            CASE 
                WHEN r.status = 'maintenance' THEN 1
                WHEN r.housekeeping_status = 'dirty' THEN 2
                ELSE 3
            END,
            r.room_number
        LIMIT 20
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching attention rooms: " . $e->getMessage());
}

// Get revenue by room type (current month)
$revenue_by_type = [];
try {
    $revenue_by_type = db_fetch_all("
        SELECT 
            rt.type_name,
            COUNT(DISTINCT r.reservation_id) as bookings,
            COALESCE(SUM(f.amount), 0) as revenue
        FROM room_types rt
        LEFT JOIN reservations r ON rt.room_type_id = r.room_type_id 
            AND MONTH(r.check_in_date) = MONTH(CURDATE())
            AND YEAR(r.check_in_date) = YEAR(CURDATE())
        LEFT JOIN folio_charges f ON r.reservation_id = f.reservation_id
            AND f.charge_type = 'room'
            AND f.is_voided = 0
        GROUP BY rt.room_type_id
        ORDER BY revenue DESC
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching revenue: " . $e->getMessage());
}

// Get floor-wise occupancy
$floor_occupancy = [];
try {
    $floor_occupancy = db_fetch_all("
        SELECT 
            floor,
            COUNT(*) as total,
            SUM(CASE WHEN status = 'occupied' THEN 1 ELSE 0 END) as occupied,
            ROUND(SUM(CASE WHEN status = 'occupied' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 1) as occupancy_rate
        FROM rooms
        WHERE is_active = 1 AND floor IS NOT NULL
        GROUP BY floor
        ORDER BY floor
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching floor occupancy: " . $e->getMessage());
}

// Get housekeeping efficiency stats
$housekeeping_stats = [
    'avg_cleaning_time' => 0,
    'tasks_today' => 0,
    'completed_today' => 0
];

try {
    $housekeeping_stats['avg_cleaning_time'] = (int)db_fetch_value("
        SELECT AVG(TIMESTAMPDIFF(MINUTE, assigned_at, completed_at)) 
        FROM hk_tasks 
        WHERE task_type = 'cleaning' 
        AND status = 'completed'
        AND completed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ") ?: 0;
    
    $housekeeping_stats['tasks_today'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM hk_tasks 
        WHERE DATE(created_at) = CURDATE()
    ") ?: 0;
    
    $housekeeping_stats['completed_today'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM hk_tasks 
        WHERE DATE(completed_at) = CURDATE()
    ") ?: 0;
} catch (Exception $e) {
    error_log("Error fetching housekeeping stats: " . $e->getMessage());
}

// Get all rooms for grid display
$rooms = [];
try {
    $rooms = db_fetch_all("
        SELECT r.*, rt.type_name,
               CONCAT(g.first_name, ' ', g.last_name) as guest_name
        FROM rooms r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        LEFT JOIN reservations res ON r.room_id = res.room_id 
            AND res.booking_status = 'checked_in'
        LEFT JOIN guests g ON res.guest_id = g.guest_id
        WHERE r.is_active = 1
        ORDER BY r.room_number
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching rooms: " . $e->getMessage());
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Rooms Dashboard</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">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; }
            .small-box .inner { padding: 20px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .small-box .icon { position: absolute; top: 10px; right: 15px; font-size: 4rem; opacity: 0.3; }
            .info-box { box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); border-radius: 0.25rem; background: #fff; display: flex; margin-bottom: 20px; min-height: 80px; }
            .info-box-icon { border-radius: 0.25rem 0 0 0.25rem; display: flex; align-items: center; justify-content: center; width: 70px; font-size: 1.875rem; text-align: center; }
            .info-box-content { padding: 10px; flex: 1; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-success { background-color: #28a745 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !important; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Rooms Dashboard</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Rooms Dashboard</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/rooms/dashboard.php">Rooms</a></li>
                    <li class="breadcrumb-item active">Dashboard</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Quick Actions Row -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <a href="/HMSPOS/rooms/rooms/create.php" class="btn btn-primary me-2 mb-2">
                            <i class="fas fa-plus-circle me-1"></i> Add Room
                        </a>
                        <a href="/HMSPOS/rooms/room-types/index.php" class="btn btn-info me-2 mb-2">
                            <i class="fas fa-tags me-1"></i> Room Types
                        </a>
                        <a href="/HMSPOS/rooms/rates/index.php" class="btn btn-success me-2 mb-2">
                            <i class="fas fa-dollar-sign me-1"></i> Rate Plans
                        </a>
                        <a href="/HMSPOS/rooms/availability/calendar.php" class="btn btn-warning me-2 mb-2">
                            <i class="fas fa-calendar-alt me-1"></i> Availability Calendar
                        </a>
                        <a href="/HMSPOS/housekeeping/cleaning/room-status.php" class="btn btn-secondary me-2 mb-2">
                            <i class="fas fa-broom me-1"></i> Housekeeping View
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total_rooms']; ?></h3>
                        <p>Total Rooms</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-hotel"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['available']; ?></h3>
                        <p>Available</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-door-open"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['occupied']; ?></h3>
                        <p>Occupied</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-bed"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['maintenance']; ?></h3>
                        <p>Maintenance</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-tools"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Second Row Stats -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-info"><i class="fas fa-percent"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Occupancy Rate</span>
                        <span class="info-box-number"><?php echo $stats['occupancy_rate']; ?>%</span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-broom"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Clean Rooms</span>
                        <span class="info-box-number"><?php echo $stats['clean']; ?></span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-warning"><i class="fas fa-broom"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Dirty Rooms</span>
                        <span class="info-box-number"><?php echo $stats['dirty']; ?></span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-danger"><i class="fas fa-calendar-check"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Expected Arrivals</span>
                        <span class="info-box-number"><?php echo array_sum(array_column($expected['checkins'], 'count')); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Room Status Grid -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-th-large me-1"></i>
                            Room Status Overview
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" onclick="refreshRoomGrid()">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="room-grid" id="roomGrid">
                            <?php foreach ($rooms as $room): ?>
                                <?php
                                $status_class = '';
                                switch($room['status']) {
                                    case 'available':
                                        $status_class = 'available';
                                        break;
                                    case 'occupied':
                                        $status_class = 'occupied';
                                        break;
                                    case 'maintenance':
                                        $status_class = 'maintenance';
                                        break;
                                    case 'housekeeping':
                                        $status_class = 'housekeeping';
                                        break;
                                    case 'blocked':
                                        $status_class = 'blocked';
                                        break;
                                }
                            ?>
                                <div class="room-item <?php echo $status_class; ?>" 
                                     onclick="viewRoom(<?php echo $room['room_id']; ?>)"
                                     data-bs-toggle="tooltip" 
                                     title="<?php echo htmlspecialchars(($room['type_name'] ?? '') . ' - ' . ucfirst($room['status'] ?? '')); ?>">
                                    <div class="room-number"><?php echo htmlspecialchars($room['room_number'] ?? ''); ?></div>
                                    <div class="room-type"><?php echo htmlspecialchars($room['type_name'] ?? ''); ?></div>
                                    <?php if (!empty($room['guest_name'])): ?>
                                        <div class="guest-name">
                                            <i class="fas fa-user"></i> <?php echo htmlspecialchars($room['guest_name']); ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (($room['housekeeping_status'] ?? '') != 'clean'): ?>
                                        <div class="hk-status">
                                            <small class="badge bg-warning">
                                                <?php echo ucfirst($room['housekeeping_status'] ?? ''); ?>
                                            </small>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Rooms Needing Attention -->
            <div class="col-md-4">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exclamation-triangle me-1"></i>
                            Rooms Needing Attention
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($attention_rooms)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                <p>All rooms are in good order</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Room</th>
                                            <th>Type</th>
                                            <th>Issue</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($attention_rooms as $room): ?>
                                        <tr>
                                            <td><strong><?php echo htmlspecialchars($room['room_number'] ?? ''); ?></strong></td>
                                            <td><?php echo htmlspecialchars($room['type_name'] ?? ''); ?></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    echo ($room['status'] ?? '') == 'maintenance' ? 'danger' : 'warning';
                                                ?>">
                                                    <?php echo htmlspecialchars($room['reason'] ?? ''); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (($room['status'] ?? '') == 'maintenance'): ?>
                                                    <a href="/HMSPOS/housekeeping/maintenance/create.php?room_id=<?php echo $room['room_id'] ?? 0; ?>" 
                                                       class="btn btn-sm btn-danger">
                                                        <i class="fas fa-tools"></i>
                                                    </a>
                                                <?php elseif (($room['housekeeping_status'] ?? '') == 'dirty'): ?>
                                                    <a href="/HMSPOS/housekeeping/tasks/create.php?room_id=<?php echo $room['room_id'] ?? 0; ?>" 
                                                       class="btn btn-sm btn-warning">
                                                        <i class="fas fa-broom"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Housekeeping Efficiency -->
                <div class="card card-info mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clock me-1"></i>
                            Housekeeping Efficiency
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <div class="text-center">
                                    <h3><?php echo round($housekeeping_stats['avg_cleaning_time'] ?? 0); ?> min</h3>
                                    <p class="text-muted">Avg. Cleaning Time</p>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="text-center">
                                    <h3><?php echo $housekeeping_stats['completed_today']; ?>/<?php echo $housekeeping_stats['tasks_today']; ?></h3>
                                    <p class="text-muted">Tasks Completed Today</p>
                                </div>
                            </div>
                        </div>
                        <div class="progress mt-2">
                            <?php 
                            $completion_rate = $housekeeping_stats['tasks_today'] > 0 
                                ? round(($housekeeping_stats['completed_today'] / $housekeeping_stats['tasks_today']) * 100) 
                                : 0;
                            ?>
                            <div class="progress-bar bg-success" style="width: <?php echo $completion_rate; ?>%">
                                <?php echo $completion_rate; ?>%
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Room Type Breakdown -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie me-1"></i>
                            Room Type Occupancy
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Room Type</th>
                                        <th class="text-center">Total</th>
                                        <th class="text-center">Occupied</th>
                                        <th class="text-center">Available</th>
                                        <th class="text-center">Occupancy %</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($room_types as $type): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($type['type_name'] ?? ''); ?></strong>
                                            <br>
                                            <small class="text-muted"><?php echo htmlspecialchars($type['type_code'] ?? ''); ?></small>
                                        </td>
                                        <td class="text-center"><?php echo $type['total_rooms'] ?? 0; ?></td>
                                        <td class="text-center"><?php echo $type['occupied'] ?? 0; ?></td>
                                        <td class="text-center"><?php echo $type['available'] ?? 0; ?></td>
                                        <td class="text-center">
                                            <?php 
                                            $occ = ($type['total_rooms'] ?? 0) > 0 
                                                ? round((($type['occupied'] ?? 0) / ($type['total_rooms'] ?? 1)) * 100, 1) 
                                                : 0;
                                            ?>
                                            <div class="progress progress-xs">
                                                <div class="progress-bar bg-success" style="width: <?php echo $occ; ?>%"></div>
                                            </div>
                                            <small><?php echo $occ; ?>%</small>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Floor Occupancy -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-layer-group me-1"></i>
                            Floor-wise Occupancy
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Floor</th>
                                        <th class="text-center">Total Rooms</th>
                                        <th class="text-center">Occupied</th>
                                        <th class="text-center">Available</th>
                                        <th class="text-center">Occupancy %</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($floor_occupancy as $floor): ?>
                                    <tr>
                                        <td><strong>Floor <?php echo htmlspecialchars($floor['floor'] ?? ''); ?></strong></td>
                                        <td class="text-center"><?php echo $floor['total'] ?? 0; ?></td>
                                        <td class="text-center"><?php echo $floor['occupied'] ?? 0; ?></td>
                                        <td class="text-center"><?php echo ($floor['total'] ?? 0) - ($floor['occupied'] ?? 0); ?></td>
                                        <td class="text-center">
                                            <div class="progress progress-xs">
                                                <div class="progress-bar bg-info" style="width: <?php echo $floor['occupancy_rate'] ?? 0; ?>%"></div>
                                            </div>
                                            <small><?php echo $floor['occupancy_rate'] ?? 0; ?>%</small>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Expected Arrivals/Departures -->
            <div class="col-md-6">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-in-alt me-1"></i>
                            Expected Arrivals Today
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($expected['checkins'])): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar-check fa-3x mb-3"></i>
                                <p>No arrivals expected today</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Room Type</th>
                                            <th class="text-center">Count</th>
                                            <th class="text-end">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($expected['checkins'] as $checkin): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($checkin['type_name'] ?? ''); ?></td>
                                            <td class="text-center">
                                                <span class="badge bg-success"><?php echo $checkin['count'] ?? 0; ?></span>
                                            </td>
                                            <td class="text-end">
                                                <a href="/HMSPOS/reservations/reservations/index.php?check_in_date=<?php echo $today; ?>&room_type=<?php echo $checkin['room_type_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success">
                                                    View
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-out-alt me-1"></i>
                            Expected Departures Today
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($expected['checkouts'])): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar-times fa-3x mb-3"></i>
                                <p>No departures expected today</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Room Type</th>
                                            <th class="text-center">Count</th>
                                            <th class="text-end">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($expected['checkouts'] as $checkout): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($checkout['type_name'] ?? ''); ?></td>
                                            <td class="text-center">
                                                <span class="badge bg-warning"><?php echo $checkout['count'] ?? 0; ?></span>
                                            </td>
                                            <td class="text-end">
                                                <a href="/HMSPOS/reservations/reservations/index.php?check_out_date=<?php echo $today; ?>&room_type=<?php echo $checkout['room_type_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning">
                                                    View
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Revenue by Room Type -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-dollar-sign me-1"></i>
                            Revenue by Room Type (This Month)
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Room Type</th>
                                        <th class="text-center">Bookings</th>
                                        <th class="text-end">Revenue</th>
                                        <th class="text-end">Avg. Rate</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($revenue_by_type as $rev): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($rev['type_name'] ?? ''); ?></td>
                                        <td class="text-center"><?php echo $rev['bookings'] ?? 0; ?></td>
                                        <td class="text-end"><?php echo function_exists('format_currency') ? format_currency($rev['revenue'] ?? 0) : 'RWF ' . number_format($rev['revenue'] ?? 0); ?></td>
                                        <td class="text-end">
                                            <?php 
                                            $avg = ($rev['bookings'] ?? 0) > 0 ? ($rev['revenue'] ?? 0) / ($rev['bookings'] ?? 1) : 0;
                                            echo function_exists('format_currency') ? format_currency($avg) : 'RWF ' . number_format($avg);
                                            ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Upcoming Week Preview -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-calendar-week me-1"></i>
                            Next 7 Days - Arrivals by Room Type
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Room Type</th>
                                        <th class="text-center">Arrivals</th>
                                        <th class="text-center">Confirmed</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $current_date = '';
                                    foreach ($upcoming as $item):
                                        $date_display = $current_date != ($item['date'] ?? '') ? (function_exists('format_date') ? format_date($item['date'] ?? '', 'D, M d') : ($item['date'] ?? '')) : '';
                                        $current_date = $item['date'] ?? '';
                                    ?>
                                    <tr>
                                        <td><?php echo $date_display; ?></td>
                                        <td><?php echo htmlspecialchars($item['type_name'] ?? ''); ?></td>
                                        <td class="text-center"><?php echo $item['arrivals'] ?? 0; ?></td>
                                        <td class="text-center">
                                            <span class="badge bg-success"><?php echo $item['confirmed'] ?? 0; ?></span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Room View Modal -->
<div class="modal fade" id="roomViewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Room Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="roomDetailsContent">
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function viewRoom(roomId) {
    const modal = new bootstrap.Modal(document.getElementById('roomViewModal'));
    modal.show();
    
    document.getElementById('roomDetailsContent').innerHTML = '<div class="text-center"><div class="spinner-border text-primary"></div></div>';
    
    $.get('/HMSPOS/api/get-room.php', { id: roomId }, function(response) {
        if (response.status === 'success') {
            displayRoomDetails(response.data);
        } else {
            document.getElementById('roomDetailsContent').innerHTML = '<div class="alert alert-danger">Failed to load room details</div>';
        }
    }).fail(function() {
        document.getElementById('roomDetailsContent').innerHTML = '<div class="alert alert-danger">Failed to load room details</div>';
    });
}

function displayRoomDetails(room) {
    let html = `
        <div class="row">
            <div class="col-md-6">
                <h4>Room ${room.room_number || ''}</h4>
                <p><strong>Type:</strong> ${room.type_name || 'N/A'}</p>
                <p><strong>Floor:</strong> ${room.floor || 'N/A'}</p>
                <p><strong>Status:</strong> <span class="badge bg-${getStatusBadge(room.status || '')}">${room.status || 'unknown'}</span></p>
                <p><strong>Housekeeping:</strong> <span class="badge bg-${getHKStatusBadge(room.housekeeping_status || '')}">${room.housekeeping_status || 'unknown'}</span></p>
            </div>
            <div class="col-md-6">
                <h5>Current Occupant</h5>
    `;
    
    if (room.guest_name) {
        html += `
            <p><strong>Guest:</strong> ${room.guest_name}</p>
            <p><strong>Check-in:</strong> ${room.check_in_date || 'N/A'}</p>
            <p><strong>Check-out:</strong> ${room.check_out_date || 'N/A'}</p>
            <a href="/HMSPOS/reservations/reservations/view.php?id=${room.reservation_id || 0}" class="btn btn-sm btn-info">View Reservation</a>
        `;
    } else {
        html += '<p class="text-muted">No guest currently</p>';
    }
    
    html += `
            </div>
        </div>
        <hr>
        <div class="text-end">
            <a href="/HMSPOS/rooms/rooms/edit.php?id=${room.room_id || 0}" class="btn btn-warning">Edit Room</a>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
    `;
    
    document.getElementById('roomDetailsContent').innerHTML = html;
}

function getStatusBadge(status) {
    switch(status) {
        case 'available': return 'success';
        case 'occupied': return 'danger';
        case 'maintenance': return 'warning';
        case 'housekeeping': return 'info';
        default: return 'secondary';
    }
}

function getHKStatusBadge(status) {
    switch(status) {
        case 'clean': return 'success';
        case 'dirty': return 'warning';
        case 'inspected': return 'info';
        case 'out_of_service': return 'danger';
        default: return 'secondary';
    }
}

function refreshRoomGrid() {
    location.reload();
}

// Auto-refresh every 5 minutes (300000 ms)
setInterval(function() {
    location.reload();
}, 300000);

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mb-4 { margin-bottom: 1.5rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.text-end { text-align: right; }

.room-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
}
.room-item {
    background: #fff;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 10px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}
.room-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.room-item.available { border-left: 4px solid #28a745; }
.room-item.occupied { border-left: 4px solid #dc3545; }
.room-item.maintenance { border-left: 4px solid #ffc107; }
.room-item.housekeeping { border-left: 4px solid #17a2b8; }
.room-item.blocked { border-left: 4px solid #6c757d; }
.room-number {
    font-size: 1.2rem;
    font-weight: 600;
}
.room-type {
    font-size: 0.8rem;
    color: #6c757d;
}
.guest-name {
    font-size: 0.8rem;
    margin-top: 5px;
    color: #007bff;
}
.hk-status {
    margin-top: 5px;
}
.progress-xs {
    height: 5px;
}
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>