<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Room Status Management - COMPLETE FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct base path
$base_path = null;

// Current file: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/housekeeping/cleaning/room-status.php
// We need to go up to: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/

// Method 1: Try going up 3 levels (from room-status.php to HMSPOS)
$base_path = dirname(__DIR__, 3);

// Method 2: If that doesn't work, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: Absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try relative path from document root
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = $_SERVER['DOCUMENT_ROOT'] . '/HMSPOS';
}

// Verify the base path works
if (!file_exists($base_path . '/config/config.php')) {
    die("Error: Cannot find system files. Tried: " . $base_path . "/config/config.php");
}

// Initialize system
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/constants.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Load csrf if it exists
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}

// Define helper functions if they don't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        return '<input type="hidden" name="csrf_token" value="' . csrf_token() . '">';
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token() {
        return session_id() . '-' . time();
    }
}

if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return true; // Bypass for now - implement properly in production
    }
}

if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('sanitize_input')) {
    function sanitize_input($input) {
        return htmlspecialchars(trim($input ?? ''), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        $timestamp = strtotime($date);
        return $timestamp ? date($format, $timestamp) : $date;
    }
}

if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        global $db;
        if (isset($db) && method_exists($db, 'begin_transaction')) {
            $db->begin_transaction();
        }
    }
}

if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        global $db;
        if (isset($db) && method_exists($db, 'commit')) {
            $db->commit();
        }
    }
}

if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        global $db;
        if (isset($db) && method_exists($db, 'rollback')) {
            $db->rollback();
        }
    }
}

