<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Housekeeping Dashboard - 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;

// Method 1: Try going up 2 levels from current file
// Current file: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/housekeeping/dashboard.php
$base_path = dirname(__DIR__, 2);

// Method 2: Manual calculation if method 1 fails
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = 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';
}

// Verify the base path works
if (!file_exists($base_path . '/config/config.php')) {
    die("Error: Cannot find system files at: " . $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 '';
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token() {
        return '';
    }
}

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('truncate_text')) {
    function truncate_text($text, $length = 50) {
        if (strlen($text) <= $length) {
            return $text;
        }
        return substr($text, 0, $length) . '...';
    }
}

// Require authentication and permission
require_auth();

// Check if permission function exists
if (function_exists('require_permission')) {
    require_permission('dashboard.housekeeping');
}

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

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

// Initialize stats with default values
$stats = [
    'clean_rooms' => 0,
    'dirty_rooms' => 0,
    'inspected_rooms' => 0,
    'out_of_service' => 0,
    'total_tasks' => 0,
    'pending_tasks' => 0,
    'assigned_tasks' => 0,
    'in_progress_tasks' => 0,
    'completed_today' => 0,
    'open_tickets' => 0,
    'urgent_tickets' => 0,
    'resolved_today' => 0,
    'active_staff' => 0,
    'avg_completion_time' => 0,
    'completion_rate' => 0
];

