<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Rooms Management - List View - 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
// Current file: /HMSPOS/rooms/rooms/index.php
// Need to go up to: /HMSPOS/
$base_path = null;

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

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

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define truncate_text function if it doesn't exist
if (!function_exists('truncate_text')) {
    function truncate_text($text, $length = 15) {
        if (strlen($text) <= $length) return $text;
        return substr($text, 0, $length) . '...';
    }
}

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

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

// 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 filter parameters
$search = $_GET['search'] ?? '';
$room_type_id = isset($_GET['room_type_id']) && $_GET['room_type_id'] !== '' ? (int)$_GET['room_type_id'] : null;
$status = $_GET['status'] ?? '';
$hk_status = $_GET['hk_status'] ?? '';
$floor = $_GET['floor'] ?? '';
$sort = $_GET['sort'] ?? 'room_number';
$order = $_GET['order'] ?? 'ASC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 50;

// Build where clause
$where = "r.is_active = 1";
$params = [];

if (!empty($search)) {
    $where .= " AND (r.room_number LIKE ? OR rt.type_name LIKE ? OR rt.type_code LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

if ($room_type_id) {
    $where .= " AND r.room_type_id = ?";
    $params[] = $room_type_id;
}

if (!empty($status)) {
    $where .= " AND r.status = ?";
    $params[] = $status;
}

if (!empty($hk_status)) {
    $where .= " AND r.housekeeping_status = ?";
    $params[] = $hk_status;
}

if (!empty($floor)) {
    $where .= " AND r.floor = ?";
    $params[] = $floor;
}

// Validate sort column
$allowed_sort = ['room_id', 'room_number', 'floor', 'status', 'housekeeping_status', 'room_type_id'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'room_number';
}

// Get rooms with details
$rooms = [];
try {
    $sql = "
        SELECT 
            r.*,
            rt.type_name, rt.type_code, rt.base_price,
            CONCAT(g.first_name, ' ', g.last_name) as guest_name,
            g.guest_id,
            res.reservation_id, res.booking_code,
            res.check_in_date, res.check_out_date
        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 $where
        ORDER BY 
            CASE 
                WHEN r.status = 'occupied' THEN 1
                WHEN r.status = 'housekeeping' THEN 2
                WHEN r.status = 'available' THEN 3
                ELSE 4
            END,
            $sort $order
    ";
    
    // Get total count
    $count_sql = "SELECT COUNT(*) FROM rooms r WHERE $where";
    $total = (int)db_fetch_value($count_sql, $params) ?: 0;
    
    // Get paginated data
    $offset = ($page - 1) * $per_page;
    $data_sql = $sql . " LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
    $rooms = db_fetch_all($data_sql, $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching rooms: " . $e->getMessage());
    $total = 0;
    $rooms = [];
}

// Calculate pagination
$total_pages = $per_page > 0 ? ceil($total / $per_page) : 1;

// Get filter options
$room_types = [];
try {
    $room_types = db_fetch_all("SELECT room_type_id, type_name, type_code FROM room_types ORDER BY type_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
}

$floors = [];
try {
    $floors = db_fetch_all("SELECT DISTINCT floor FROM rooms WHERE floor IS NOT NULL AND floor != '' ORDER BY floor") ?: [];
} catch (Exception $e) {
    error_log("Error fetching floors: " . $e->getMessage());
}

// Get status counts for summary
$status_counts = [];
try {
    $status_counts = db_fetch_all("
        SELECT 
            status,
            COUNT(*) as count
        FROM rooms
        WHERE is_active = 1
        GROUP BY status
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching status counts: " . $e->getMessage());
}

$hk_status_counts = [];
try {
    $hk_status_counts = db_fetch_all("
        SELECT 
            housekeeping_status,
            COUNT(*) as count
        FROM rooms
        WHERE is_active = 1
        GROUP BY housekeeping_status
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching HK status counts: " . $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 Management</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; }
        </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 Management</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 Management</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">Rooms</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if (function_exists('display_flash_messages')): ?>
            <?php display_flash_messages(); ?>
        <?php endif; ?>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php 
                            $total = array_sum(array_column($status_counts, 'count'));
                            echo $total;
                        ?></h3>
                        <p>Total Rooms</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-hotel"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php 
                            $available = 0;
                            foreach ($status_counts as $s) {
                                if (($s['status'] ?? '') == 'available') $available = $s['count'] ?? 0;
                            }
                            echo $available;
                        ?></h3>
                        <p>Available</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-door-open"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php 
                            $occupied = 0;
                            foreach ($status_counts as $s) {
                                if (($s['status'] ?? '') == 'occupied') $occupied = $s['count'] ?? 0;
                            }
                            echo $occupied;
                        ?></h3>
                        <p>Occupied</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-bed"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php 
                            $maintenance = 0;
                            foreach ($status_counts as $s) {
                                if (($s['status'] ?? '') == 'maintenance') $maintenance = $s['count'] ?? 0;
                            }
                            echo $maintenance;
                        ?></h3>
                        <p>Maintenance</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-tools"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php 
                            $housekeeping = 0;
                            foreach ($status_counts as $s) {
                                if (($s['status'] ?? '') == 'housekeeping') $housekeeping = $s['count'] ?? 0;
                            }
                            echo $housekeeping;
                        ?></h3>
                        <p>Housekeeping</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-broom"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-dark">
                    <div class="inner">
                        <h3><?php 
                            $dirty = 0;
                            foreach ($hk_status_counts as $s) {
                                if (($s['housekeeping_status'] ?? '') == 'dirty') $dirty = $s['count'] ?? 0;
                            }
                            echo $dirty;
                        ?></h3>
                        <p>Dirty Rooms</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-broom"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter me-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-2">
                        <input type="text" class="form-control" name="search" placeholder="Search room # or type..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="room_type_id">
                            <option value="">All Room Types</option>
                            <?php foreach ($room_types as $type): ?>
                                <option value="<?php echo $type['room_type_id'] ?? 0; ?>" <?php echo $room_type_id == ($type['room_type_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars(($type['type_name'] ?? '') . ' (' . ($type['type_code'] ?? '') . ')'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">All Status</option>
                            <option value="available" <?php echo $status == 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="occupied" <?php echo $status == 'occupied' ? 'selected' : ''; ?>>Occupied</option>
                            <option value="maintenance" <?php echo $status == 'maintenance' ? 'selected' : ''; ?>>Maintenance</option>
                            <option value="housekeeping" <?php echo $status == 'housekeeping' ? 'selected' : ''; ?>>Housekeeping</option>
                            <option value="blocked" <?php echo $status == 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="hk_status">
                            <option value="">All HK Status</option>
                            <option value="clean" <?php echo $hk_status == 'clean' ? 'selected' : ''; ?>>Clean</option>
                            <option value="dirty" <?php echo $hk_status == 'dirty' ? 'selected' : ''; ?>>Dirty</option>
                            <option value="inspected" <?php echo $hk_status == 'inspected' ? 'selected' : ''; ?>>Inspected</option>
                            <option value="out_of_service" <?php echo $hk_status == 'out_of_service' ? 'selected' : ''; ?>>Out of Service</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="floor">
                            <option value="">All Floors</option>
                            <?php foreach ($floors as $f): ?>
                                <option value="<?php echo htmlspecialchars($f['floor'] ?? ''); ?>" <?php echo $floor == ($f['floor'] ?? '') ? 'selected' : ''; ?>>
                                    Floor <?php echo htmlspecialchars($f['floor'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="per_page">
                            <option value="25" <?php echo $per_page == 25 ? 'selected' : ''; ?>>25 per page</option>
                            <option value="50" <?php echo $per_page == 50 ? 'selected' : ''; ?>>50 per page</option>
                            <option value="100" <?php echo $per_page == 100 ? 'selected' : ''; ?>>100 per page</option>
                            <option value="200" <?php echo $per_page == 200 ? 'selected' : ''; ?>>200 per page</option>
                        </select>
                    </div>
                    
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search me-1"></i> Apply Filters
                        </button>
                        
                        <a href="?" class="btn btn-secondary">
                            <i class="fas fa-times me-1"></i> Clear
                        </a>
                        
                        <?php if (function_exists('has_permission') && has_permission('rooms.create')): ?>
                            <a href="create.php" class="btn btn-success float-end">
                                <i class="fas fa-plus"></i> Add Room
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- Rooms Grid/Table View Toggle -->
        <div class="row mb-2">
            <div class="col-12">
                <div class="btn-group">
                    <button type="button" class="btn btn-sm btn-info active" id="gridViewBtn">
                        <i class="fas fa-th-large"></i> Grid View
                    </button>
                    <button type="button" class="btn btn-sm btn-secondary" id="tableViewBtn">
                        <i class="fas fa-list"></i> Table View
                    </button>
                </div>
            </div>
        </div>

        <!-- Grid View -->
        <div id="gridView" style="display: block;">
            <div class="room-grid">
                <?php if (empty($rooms)): ?>
                    <div class="col-12 text-center text-muted py-5">
                        <i class="fas fa-door-open fa-4x mb-3"></i>
                        <h5>No rooms found</h5>
                        <p>Try adjusting your filters</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($rooms as $room): ?>
                        <div class="room-item status-<?php echo $room['status'] ?? 'available'; ?>" 
                             onclick="viewRoom(<?php echo $room['room_id'] ?? 0; ?>)">
                            <div class="room-number"><?php echo htmlspecialchars($room['room_number'] ?? ''); ?></div>
                            <div class="room-type"><?php echo htmlspecialchars($room['type_code'] ?? ''); ?></div>
                            <div class="room-status">
                                <span class="badge bg-<?php 
                                    echo ($room['status'] ?? '') == 'available' ? 'success' : 
                                        (($room['status'] ?? '') == 'occupied' ? 'danger' : 
                                        (($room['status'] ?? '') == 'maintenance' ? 'warning' : 
                                        (($room['status'] ?? '') == 'housekeeping' ? 'info' : 'secondary')));
                                ?>">
                                    <?php echo ucfirst($room['status'] ?? 'unknown'); ?>
                                </span>
                            </div>
                            <?php if (!empty($room['guest_name'])): ?>
                                <div class="guest-name" title="<?php echo htmlspecialchars($room['guest_name']); ?>">
                                    <i class="fas fa-user"></i> 
                                    <?php echo htmlspecialchars(truncate_text($room['guest_name'], 15)); ?>
                                </div>
                                <div class="checkout-date">
                                    <small><?php echo !empty($room['check_out_date']) ? format_date($room['check_out_date'], 'M d') : ''; ?></small>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($room['housekeeping_status']) && $room['housekeeping_status'] != 'clean'): ?>
                                <div class="hk-indicator">
                                    <span class="badge bg-<?php 
                                        echo ($room['housekeeping_status'] ?? '') == 'dirty' ? 'warning' : 
                                            (($room['housekeeping_status'] ?? '') == 'inspected' ? 'info' : 'secondary');
                                    ?>">
                                        <?php echo ucfirst($room['housekeeping_status'] ?? ''); ?>
                                    </span>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Table View -->
        <div id="tableView" style="display: none;">
            <div class="card">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Room #</th>
                                    <th>Floor</th>
                                    <th>Type</th>
                                    <th>Status</th>
                                    <th>Housekeeping</th>
                                    <th>Current Guest</th>
                                    <th>Check-out</th>
                                    <th>Rate</th>
                                    <th width="120">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($rooms as $room): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($room['room_number'] ?? ''); ?></strong>
                                    </td>
                                    <td><?php echo htmlspecialchars($room['floor'] ?? '-'); ?></td>
                                    <td>
                                        <?php echo htmlspecialchars($room['type_name'] ?? ''); ?>
                                        <br>
                                        <small><?php echo htmlspecialchars($room['type_code'] ?? ''); ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo ($room['status'] ?? '') == 'available' ? 'success' : 
                                                (($room['status'] ?? '') == 'occupied' ? 'danger' : 
                                                (($room['status'] ?? '') == 'maintenance' ? 'warning' : 
                                                (($room['status'] ?? '') == 'housekeeping' ? 'info' : 'secondary')));
                                        ?>">
                                            <?php echo ucfirst($room['status'] ?? 'unknown'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo ($room['housekeeping_status'] ?? '') == 'clean' ? 'success' : 
                                                (($room['housekeeping_status'] ?? '') == 'dirty' ? 'warning' : 
                                                (($room['housekeeping_status'] ?? '') == 'inspected' ? 'info' : 'secondary'));
                                        ?>">
                                            <?php echo ucfirst($room['housekeeping_status'] ?? 'unknown'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($room['guest_name'])): ?>
                                            <a href="/HMSPOS/guests/guests/view.php?id=<?php echo $room['guest_id'] ?? 0; ?>">
                                                <?php echo htmlspecialchars($room['guest_name']); ?>
                                            </a>
                                        <?php else: ?>
                                            <span class="text-muted">Vacant</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo !empty($room['check_out_date']) ? format_date($room['check_out_date']) : '-'; ?></td>
                                    <td><?php echo format_currency($room['base_price'] ?? 0); ?></td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="view.php?id=<?php echo $room['room_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('rooms.edit')): ?>
                                                <a href="edit.php?id=<?php echo $room['room_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            <?php endif; ?>
                                            
                                            <a href="status.php?id=<?php echo $room['room_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-primary" title="Change Status">
                                                <i class="fas fa-sync-alt"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="row mt-3">
            <div class="col-sm-5">
                <span class="text-muted">
                    Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $per_page, $total); ?> of <?php echo $total; ?> rooms
                </span>
            </div>
            <div class="col-sm-7">
                <ul class="pagination pagination-sm float-end">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=1&search=<?php echo urlencode($search); ?>&room_type_id=<?php echo $room_type_id; ?>&status=<?php echo $status; ?>&hk_status=<?php echo $hk_status; ?>&floor=<?php echo $floor; ?>&per_page=<?php echo $per_page; ?>">
                                <i class="fas fa-angle-double-left"></i>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&room_type_id=<?php echo $room_type_id; ?>&status=<?php echo $status; ?>&hk_status=<?php echo $hk_status; ?>&floor=<?php echo $floor; ?>&per_page=<?php echo $per_page; ?>">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $page + 2);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&room_type_id=<?php echo $room_type_id; ?>&status=<?php echo $status; ?>&hk_status=<?php echo $hk_status; ?>&floor=<?php echo $floor; ?>&per_page=<?php echo $per_page; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&room_type_id=<?php echo $room_type_id; ?>&status=<?php echo $status; ?>&hk_status=<?php echo $hk_status; ?>&floor=<?php echo $floor; ?>&per_page=<?php echo $per_page; ?>">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&room_type_id=<?php echo $room_type_id; ?>&status=<?php echo $status; ?>&hk_status=<?php echo $hk_status; ?>&floor=<?php echo $floor; ?>&per_page=<?php echo $per_page; ?>">
                                <i class="fas fa-angle-double-right"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
        <?php endif; ?>
    </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>
$(document).ready(function() {
    // Grid/Table view toggle
    $('#gridViewBtn').click(function() {
        $(this).addClass('active btn-info').removeClass('btn-secondary');
        $('#tableViewBtn').removeClass('active btn-info').addClass('btn-secondary');
        $('#gridView').show();
        $('#tableView').hide();
        localStorage.setItem('roomViewMode', 'grid');
    });
    
    $('#tableViewBtn').click(function() {
        $(this).addClass('active btn-info').removeClass('btn-secondary');
        $('#gridViewBtn').removeClass('active btn-info').addClass('btn-secondary');
        $('#gridView').hide();
        $('#tableView').show();
        localStorage.setItem('roomViewMode', 'table');
    });
    
    // Load saved view mode
    const savedMode = localStorage.getItem('roomViewMode');
    if (savedMode === 'table') {
        $('#tableViewBtn').click();
    }
});

function viewRoom(roomId) {
    const modal = new bootstrap.Modal(document.getElementById('roomViewModal'));
    modal.show();
    
    $('#roomDetailsContent').html('<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 {
            $('#roomDetailsContent').html('<div class="alert alert-danger">Failed to load room details</div>');
        }
    }).fail(function() {
        $('#roomDetailsContent').html('<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 || ''} (${room.type_code || ''})</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>
                <p><strong>Base Rate:</strong> ${formatCurrency(room.base_price || 0)}</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 || ''}</p>
            <p><strong>Check-out:</strong> ${room.check_out_date || ''}</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>
            <a href="/HMSPOS/rooms/rooms/status.php?id=${room.room_id || 0}" class="btn btn-primary">Change Status</a>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
    `;
    
    $('#roomDetailsContent').html(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 formatCurrency(amount) {
    return 'RWF ' + parseFloat(amount).toLocaleString();
}
</script>

<style>
.room-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 12px;
    margin-bottom: 20px;
}
.room-item {
    background: #fff;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 12px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.room-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}
.room-item.status-available { border-left: 4px solid #28a745; }
.room-item.status-occupied { border-left: 4px solid #dc3545; }
.room-item.status-maintenance { border-left: 4px solid #ffc107; }
.room-item.status-housekeeping { border-left: 4px solid #17a2b8; }
.room-item.status-blocked { border-left: 4px solid #6c757d; }
.room-number {
    font-size: 1.3rem;
    font-weight: 600;
}
.room-type {
    font-size: 0.9rem;
    color: #6c757d;
    margin: 5px 0;
}
.room-status {
    margin: 5px 0;
}
.guest-name {
    font-size: 0.85rem;
    margin-top: 5px;
    color: #007bff;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.checkout-date {
    font-size: 0.75rem;
    color: #dc3545;
}
.hk-indicator {
    position: absolute;
    top: 5px;
    right: 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; }
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.text-end { text-align: right; }
.float-end { float: right; }
</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>';
}
?>