if (!function_exists('db_update')) {
    function db_update($table, $data, $where, $params = []) {
        try {
            $set = [];
            foreach ($data as $key => $value) {
                $set[] = "$key = ?";
                array_unshift($params, $value);
            }
            $set_str = implode(', ', $set);
            $sql = "UPDATE $table SET $set_str WHERE $where";
            return db_execute($sql, $params);
        } catch (Exception $e) {
            error_log("Error in db_update: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('db_insert')) {
    function db_insert($table, $data) {
        try {
            $columns = implode(', ', array_keys($data));
            $placeholders = implode(', ', array_fill(0, count($data), '?'));
            $sql = "INSERT INTO $table ($columns) VALUES ($placeholders)";
            return db_execute($sql, array_values($data));
        } catch (Exception $e) {
            error_log("Error in db_insert: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('db_execute')) {
    function db_execute($sql, $params = []) {
        global $db;
        try {
            $stmt = $db->prepare($sql);
            if ($params) {
                $types = str_repeat('s', count($params));
                $stmt->bind_param($types, ...$params);
            }
            $stmt->execute();
            return $stmt->affected_rows;
        } catch (Exception $e) {
            error_log("Error in db_execute: " . $e->getMessage());
            return false;
        }
    }
}

// Require authentication and permission
require_auth();

// Check if permission function exists
if (function_exists('require_permission')) {
    require_permission('hk.tasks.view');
}

// Set page title
$page_title = 'Room Status';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;

// Get filter parameters
$floor = $_GET['floor'] ?? '';
$status = $_GET['status'] ?? '';
$hk_status = $_GET['hk_status'] ?? '';
$search = $_GET['search'] ?? '';

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

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

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

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

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

// Initialize variables
$rooms = [];
$floors = [];
$stats = [
    'total' => 0,
    'occupied' => 0,
    'available' => 0,
    'maintenance' => 0,
    'housekeeping' => 0,
    'clean' => 0,
    'dirty' => 0,
    'inspected' => 0
];
$message = '';
$error = '';

// Get rooms with current status
try {
    // Check if tables exist
    $rooms_table_exists = db_fetch_value("SHOW TABLES LIKE 'rooms'");
    $room_types_exists = db_fetch_value("SHOW TABLES LIKE 'room_types'");
    
    if ($rooms_table_exists && $room_types_exists) {
        $rooms = db_fetch_all("
            SELECT 
                r.*,
                rt.type_name,
                CONCAT(g.first_name, ' ', g.last_name) as guest_name,
                res.reservation_id, res.booking_code,
                res.check_in_date, res.check_out_date,
                t.task_id, t.priority, t.status as task_status,
                u.first_name as assigned_first, u.last_name as assigned_last
            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
            LEFT JOIN hk_tasks t ON r.room_id = t.room_id 
                AND t.status IN ('pending', 'assigned', 'in_progress')
            LEFT JOIN users u ON t.assigned_to = u.user_id
            WHERE $where
            ORDER BY r.floor, r.room_number
        ", $params) ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting rooms: " . $e->getMessage());
    $rooms = [];
}

// Get distinct floors for filter
try {
    if ($rooms_table_exists) {
        $floors = db_fetch_all("SELECT DISTINCT floor FROM rooms WHERE floor IS NOT NULL ORDER BY floor") ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting floors: " . $e->getMessage());
    $floors = [];
}

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

// Handle bulk status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_update'])) {
    if (defined('CSRF_TOKEN_NAME') && !verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $room_ids = $_POST['room_ids'] ?? [];
        $new_status = sanitize_input($_POST['new_status'] ?? '');
        $new_hk_status = sanitize_input($_POST['new_hk_status'] ?? '');
        
        if (empty($room_ids)) {
            $error = 'Please select at least one room';
        } elseif (empty($new_status) && empty($new_hk_status)) {
            $error = 'Please select a status to update';
        } else {
            try {
                begin_transaction();
                
                foreach ($room_ids as $room_id) {
                    $room_id = (int)$room_id;
                    $update_data = [];
                    
                    if (!empty($new_status)) {
                        $update_data['status'] = $new_status;
                    }
                    
                    if (!empty($new_hk_status)) {
                        $update_data['housekeeping_status'] = $new_hk_status;
                    }
                    
                    if (!empty($update_data)) {
                        $update_data['updated_at'] = date('Y-m-d H:i:s');
                        db_update('rooms', $update_data, 'room_id = ?', [$room_id]);
                        
                        // Create housekeeping task if marked dirty
                        if ($new_hk_status == 'dirty') {
                            $task_code = 'HK-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                            
                            db_insert('hk_tasks', [
                                'task_code' => $task_code,
                                'room_id' => $room_id,
                                'task_type' => 'cleaning',
                                'priority' => 'medium',
                                'status' => 'pending',
                                'notes' => 'Auto-created from bulk status update',
                                'created_by' => $current_user['user_id'] ?? 0,
                                'created_at' => date('Y-m-d H:i:s')
                            ]);
                        }
                    }
                }
                
                $message = 'Room statuses updated successfully';
                commit_transaction();
                
            } catch (Exception $e) {
                rollback_transaction();
                $error = 'Failed to update room statuses: ' . $e->getMessage();
            }
        }
    }
}

// Include header - check multiple possible locations
$header_paths = [
    $base_path . '/views/partials/header.php',
    $base_path . '/includes/header.php'
];

$header_found = false;
foreach ($header_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $header_found = true;
        break;
    }
}

if (!$header_found) {
    // 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>Room Status</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; display: block; }
            .small-box > .inner { padding: 10px; }
            .small-box h3 { font-size: 2.2rem; font-weight: bold; margin: 0 0 10px 0; white-space: nowrap; padding: 0; }
            .small-box p { font-size: 1rem; }
            .small-box .icon { position: absolute; top: 10px; right: 10px; z-index: 0; font-size: 70px; color: rgba(0,0,0,0.15); }
            .badge { padding: 5px 10px; border-radius: 4px; }
            .badge-success { background-color: #28a745; color: #fff; }
            .badge-warning { background-color: #ffc107; color: #000; }
            .badge-danger { background-color: #dc3545; color: #fff; }
            .badge-info { background-color: #17a2b8; color: #fff; }
            .badge-secondary { background-color: #6c757d; color: #fff; }
        </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="#">Ruhondo Beach Resort</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="<?php echo base_url('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">Room Status</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('public/dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('housekeeping/dashboard.php'); ?>">Housekeeping</a></li>
                    <li class="breadcrumb-item active">Room Status</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo htmlspecialchars($error); ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?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 echo $stats['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-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-2 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-2 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 class="col-lg-2 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3><?php echo $stats['clean']; ?></h3>
                        <p>Clean</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php echo $stats['dirty']; ?></h3>
                        <p>Dirty</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 mr-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-3">
                        <input type="text" class="form-control" name="search" placeholder="Search room # or type..." 
                               value="<?php echo escape_html($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-control" name="floor">
                            <option value="">All Floors</option>
                            <?php foreach ($floors as $f): ?>
                                <option value="<?php echo $f['floor']; ?>" <?php echo $floor == $f['floor'] ? 'selected' : ''; ?>>
                                    Floor <?php echo $f['floor']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-control" 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-control" 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-3">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search mr-1"></i> Apply Filters
                        </button>
                        
                        <a href="?" class="btn btn-secondary">
                            <i class="fas fa-times mr-1"></i> Clear
                        </a>
                        
                        <button type="button" class="btn btn-info" onclick="showBulkUpdate()">
                            <i class="fas fa-edit"></i> Bulk
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Room Status Grid -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-th-large mr-1"></i>
                    Room Status Overview
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-sm btn-primary" onclick="refreshView()">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>
            
            <div class="card-body">
                <?php if (empty($rooms)): ?>
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-door-open fa-3x mb-3"></i>
                        <p>No rooms found matching your criteria</p>
                    </div>
                <?php else: ?>
                <div class="room-status-grid">
                    <?php foreach ($rooms as $room): ?>
                    <div class="room-status-card status-<?php echo $room['status']; ?> hk-<?php echo $room['housekeeping_status']; ?>"
                         onclick="showRoomOptions(<?php echo $room['room_id']; ?>)">
                        
                        <div class="room-header">
                            <span class="room-number"><?php echo $room['room_number']; ?></span>
                            <?php if (!empty($room['guest_name'])): ?>
                                <span class="guest-indicator" title="Occupied">
                                    <i class="fas fa-user"></i>
                                </span>
                            <?php endif; ?>
                        </div>
                        
                        <div class="room-type">
                            <small><?php echo $room['type_name']; ?></small>
                        </div>
                        
                        <div class="status-badges">
                            <span class="badge badge-<?php 
                                echo $room['status'] == 'available' ? 'success' : 
                                    ($room['status'] == 'occupied' ? 'danger' : 
                                    ($room['status'] == 'maintenance' ? 'warning' : 
                                    ($room['status'] == 'housekeeping' ? 'info' : 'secondary')));
                            ?>">
                                <?php echo ucfirst($room['status']); ?>
                            </span>
                            
                            <span class="badge badge-<?php 
                                echo $room['housekeeping_status'] == 'clean' ? 'success' : 
                                    ($room['housekeeping_status'] == 'dirty' ? 'warning' : 
                                    ($room['housekeeping_status'] == 'inspected' ? 'info' : 'secondary'));
                            ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $room['housekeeping_status'])); ?>
                            </span>
                        </div>
                        
                        <?php if (!empty($room['task_status'])): ?>
                        <div class="task-indicator">
                            <span class="badge badge-<?php 
                                echo $room['priority'] == 'urgent' ? 'danger' : 
                                    ($room['priority'] == 'high' ? 'warning' : 'info');
                            ?>">
                                <i class="fas fa-broom"></i> Task
                            </span>
                            <?php if (!empty($room['assigned_first'])): ?>
                                <br>
                                <small><?php echo $room['assigned_first']; ?></small>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($room['guest_name'])): ?>
                        <div class="guest-info">
                            <small><?php echo escape_html($room['guest_name']); ?></small>
                            <br>
                            <small class="text-muted">Until <?php echo format_date($room['check_out_date'], 'M d'); ?></small>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- Bulk Update Modal -->
<div class="modal fade" id="bulkUpdateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Bulk Update Room Status</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form method="POST">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="bulk_update" value="1">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label>Select Rooms</label>
                        <div style="max-height: 300px; overflow-y: auto; border: 1px solid #dee2e6; padding: 10px; border-radius: 4px;">
                            <?php if (empty($rooms)): ?>
                                <p class="text-muted">No rooms available</p>
                            <?php else: ?>
                                <?php foreach ($rooms as $room): ?>
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" 
                                           id="room_<?php echo $room['room_id']; ?>" 
                                           name="room_ids[]" value="<?php echo $room['room_id']; ?>">
                                    <label class="form-check-label" for="room_<?php echo $room['room_id']; ?>">
                                        Room <?php echo $room['room_number']; ?> - <?php echo $room['type_name']; ?>
                                    </label>
                                </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="new_status">Update Room Status</label>
                        <select class="form-control" id="new_status" name="new_status">
                            <option value="">No Change</option>
                            <option value="available">Available</option>
                            <option value="maintenance">Maintenance</option>
                            <option value="blocked">Blocked</option>
                        </select>
                        <small class="text-muted">Note: Occupied status cannot be set manually</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="new_hk_status">Update Housekeeping Status</label>
                        <select class="form-control" id="new_hk_status" name="new_hk_status">
                            <option value="">No Change</option>
                            <option value="clean">Clean</option>
                            <option value="dirty">Dirty</option>
                            <option value="inspected">Inspected</option>
                            <option value="out_of_service">Out of Service</option>
                        </select>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        <strong>Note:</strong> Marking a room as dirty will automatically create a cleaning task.
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Selected</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Room Options Modal -->
<div class="modal fade" id="roomOptionsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Room Actions</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="roomOptionsContent">
                <div class="text-center">
                    <div class="spinner-border text-primary"></div>
                    <p>Loading room options...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Global variables - FIXED URL
const baseUrl = '<?php echo base_url(''); ?>';
const apiBaseUrl = '<?php echo base_url('api/'); ?>'; // This ensures /HMSPOS/api/

console.log('Base URL:', baseUrl);
console.log('API Base URL:', apiBaseUrl);

function showBulkUpdate() {
    $('#bulkUpdateModal').modal('show');
}

function showRoomOptions(roomId) {
    $('#roomOptionsModal').modal('show');
    $('#roomOptionsContent').html('<div class="text-center"><div class="spinner-border text-primary"></div><p>Loading room options...</p></div>');
    
    // Fixed URL - use apiBaseUrl
    const apiUrl = apiBaseUrl + 'get-room-options.php';
    
    console.log('Fetching room options from:', apiUrl, 'for room ID:', roomId);
    
    // Also test if the API file exists by making a HEAD request
    $.ajax({
        url: apiUrl,
        method: 'HEAD',
        success: function() {
            console.log('API endpoint exists, proceeding with GET request');
            // Now make the actual GET request
            $.ajax({
                url: apiUrl,
                method: 'GET',
                data: { 
                    id: roomId, 
                    t: new Date().getTime() // Add timestamp to prevent caching
                },
                dataType: 'json',
                timeout: 10000, // 10 second timeout
                success: function(response) {
                    console.log('API Response:', response);
                    
                    if (response && response.status === 'success') {
                        renderRoomOptions(response.data, roomId);
                    } else {
                        $('#roomOptionsContent').html(
                            '<div class="alert alert-danger">Failed to load room options: ' + 
                            (response.message || 'Unknown error') + '</div>' +
                            '<div class="text-center mt-3">' +
                            '<button class="btn btn-sm btn-primary" onclick="showRoomOptions(' + roomId + ')">Retry</button>' +
                            '</div>'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    console.error('Response Text:', xhr.responseText);
                    
                    let errorMsg = 'Failed to load room options. ';
                    if (status === 'timeout') {
                        errorMsg += 'Request timed out.';
                    } else if (xhr.status === 404) {
                        errorMsg += 'API endpoint not found. Please check if the API file exists at: ' + apiUrl;
                    } else if (xhr.status === 500) {
                        errorMsg += 'Server error. Check PHP error logs.';
                    } else {
                        errorMsg += error;
                    }
                    
                    $('#roomOptionsContent').html(
                        '<div class="alert alert-danger">' + errorMsg + 
                        '<br><small>URL: ' + apiUrl + '</small>' +
                        '<br><button class="btn btn-sm btn-primary mt-2" onclick="showRoomOptions(' + roomId + ')">Retry</button>' +
                        '</div>'
                    );
                }
            });
        },
        error: function(xhr, status, error) {
            console.error('API endpoint check failed:', status, error);
            $('#roomOptionsContent').html(
                '<div class="alert alert-danger">' +
                '<strong>API endpoint not found!</strong><br>' +
                'The file <code>get-room-options.php</code> does not exist at: ' + apiUrl + '<br><br>' +
                '<strong>Please create the API file at:</strong><br>' +
                '<code>' + apiUrl + '</code><br><br>' +
                '<button class="btn btn-sm btn-primary" onclick="window.location.href=\'' + baseUrl + 'api/test.php\'">' +
                'Run API Test</button>' +
                '</div>'
            );
        }
    });
}

function renderRoomOptions(room, roomId) {
    let html = '';
    
    // Room info section
    html += '<div class="text-center mb-3">';
    html += '<h4>Room ' + room.room_number + '</h4>';
    html += '<p class="text-muted">' + room.type_name + '</p>';
    html += '</div>';
    
    // Current status
    html += '<div class="mb-3">';
    html += '<strong>Current Status:</strong><br>';
    html += '<span class="badge badge-' + getStatusBadge(room.status) + ' mr-1">' + capitalize(room.status) + '</span>';
    html += '<span class="badge badge-' + getHKStatusBadge(room.housekeeping_status) + '">' + capitalize(room.housekeeping_status.replace('_', ' ')) + '</span>';
    html += '</div>';
    
    // Guest info if occupied
    if (room.guest_name) {
        html += '<div class="mb-3">';
        html += '<strong>Guest:</strong><br>';
        html += room.guest_name + '<br>';
        if (room.check_out_date) {
            html += '<small class="text-muted">Check-out: ' + room.check_out_date + '</small>';
        }
        html += '</div>';
    }
    
    // Quick actions
    html += '<div class="mb-3">';
    html += '<strong>Quick Actions:</strong><br>';
    html += '<div class="btn-group-vertical w-100">';
    
    // Room status actions
    if (room.status !== 'occupied') {
        html += '<button class="btn btn-sm btn-outline-primary text-left mb-1" onclick="updateRoomStatus(' + roomId + ', \'status\', \'available\')">';
        html += '<i class="fas fa-door-open mr-2"></i> Set as Available</button>';
    }
    
    html += '<button class="btn btn-sm btn-outline-warning text-left mb-1" onclick="updateRoomStatus(' + roomId + ', \'status\', \'maintenance\')">';
    html += '<i class="fas fa-tools mr-2"></i> Set as Maintenance</button>';
    
    // HK status actions
    html += '<button class="btn btn-sm btn-outline-success text-left mb-1" onclick="updateRoomStatus(' + roomId + ', \'housekeeping_status\', \'clean\')">';
    html += '<i class="fas fa-check-circle mr-2"></i> Mark as Clean</button>';
    
    html += '<button class="btn btn-sm btn-outline-warning text-left mb-1" onclick="updateRoomStatus(' + roomId + ', \'housekeeping_status\', \'dirty\')">';
    html += '<i class="fas fa-broom mr-2"></i> Mark as Dirty</button>';
    
    html += '<button class="btn btn-sm btn-outline-info text-left mb-1" onclick="updateRoomStatus(' + roomId + ', \'housekeeping_status\', \'inspected\')">';
    html += '<i class="fas fa-clipboard-check mr-2"></i> Mark as Inspected</button>';
    
    html += '</div>';
    html += '</div>';
    
    // Create task link
    html += '<hr>';
    html += '<div class="text-center">';
    html += '<a href="' + baseUrl + 'housekeeping/tasks/create.php?room_id=' + roomId + '" class="btn btn-sm btn-primary">';
    html += '<i class="fas fa-plus-circle mr-1"></i> Create Cleaning Task</a>';
    html += '</div>';
    
    $('#roomOptionsContent').html(html);
}

function updateRoomStatus(roomId, field, value) {
    // Confirm action
    if (!confirm('Are you sure you want to update this room?')) {
        return;
    }
    
    // Get the button that was clicked
    const btn = event.target;
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
    btn.disabled = true;
    
    $.ajax({
        url: apiBaseUrl + 'update-room-status.php',
        method: 'POST',
        data: {
            room_id: roomId,
            field: field,
            value: value,
            csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ''; ?>'
        },
        dataType: 'json',
        timeout: 10000,
        success: function(response) {
            if (response && response.status === 'success') {
                $('#roomOptionsModal').modal('hide');
                // Show success message
                alert('Room status updated successfully');
                location.reload();
            } else {
                alert('Failed to update room status: ' + (response.message || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            console.error('Update error:', error);
            alert('Failed to update room status. Please try again.\nError: ' + error);
        },
        complete: function() {
            btn.innerHTML = originalText;
            btn.disabled = false;
        }
    });
}

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';
        default: return 'secondary';
    }
}

function capitalize(str) {
    if (!str) return '';
    return str.charAt(0).toUpperCase() + str.slice(1);
}

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

// Initialize tooltips if Bootstrap is loaded
$(document).ready(function() {
    if (typeof $('[data-toggle="tooltip"]').tooltip === 'function') {
        $('[data-toggle="tooltip"]').tooltip();
    }
});
</script>

<style>
.room-status-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 15px;
}

.room-status-card {
    background: #fff;
    border: 2px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    position: relative;
}

.room-status-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.room-status-card.status-available {
    border-left-color: #28a745;
    border-left-width: 4px;
}

.room-status-card.status-occupied {
    border-left-color: #dc3545;
    border-left-width: 4px;
}

.room-status-card.status-maintenance {
    border-left-color: #ffc107;
    border-left-width: 4px;
}

.room-status-card.status-housekeeping {
    border-left-color: #17a2b8;
    border-left-width: 4px;
}

.room-status-card.hk-clean {
    border-bottom-color: #28a745;
    border-bottom-width: 2px;
}

.room-status-card.hk-dirty {
    border-bottom-color: #ffc107;
    border-bottom-width: 2px;
}

.room-status-card.hk-inspected {
    border-bottom-color: #17a2b8;
    border-bottom-width: 2px;
}

.room-status-card.hk-out_of_service {
    border-bottom-color: #6c757d;
    border-bottom-width: 2px;
}

.room-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}

.room-number {
    font-size: 1.3rem;
    font-weight: 600;
}

.guest-indicator {
    color: #dc3545;
    font-size: 1rem;
}

.room-type {
    color: #6c757d;
    margin-bottom: 10px;
    font-size: 0.9rem;
}

.status-badges {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    margin-bottom: 10px;
}

.task-indicator {
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px dashed #dee2e6;
    font-size: 0.85rem;
}

.guest-info {
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid #dee2e6;
    font-size: 0.85rem;
}

.badge {
    display: inline-block;
    padding: 0.25em 0.4em;
    font-size: 75%;
    font-weight: 700;
    line-height: 1;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 0.25rem;
}

.badge-success {
    background-color: #28a745;
    color: #fff;
}

.badge-warning {
    background-color: #ffc107;
    color: #212529;
}

.badge-danger {
    background-color: #dc3545;
    color: #fff;
}

.badge-info {
    background-color: #17a2b8;
    color: #fff;
}

.badge-secondary {
    background-color: #6c757d;
    color: #fff;
}

.mr-1 { margin-right: 0.25rem; }
.mr-2 { margin-right: 0.5rem; }
.ml-auto { margin-left: auto; }
.mb-1 { margin-bottom: 0.25rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.text-center { text-align: center; }
.text-muted { color: #6c757d; }
.w-100 { width: 100%; }

.btn-group-vertical {
    display: flex;
    flex-direction: column;
}

.btn-group-vertical .btn {
    border-radius: 0;
}

.btn-group-vertical .btn:first-child {
    border-top-left-radius: 0.25rem;
    border-top-right-radius: 0.25rem;
}

.btn-group-vertical .btn:last-child {
    border-bottom-left-radius: 0.25rem;
    border-bottom-right-radius: 0.25rem;
}
</style>

<?php
// Include footer - check multiple possible locations
$footer_paths = [
    $base_path . '/views/partials/footer.php',
    $base_path . '/includes/footer.php'
];

$footer_found = false;
foreach ($footer_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $footer_found = true;
        break;
    }
}

if (!$footer_found) {
    echo '</div></div></body></html>';
}
?>