// Get housekeeping statistics with error handling
try {
    // Check if rooms table exists
    $tables_exist = db_fetch_value("SHOW TABLES LIKE 'rooms'");
    
    if ($tables_exist) {
        $stats['clean_rooms'] = (int)(db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'clean'") ?: 0);
        $stats['dirty_rooms'] = (int)(db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'dirty'") ?: 0);
        $stats['inspected_rooms'] = (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);
    }
    
    // Check if hk_tasks table exists
    $tasks_exist = db_fetch_value("SHOW TABLES LIKE 'hk_tasks'");
    
    if ($tasks_exist) {
        $stats['total_tasks'] = (int)(db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE DATE(created_at) = CURDATE()") ?: 0);
        $stats['pending_tasks'] = (int)(db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE status = 'pending'") ?: 0);
        $stats['assigned_tasks'] = (int)(db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE status = 'assigned'") ?: 0);
        $stats['in_progress_tasks'] = (int)(db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE status = 'in_progress'") ?: 0);
        $stats['completed_today'] = (int)(db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE status = 'completed' AND DATE(completed_at) = CURDATE()") ?: 0);
    }
    
    // Check if maintenance_tickets table exists
    $maintenance_exist = db_fetch_value("SHOW TABLES LIKE 'maintenance_tickets'");
    
    if ($maintenance_exist) {
        $stats['open_tickets'] = (int)(db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE status IN ('open', 'assigned', 'in_progress')") ?: 0);
        $stats['urgent_tickets'] = (int)(db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE priority = 'urgent' AND status != 'resolved'") ?: 0);
        $stats['resolved_today'] = (int)(db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE DATE(resolved_at) = CURDATE()") ?: 0);
    }
    
    // Staff performance
    if ($tasks_exist) {
        $stats['active_staff'] = (int)(db_fetch_value("SELECT COUNT(DISTINCT assigned_to) FROM hk_tasks WHERE status IN ('assigned', 'in_progress')") ?: 0);
        
        $avg_time = db_fetch_value("
            SELECT AVG(TIMESTAMPDIFF(MINUTE, assigned_at, completed_at)) 
            FROM hk_tasks 
            WHERE status = 'completed' 
            AND completed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        ");
        $stats['avg_completion_time'] = $avg_time ? round($avg_time) : 0;
    }
    
} catch (Exception $e) {
    error_log("Error in housekeeping stats: " . $e->getMessage());
}

// Calculate efficiency metrics
$stats['completion_rate'] = $stats['total_tasks'] > 0 
    ? round(($stats['completed_today'] / $stats['total_tasks']) * 100, 1) 
    : 0;

// Initialize empty arrays for data
$pending_tasks = [];
$floor_status = [];
$maintenance_tickets = [];
$staff_workload = [];
$attention_rooms = [];
$vip_arrivals = [];
$completion_trend = ['labels' => [], 'completed' => [], 'created' => []];

// Get pending tasks with error handling
try {
    if ($tasks_exist) {
        $pending_tasks = db_fetch_all("
            SELECT 
                t.*,
                r.room_number,
                rt.type_name as room_type,
                u.first_name as assigned_first, u.last_name as assigned_last,
                cr.first_name as created_first, cr.last_name as created_last
            FROM hk_tasks t
            JOIN rooms r ON t.room_id = r.room_id
            JOIN room_types rt ON r.room_type_id = rt.room_type_id
            LEFT JOIN users u ON t.assigned_to = u.user_id
            LEFT JOIN users cr ON t.created_by = cr.user_id
            WHERE t.status IN ('pending', 'assigned', 'in_progress')
            ORDER BY 
                CASE t.priority 
                    WHEN 'urgent' THEN 1
                    WHEN 'high' THEN 2
                    WHEN 'medium' THEN 3
                    WHEN 'low' THEN 4
                END,
                t.created_at ASC
            LIMIT 20
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting pending tasks: " . $e->getMessage());
}

// Get room status by floor with error handling
try {
    if ($tables_exist) {
        $floor_status = db_fetch_all("
            SELECT 
                r.floor,
                COUNT(*) as total,
                SUM(CASE WHEN r.housekeeping_status = 'clean' THEN 1 ELSE 0 END) as clean,
                SUM(CASE WHEN r.housekeeping_status = 'dirty' THEN 1 ELSE 0 END) as dirty,
                SUM(CASE WHEN r.housekeeping_status = 'inspected' THEN 1 ELSE 0 END) as inspected,
                SUM(CASE WHEN r.housekeeping_status = 'out_of_service' THEN 1 ELSE 0 END) as out_of_service
            FROM rooms r
            WHERE r.is_active = 1 AND r.floor IS NOT NULL
            GROUP BY r.floor
            ORDER BY r.floor
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting floor status: " . $e->getMessage());
}

// Get open maintenance tickets with error handling
try {
    if ($maintenance_exist) {
        $maintenance_tickets = db_fetch_all("
            SELECT 
                m.*,
                r.room_number,
                u.first_name as reported_first, u.last_name as reported_last,
                a.first_name as assigned_first, a.last_name as assigned_last
            FROM maintenance_tickets m
            LEFT JOIN rooms r ON m.room_id = r.room_id
            LEFT JOIN users u ON m.reported_by = u.user_id
            LEFT JOIN users a ON m.assigned_to = a.user_id
            WHERE m.status IN ('open', 'assigned', 'in_progress')
            ORDER BY 
                CASE m.priority 
                    WHEN 'urgent' THEN 1
                    WHEN 'high' THEN 2
                    WHEN 'medium' THEN 3
                    WHEN 'low' THEN 4
                END,
                m.created_at ASC
            LIMIT 15
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting maintenance tickets: " . $e->getMessage());
}

// Get staff workload with error handling
try {
    if ($tasks_exist) {
        $staff_workload = db_fetch_all("
            SELECT 
                u.user_id, u.first_name, u.last_name,
                COUNT(t.task_id) as assigned_tasks,
                SUM(CASE WHEN t.status = 'completed' AND DATE(t.completed_at) = CURDATE() THEN 1 ELSE 0 END) as completed_today,
                AVG(CASE WHEN t.status = 'completed' THEN TIMESTAMPDIFF(MINUTE, t.assigned_at, t.completed_at) ELSE NULL END) as avg_time
            FROM users u
            LEFT JOIN hk_tasks t ON u.user_id = t.assigned_to AND DATE(t.created_at) = CURDATE()
            WHERE u.role_id IN (7, 8) -- Housekeeping roles
            GROUP BY u.user_id
            ORDER BY assigned_tasks DESC
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting staff workload: " . $e->getMessage());
}

// Get rooms needing attention with error handling
try {
    if ($tables_exist) {
        $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'
                    WHEN r.status = 'housekeeping' THEN 'Housekeeping in Progress'
                END as reason,
                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.status = 'maintenance' 
               OR r.housekeeping_status IN ('dirty', 'out_of_service')
               OR r.status = 'housekeeping'
            ORDER BY 
                CASE 
                    WHEN r.status = 'maintenance' THEN 1
                    WHEN r.housekeeping_status = 'dirty' THEN 2
                    WHEN r.housekeeping_status = 'out_of_service' THEN 3
                    ELSE 4
                END,
                r.room_number
            LIMIT 20
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting attention rooms: " . $e->getMessage());
}

// Get upcoming VIP arrivals with error handling
try {
    $vip_arrivals = db_fetch_all("
        SELECT 
            r.*,
            g.first_name, g.last_name,
            rt.type_name,
            rm.room_number
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        LEFT JOIN rooms rm ON r.room_id = rm.room_id
        WHERE r.check_in_date = CURDATE()
        AND r.booking_status = 'confirmed'
        AND (r.special_requests LIKE '%VIP%' OR r.special_requests LIKE '%vip%')
        ORDER BY r.check_in_date
    ") ?: [];
} catch (Exception $e) {
    error_log("Error getting VIP arrivals: " . $e->getMessage());
}

// Get task completion trend (last 7 days) with error handling
try {
    if ($tasks_exist) {
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $completion_trend['labels'][] = date('D', strtotime($date));
            
            $completed = (int)(db_fetch_value("
                SELECT COUNT(*) FROM hk_tasks 
                WHERE DATE(completed_at) = ? 
                AND status = 'completed'
            ", [$date]) ?: 0);
            
            $created = (int)(db_fetch_value("
                SELECT COUNT(*) FROM hk_tasks 
                WHERE DATE(created_at) = ?
            ", [$date]) ?: 0);
            
            $completion_trend['completed'][] = $completed;
            $completion_trend['created'][] = $created;
        }
    }
} catch (Exception $e) {
    error_log("Error getting completion trend: " . $e->getMessage());
}

// Get rooms for quick select
$rooms = [];
try {
    if ($tables_exist) {
        $rooms = db_fetch_all("
            SELECT r.room_id, r.room_number, r.housekeeping_status 
            FROM rooms r 
            WHERE r.is_active = 1 
            ORDER BY r.room_number
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error getting rooms: " . $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>Housekeeping 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; 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); }
            .info-box { box-shadow: 0 0 1px rgba(0,0,0,0.125), 0 1px 3px rgba(0,0,0,0.2); border-radius: 0.5rem; background: #fff; display: flex; align-items: stretch; margin-bottom: 15px; min-height: 90px; }
            .info-box-icon { border-radius: 0.5rem 0 0 0.5rem; display: flex; align-items: center; justify-content: center; width: 90px; font-size: 2.5rem; }
            .info-box-content { padding: 10px; flex: 1; }
            .bg-primary { background-color: #007bff !important; color: #fff; }
            .bg-success { background-color: #28a745 !important; color: #fff; }
            .bg-info { background-color: #17a2b8 !important; color: #fff; }
            .bg-warning { background-color: #ffc107 !important; color: #1f2d3d; }
            .bg-danger { background-color: #dc3545 !important; color: #fff; }
            .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">Housekeeping Dashboard</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 active">Housekeeping 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="<?php echo base_url('housekeeping/tasks/create.php'); ?>" class="btn btn-primary mr-2 mb-2">
                            <i class="fas fa-plus-circle mr-1"></i> New Task
                        </a>
                        <a href="<?php echo base_url('housekeeping/tasks/assign.php'); ?>" class="btn btn-info mr-2 mb-2">
                            <i class="fas fa-user-plus mr-1"></i> Assign Tasks
                        </a>
                        <a href="<?php echo base_url('housekeeping/cleaning/schedule.php'); ?>" class="btn btn-success mr-2 mb-2">
                            <i class="fas fa-calendar-alt mr-1"></i> Cleaning Schedule
                        </a>
                        <a href="<?php echo base_url('housekeeping/cleaning/room-status.php'); ?>" class="btn btn-warning mr-2 mb-2">
                            <i class="fas fa-door-open mr-1"></i> Room Status
                        </a>
                        <a href="<?php echo base_url('housekeeping/maintenance/create.php'); ?>" class="btn btn-danger mr-2 mb-2">
                            <i class="fas fa-tools mr-1"></i> Report Issue
                        </a>
                        <a href="<?php echo base_url('housekeeping/maintenance/tickets.php'); ?>" class="btn btn-secondary mr-2 mb-2">
                            <i class="fas fa-clipboard-list mr-1"></i> Maintenance Tickets
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- VIP Alert -->
        <?php if (!empty($vip_arrivals)): ?>
        <div class="alert alert-warning">
            <i class="fas fa-crown mr-2"></i>
            <strong>VIP Arrivals Today:</strong>
            <?php foreach ($vip_arrivals as $vip): ?>
                <?php echo escape_html($vip['first_name'] . ' ' . $vip['last_name']); ?> 
                (Room <?php echo $vip['room_number'] ?: 'TBA'; ?>) - 
            <?php endforeach; ?>
            <a href="<?php echo base_url('housekeeping/tasks/create.php?type=vip'); ?>" class="alert-link">Prepare VIP rooms</a>
        </div>
        <?php endif; ?>

        <!-- 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['clean_rooms']; ?></h3>
                        <p>Clean Rooms</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['dirty_rooms']; ?></h3>
                        <p>Dirty Rooms</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-broom"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['open_tickets']; ?></h3>
                        <p>Open Maintenance</p>
                        <?php if ($stats['urgent_tickets'] > 0): ?>
                            <small><?php echo $stats['urgent_tickets']; ?> urgent</small>
                        <?php endif; ?>
                    </div>
                    <div class="icon">
                        <i class="fas fa-tools"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['completed_today']; ?>/<?php echo $stats['total_tasks']; ?></h3>
                        <p>Tasks Completed</p>
                        <small><?php echo $stats['completion_rate']; ?>% rate</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clipboard-check"></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-clock"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Avg. Cleaning Time</span>
                        <span class="info-box-number"><?php echo round($stats['avg_completion_time']); ?> min</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-user-check"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Active Staff</span>
                        <span class="info-box-number"><?php echo $stats['active_staff']; ?></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-hourglass-half"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Pending Tasks</span>
                        <span class="info-box-number"><?php echo $stats['pending_tasks']; ?></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-check-double"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Inspected Rooms</span>
                        <span class="info-box-number"><?php echo $stats['inspected_rooms']; ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chart Row -->
        <?php if (!empty($completion_trend['labels'])): ?>
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            Task Completion Trend (Last 7 Days)
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="taskChart" style="height: 300px;"></canvas>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-layer-group mr-1"></i>
                            Room Status by Floor
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($floor_status)): ?>
                            <div class="text-center text-muted py-4">
                                <p>No floor data available</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Floor</th>
                                            <th class="text-center">Clean</th>
                                            <th class="text-center">Dirty</th>
                                            <th class="text-center">Inspected</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($floor_status as $floor): ?>
                                        <tr>
                                            <td><strong>Floor <?php echo $floor['floor']; ?></strong></td>
                                            <td class="text-center">
                                                <span class="badge badge-success"><?php echo $floor['clean']; ?></span>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge badge-warning"><?php echo $floor['dirty']; ?></span>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge badge-info"><?php echo $floor['inspected']; ?></span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="row">
            <!-- Pending Tasks -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-tasks mr-1"></i>
                            Pending Tasks
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('housekeeping/tasks/index.php'); ?>" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($pending_tasks)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                <p>No pending tasks</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Priority</th>
                                            <th>Room</th>
                                            <th>Task</th>
                                            <th>Assigned To</th>
                                            <th>Status</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($pending_tasks as $task): ?>
                                        <tr>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $task['priority'] == 'urgent' ? 'danger' : 
                                                        ($task['priority'] == 'high' ? 'warning' : 
                                                        ($task['priority'] == 'medium' ? 'info' : 'secondary'));
                                                ?>">
                                                    <?php echo ucfirst($task['priority']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <strong><?php echo $task['room_number']; ?></strong>
                                                <br>
                                                <small><?php echo $task['room_type']; ?></small>
                                            </td>
                                            <td>
                                                <?php echo ucfirst(str_replace('_', ' ', $task['task_type'])); ?>
                                                <?php if (!empty($task['notes'])): ?>
                                                    <br>
                                                    <small class="text-muted"><?php echo escape_html(truncate_text($task['notes'], 30)); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if (!empty($task['assigned_to'])): ?>
                                                    <?php echo escape_html($task['assigned_first'] . ' ' . $task['assigned_last']); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">Unassigned</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $task['status'] == 'pending' ? 'secondary' : 
                                                        ($task['status'] == 'assigned' ? 'info' : 
                                                        ($task['status'] == 'in_progress' ? 'primary' : 'success'));
                                                ?>">
                                                    <?php echo ucfirst(str_replace('_', ' ', $task['status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (empty($task['assigned_to'])): ?>
                                                    <a href="<?php echo base_url('housekeeping/tasks/assign.php?id=' . $task['task_id']); ?>" 
                                                       class="btn btn-sm btn-success">
                                                        <i class="fas fa-user-plus"></i>
                                                    </a>
                                                <?php elseif ($task['status'] != 'completed'): ?>
                                                    <a href="<?php echo base_url('housekeeping/tasks/complete.php?id=' . $task['task_id']); ?>" 
                                                       class="btn btn-sm btn-primary">
                                                        <i class="fas fa-check"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Open Maintenance Tickets -->
            <div class="col-md-6">
                <div class="card card-danger">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-tools mr-1"></i>
                            Open Maintenance Tickets
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('housekeeping/maintenance/tickets.php'); ?>" class="btn btn-sm btn-danger">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($maintenance_tickets)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                <p>No open maintenance tickets</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Priority</th>
                                            <th>Ticket</th>
                                            <th>Room</th>
                                            <th>Issue</th>
                                            <th>Reported By</th>
                                            <th>Status</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($maintenance_tickets as $ticket): ?>
                                        <tr>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $ticket['priority'] == 'urgent' ? 'danger' : 
                                                        ($ticket['priority'] == 'high' ? 'warning' : 
                                                        ($ticket['priority'] == 'medium' ? 'info' : 'secondary'));
                                                ?>">
                                                    <?php echo ucfirst($ticket['priority']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="<?php echo base_url('housekeeping/maintenance/view.php?id=' . $ticket['ticket_id']); ?>">
                                                    <?php echo $ticket['ticket_code']; ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php echo $ticket['room_number'] ?: 'Common Area'; ?>
                                            </td>
                                            <td>
                                                <?php echo escape_html(truncate_text($ticket['description'], 30)); ?>
                                            </td>
                                            <td>
                                                <small><?php echo escape_html($ticket['reported_first']); ?></small>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $ticket['status'] == 'open' ? 'secondary' : 
                                                        ($ticket['status'] == 'assigned' ? 'info' : 
                                                        ($ticket['status'] == 'in_progress' ? 'primary' : 'success'));
                                                ?>">
                                                    <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (empty($ticket['assigned_to'])): ?>
                                                    <a href="<?php echo base_url('housekeeping/maintenance/update.php?id=' . $ticket['ticket_id']); ?>" 
                                                       class="btn btn-sm btn-success">
                                                        <i class="fas fa-wrench"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Rooms Needing Attention -->
            <div class="col-md-6">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exclamation-triangle mr-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>Guest</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($attention_rooms as $room): ?>
                                        <tr>
                                            <td><strong><?php echo $room['room_number']; ?></strong></td>
                                            <td><?php echo $room['type_name']; ?></td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $room['status'] == 'maintenance' ? 'danger' : 'warning';
                                                ?>">
                                                    <?php echo $room['reason']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (!empty($room['guest_name'])): ?>
                                                    <?php echo escape_html($room['guest_name']); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">Vacant</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($room['status'] == 'maintenance'): ?>
                                                    <a href="<?php echo base_url('housekeeping/maintenance/create.php?room_id=' . $room['room_id']); ?>" 
                                                       class="btn btn-sm btn-danger">
                                                        <i class="fas fa-tools"></i>
                                                    </a>
                                                <?php elseif ($room['housekeeping_status'] == 'dirty'): ?>
                                                    <a href="<?php echo base_url('housekeeping/tasks/create.php?room_id=' . $room['room_id']); ?>" 
                                                       class="btn btn-sm btn-warning">
                                                        <i class="fas fa-broom"></i>
                                                    </a>
                                                <?php endif; ?>
                                                <a href="<?php echo base_url('rooms/rooms/status.php?id=' . $room['room_id']); ?>" 
                                                   class="btn btn-sm btn-info">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Staff Workload -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-users mr-1"></i>
                            Staff Workload
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($staff_workload)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-users fa-3x mb-3"></i>
                                <p>No housekeeping staff data</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Staff</th>
                                            <th class="text-center">Assigned</th>
                                            <th class="text-center">Completed Today</th>
                                            <th class="text-right">Avg. Time</th>
                                            <th>Workload</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($staff_workload as $staff): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape_html($staff['first_name'] . ' ' . $staff['last_name']); ?></strong>
                                            </td>
                                            <td class="text-center"><?php echo $staff['assigned_tasks']; ?></td>
                                            <td class="text-center"><?php echo $staff['completed_today']; ?></td>
                                            <td class="text-right">
                                                <?php echo $staff['avg_time'] ? round($staff['avg_time']) . ' min' : '-'; ?>
                                            </td>
                                            <td style="width: 150px;">
                                                <?php 
                                                $max_tasks = 8; // Assuming 8 tasks is full workload
                                                $percentage = min(100, ($staff['assigned_tasks'] / $max_tasks) * 100);
                                                ?>
                                                <div class="progress progress-xs">
                                                    <div class="progress-bar bg-<?php 
                                                        echo $percentage > 80 ? 'danger' : ($percentage > 50 ? 'warning' : 'success');
                                                    ?>" style="width: <?php echo $percentage; ?>%"></div>
                                                </div>
                                                <small><?php echo round($percentage); ?>% capacity</small>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Room Status Update -->
        <div class="row">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sync-alt mr-1"></i>
                            Quick Room Status Update
                        </h3>
                    </div>
                    <div class="card-body">
                        <?php if (empty($rooms)): ?>
                            <div class="alert alert-warning">No rooms available</div>
                        <?php else: ?>
                        <form class="form-inline" id="quickStatusForm">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <div class="form-group mb-2 mr-2">
                                <select class="form-control" id="quickRoomSelect" required>
                                    <option value="">Select Room</option>
                                    <?php foreach ($rooms as $room): ?>
                                        <option value="<?php echo $room['room_id']; ?>" 
                                                data-status="<?php echo $room['housekeeping_status']; ?>">
                                            Room <?php echo $room['room_number']; ?> 
                                            (Current: <?php echo $room['housekeeping_status']; ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group mb-2 mr-2">
                                <select class="form-control" id="quickStatusSelect" required>
                                    <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>
                            
                            <button type="submit" class="btn btn-primary mb-2">
                                <i class="fas fa-save mr-1"></i> Update Status
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>

<script>
$(document).ready(function() {
    <?php if (!empty($completion_trend['labels'])): ?>
    // Task Completion Chart
    const taskCtx = document.getElementById('taskChart').getContext('2d');
    
    new Chart(taskCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($completion_trend['labels']); ?>,
            datasets: [{
                label: 'Tasks Created',
                data: <?php echo json_encode($completion_trend['created']); ?>,
                borderColor: '#ffc107',
                backgroundColor: 'rgba(255, 193, 7, 0.1)',
                tension: 0.1,
                fill: true
            }, {
                label: 'Tasks Completed',
                data: <?php echo json_encode($completion_trend['completed']); ?>,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
    <?php endif; ?>
    
    // Quick status update
    $('#quickStatusForm').on('submit', function(e) {
        e.preventDefault();
        
        const roomId = $('#quickRoomSelect').val();
        const status = $('#quickStatusSelect').val();
        
        if (!roomId) {
            alert('Please select a room');
            return;
        }
        
        // Show loading
        const btn = $(this).find('button[type="submit"]');
        btn.html('<i class="fas fa-spinner fa-spin"></i> Updating...').prop('disabled', true);
        
        $.ajax({
            url: '<?php echo base_url('api/update-room-status.php'); ?>',
            method: 'POST',
            data: {
                room_id: roomId,
                housekeeping_status: status,
                csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ''; ?>'
            },
            dataType: 'json',
            success: function(response) {
                if (response && response.status === 'success') {
                    alert('Room status updated successfully');
                    location.reload();
                } else {
                    alert('Failed to update room status: ' + (response.message || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                alert('Failed to update room status: ' + error);
            },
            complete: function() {
                btn.html('<i class="fas fa-save mr-1"></i> Update Status').prop('disabled', false);
            }
        });
    });
    
    // Update room select info when changed
    $('#quickRoomSelect').on('change', function() {
        const selected = $(this).find(':selected');
        const currentStatus = selected.data('status');
        $('#quickStatusSelect').val(currentStatus || 'clean');
    });
    
    // Auto-refresh every 2 minutes
    setTimeout(function() {
        location.reload();
    }, 120000);
});
</script>

<style>
.progress-xs {
    height: 5px;
    margin-top: 5px;
}
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mr-1 { margin-right: 0.25rem; }
.mr-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-4 { margin-bottom: 1.5rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.text-center { text-align: center; }
.text-right { text-align: right; }
.text-muted { color: #6c757d; }
</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>';
}
?>