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

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

// Load the universal initializer (go up one level from /frontdesk/ to root)
require_once dirname(__DIR__) . '/config/init.php';

// Require authentication
require_auth();

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

// Define time_ago function if it doesn't exist
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) {
            return $diff . ' seconds ago';
        } elseif ($diff < 3600) {
            $mins = floor($diff / 60);
            return $mins . ' minute' . ($mins > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 86400) {
            $hours = floor($diff / 3600);
            return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 2592000) {
            $days = floor($diff / 86400);
            return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
        } else {
            return date('M d, Y', $time);
        }
    }
}

// Define get_room_availability function if it doesn't exist
if (!function_exists('get_room_availability')) {
    function get_room_availability($check_in, $check_out) {
        try {
            return db_fetch_all("
                SELECT r.*, rt.type_name, rt.base_price
                FROM rooms r
                JOIN room_types rt ON r.room_type_id = rt.room_type_id
                WHERE r.is_active = 1
                AND r.status = 'available'
                AND r.room_id NOT IN (
                    SELECT room_id 
                    FROM reservations 
                    WHERE booking_status IN ('confirmed', 'checked_in')
                    AND check_in_date < ?
                    AND check_out_date > ?
                    AND room_id IS NOT NULL
                )
                ORDER BY rt.base_price, r.room_number
            ", [$check_out, $check_in]) ?: [];
        } catch (Exception $e) {
            error_log("Error getting room availability: " . $e->getMessage());
            return [];
        }
    }
}

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

// Set page title
$page_title = 'Front Desk Dashboard';

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

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

// Initialize stats array
$stats = [
    'arrivals_today' => 0,
    'departures_today' => 0,
    'occupied_rooms' => 0,
    'available_rooms' => 0,
    'total_rooms' => 1,
    'inhouse_guests' => 0,
    'revenue_today' => 0,
    'outstanding_balance' => 0,
    'occupancy_rate' => 0
];

// Get dashboard statistics with error handling
try {
    // Today's arrivals
    $stats['arrivals_today'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM reservations 
        WHERE check_in_date = ? 
        AND booking_status IN ('confirmed', 'pending')
    ", [$today]) ?: 0;
    
    // Today's departures
    $stats['departures_today'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM reservations 
        WHERE check_out_date = ? 
        AND booking_status = 'checked_in'
    ", [$today]) ?: 0;
    
    // Current occupancy
    $stats['occupied_rooms'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM rooms WHERE status = 'occupied'
    ") ?: 0;
    
    // Available rooms
    $stats['available_rooms'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM rooms WHERE status = 'available'
    ") ?: 0;
    
    // Total rooms
    $stats['total_rooms'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM rooms WHERE is_active = 1
    ") ?: 1;
    
    // In-house guests
    $stats['inhouse_guests'] = (int)db_fetch_value("
        SELECT COUNT(DISTINCT guest_id) FROM reservations 
        WHERE booking_status = 'checked_in'
    ") ?: 0;
    
    // Today's revenue
    $stats['revenue_today'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
        WHERE DATE(posted_at) = CURDATE() 
        AND charge_type != 'payment'
        AND is_voided = 0
    ") ?: 0;
    
    // Outstanding balance
    $stats['outstanding_balance'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount - paid_amount), 0) 
        FROM reservations 
        WHERE booking_status IN ('confirmed', 'checked_in')
    ") ?: 0;
    
} catch (Exception $e) {
    error_log("Error fetching stats: " . $e->getMessage());
}

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

// Get today's arrivals with details
$arrivals = [];
try {
    $arrivals = db_fetch_all("
        SELECT r.*, 
               g.first_name, g.last_name, g.email, g.phone,
               rt.type_name
        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
        WHERE r.check_in_date = ?
        AND r.booking_status IN ('confirmed', 'pending')
        ORDER BY r.created_at
    ", [$today]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching arrivals: " . $e->getMessage());
}

// Get today's departures
$departures = [];
try {
    $departures = db_fetch_all("
        SELECT r.*, 
               g.first_name, g.last_name, g.email, g.phone,
               rm.room_number
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        LEFT JOIN rooms rm ON r.room_id = rm.room_id
        WHERE r.check_out_date = ?
        AND r.booking_status = 'checked_in'
        ORDER BY g.first_name
    ", [$today]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching departures: " . $e->getMessage());
}

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

// Get recent activities
$recent_activities = [];
try {
    $recent_activities = db_fetch_all("
        (SELECT 'checkin' as type, 
                CONCAT(g.first_name, ' ', g.last_name) as guest,
                r.booking_code as reference,
                r.updated_at as created_at
         FROM reservations r
         JOIN guests g ON r.guest_id = g.guest_id
         WHERE r.booking_status = 'checked_in'
         ORDER BY r.updated_at DESC LIMIT 10)
        UNION ALL
        (SELECT 'reservation' as type,
                CONCAT(g.first_name, ' ', g.last_name) as guest,
                r.booking_code as reference,
                r.created_at
         FROM reservations r
         JOIN guests g ON r.guest_id = g.guest_id
         ORDER BY r.created_at DESC LIMIT 10)
        ORDER BY created_at DESC
        LIMIT 15
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching activities: " . $e->getMessage());
}

// Get upcoming reservations (next 7 days)
$upcoming = [];
try {
    $upcoming = db_fetch_all("
        SELECT r.*, 
               g.first_name, g.last_name,
               rt.type_name
        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
        WHERE r.check_in_date BETWEEN ? AND ?
        AND r.booking_status IN ('confirmed', 'pending')
        ORDER BY r.check_in_date
        LIMIT 10
    ", [$today, date('Y-m-d', strtotime('+7 days'))]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching upcoming: " . $e->getMessage());
}

// Get walk-in availability for today
$available_rooms = [];
try {
    $available_rooms = get_room_availability($today, $tomorrow);
} catch (Exception $e) {
    error_log("Error fetching available rooms: " . $e->getMessage());
}

// Get room types for quick check-in modal
$room_types = [];
try {
    $room_types = db_fetch_all("SELECT * FROM room_types ORDER BY type_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
}

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

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

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Quick Actions Row -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <a href="/HMSPOS/reservations/reservations/create.php" class="btn btn-primary mr-2 mb-2">
                            <i class="fas fa-plus-circle mr-1"></i> New Reservation
                        </a>
                        <a href="/HMSPOS/reservations/checkin/index.php" class="btn btn-success mr-2 mb-2">
                            <i class="fas fa-sign-in-alt mr-1"></i> Check-In
                        </a>
                        <a href="/HMSPOS/reservations/checkout/index.php" class="btn btn-warning mr-2 mb-2">
                            <i class="fas fa-sign-out-alt mr-1"></i> Check-Out
                        </a>
                        <a href="/HMSPOS/guests/guests/create.php" class="btn btn-info mr-2 mb-2">
                            <i class="fas fa-user-plus mr-1"></i> New Guest
                        </a>
                        <a href="/HMSPOS/rooms/availability/calendar.php" class="btn btn-secondary mr-2 mb-2">
                            <i class="fas fa-calendar-alt mr-1"></i> Availability Calendar
                        </a>
                        <button type="button" class="btn btn-dark mb-2" onclick="quickCheckIn()">
                            <i class="fas fa-bolt mr-1"></i> Quick Walk-In
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Info Boxes -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['arrivals_today']; ?></h3>
                        <p>Arrivals Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                    <a href="#arrivals" class="small-box-footer">
                        View Details <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['departures_today']; ?></h3>
                        <p>Departures Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-times"></i>
                    </div>
                    <a href="#departures" class="small-box-footer">
                        View Details <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['occupied_rooms']; ?> / <?php echo $stats['total_rooms']; ?></h3>
                        <p>Occupancy (<?php echo $stats['occupancy_rate']; ?>%)</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-bed"></i>
                    </div>
                    <a href="/HMSPOS/rooms/rooms/index.php" class="small-box-footer">
                        View Rooms <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo function_exists('format_currency') ? format_currency($stats['outstanding_balance']) : 'RWF ' . number_format($stats['outstanding_balance']); ?></h3>
                        <p>Outstanding Balance</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <a href="/HMSPOS/billing/debtor/index.php" class="small-box-footer">
                        View Debtors <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </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-user-friends"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">In-House Guests</span>
                        <span class="info-box-number"><?php echo $stats['inhouse_guests']; ?></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-door-open"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Available Rooms</span>
                        <span class="info-box-number"><?php echo $stats['available_rooms']; ?></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-dollar-sign"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Today's Revenue</span>
                        <span class="info-box-number"><?php echo function_exists('format_currency') ? format_currency($stats['revenue_today']) : 'RWF ' . number_format($stats['revenue_today']); ?></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-chart-line"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Avg. Daily Rate</span>
                        <span class="info-box-number">
                            <?php 
                            $avg_rate = $stats['occupied_rooms'] > 0 
                                ? $stats['revenue_today'] / $stats['occupied_rooms'] 
                                : 0;
                            echo function_exists('format_currency') ? format_currency($avg_rate) : 'RWF ' . number_format($avg_rate);
                            ?>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Today's Arrivals -->
            <div class="col-md-6">
                <div class="card card-primary card-outline" id="arrivals">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-in-alt mr-1"></i>
                            Today's Arrivals (<?php echo count($arrivals); ?>)
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/reservations/checkin/index.php" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($arrivals)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar-check fa-3x mb-3"></i>
                                <p>No arrivals scheduled for today</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Room Type</th>
                                            <th>Booking Code</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($arrivals as $arrival): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars(($arrival['first_name'] ?? '') . ' ' . ($arrival['last_name'] ?? '')); ?></strong>
                                                <br>
                                                <small class="text-muted"><?php echo htmlspecialchars($arrival['phone'] ?? ''); ?></small>
                                            </td>
                                            <td><?php echo htmlspecialchars($arrival['type_name'] ?? ''); ?></td>
                                            <td>
                                                <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $arrival['reservation_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($arrival['booking_code'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo ($arrival['booking_status'] ?? '') == 'confirmed' ? 'success' : 'warning'; ?>">
                                                    <?php echo ucfirst($arrival['booking_status'] ?? 'pending'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/reservations/checkin/start.php?id=<?php echo $arrival['reservation_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-sign-in-alt"></i> Check-In
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Today's Departures -->
            <div class="col-md-6">
                <div class="card card-warning card-outline" id="departures">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-out-alt mr-1"></i>
                            Today's Departures (<?php echo count($departures); ?>)
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/reservations/checkout/index.php" class="btn btn-sm btn-warning">
                                View All
                            </a>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($departures)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar-times fa-3x mb-3"></i>
                                <p>No departures scheduled for today</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Room</th>
                                            <th>Booking Code</th>
                                            <th>Balance</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($departures as $departure): ?>
                                        <?php 
                                        $balance = ($departure['total_amount'] ?? 0) - ($departure['paid_amount'] ?? 0);
                                        ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars(($departure['first_name'] ?? '') . ' ' . ($departure['last_name'] ?? '')); ?></strong>
                                            </td>
                                            <td>
                                                <span class="badge bg-info">Room <?php echo htmlspecialchars($departure['room_number'] ?? 'N/A'); ?></span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $departure['reservation_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($departure['booking_code'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $balance > 0 ? 'danger' : 'success'; ?>">
                                                    <?php echo function_exists('format_currency') ? format_currency($balance) : 'RWF ' . number_format($balance); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/reservations/checkout/start.php?id=<?php echo $departure['reservation_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning">
                                                    <i class="fas fa-sign-out-alt"></i> Check-Out
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Room Status -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-door-open mr-1"></i>
                            Room Status
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="roomStatusChart" style="height: 250px;"></canvas>
                        
                        <div class="mt-4">
                            <?php 
                            $status_colors = [
                                'available' => '#28a745',
                                'occupied' => '#dc3545',
                                'maintenance' => '#ffc107',
                                'housekeeping' => '#17a2b8',
                                'blocked' => '#6c757d'
                            ];
                            
                            foreach ($room_status as $status):
                                $color = $status_colors[$status['status'] ?? ''] ?? '#6c757d';
                            ?>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span>
                                    <i class="fas fa-circle mr-2" style="color: <?php echo $color; ?>"></i>
                                    <?php echo ucfirst($status['status'] ?? 'unknown'); ?>
                                </span>
                                <span class="badge bg-secondary"><?php echo $status['count'] ?? 0; ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="card-footer text-center">
                        <a href="/HMSPOS/rooms/rooms/index.php">View All Rooms</a>
                    </div>
                </div>
            </div>

            <!-- Available for Walk-in -->
            <div class="col-md-4">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-door-open mr-1"></i>
                            Available for Walk-in Today
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($available_rooms)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-bed fa-3x mb-3"></i>
                                <p>No rooms available for walk-in today</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Room</th>
                                            <th>Type</th>
                                            <th>Price</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach (array_slice($available_rooms, 0, 8) as $room): ?>
                                        <tr>
                                            <td><strong><?php echo htmlspecialchars($room['room_number'] ?? ''); ?></strong></td>
                                            <td><?php echo htmlspecialchars($room['type_name'] ?? ''); ?></td>
                                            <td><?php echo function_exists('format_currency') ? format_currency($room['base_price'] ?? 0) : 'RWF ' . number_format($room['base_price'] ?? 0); ?></td>
                                            <td>
                                                <a href="/HMSPOS/reservations/reservations/create.php?room_id=<?php echo $room['room_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-plus"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php if (count($available_rooms) > 8): ?>
                                <div class="text-center text-muted p-2">
                                    <small>and <?php echo count($available_rooms) - 8; ?> more...</small>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Recent Activity -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history mr-1"></i>
                            Recent Activity
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($recent_activities)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-history fa-3x mb-3"></i>
                                <p>No recent activity</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($recent_activities as $activity): ?>
                                <div class="list-group-item">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">
                                            <?php 
                                            $icon = ($activity['type'] ?? '') == 'checkin' ? 'fa-sign-in-alt text-success' : 'fa-calendar-plus text-primary';
                                            ?>
                                            <i class="fas <?php echo $icon; ?> mr-2"></i>
                                            <strong><?php echo ucfirst($activity['type'] ?? 'event'); ?></strong>
                                        </h6>
                                        <small class="text-muted">
                                            <?php echo function_exists('time_ago') ? time_ago($activity['created_at'] ?? date('Y-m-d H:i:s')) : ''; ?>
                                        </small>
                                    </div>
                                    <p class="mb-1"><?php echo htmlspecialchars($activity['guest'] ?? ''); ?></p>
                                    <small class="text-muted">Ref: <?php echo htmlspecialchars($activity['reference'] ?? ''); ?></small>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Upcoming Reservations -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-calendar-alt mr-1"></i>
                            Upcoming Reservations (Next 7 Days)
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/reservations/reservations/index.php" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($upcoming)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar fa-3x mb-3"></i>
                                <p>No upcoming reservations</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Check-in</th>
                                            <th>Guest</th>
                                            <th>Room Type</th>
                                            <th>Booking Code</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($upcoming as $res): ?>
                                        <tr>
                                            <td><?php echo function_exists('format_date') ? format_date($res['check_in_date'] ?? '') : ($res['check_in_date'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars(($res['first_name'] ?? '') . ' ' . ($res['last_name'] ?? '')); ?></td>
                                            <td><?php echo htmlspecialchars($res['type_name'] ?? ''); ?></td>
                                            <td>
                                                <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $res['reservation_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($res['booking_code'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo ($res['booking_status'] ?? '') == 'confirmed' ? 'success' : 'warning'; ?>">
                                                    <?php echo ucfirst($res['booking_status'] ?? 'pending'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/reservations/reservations/edit.php?id=<?php echo $res['reservation_id'] ?? 0; ?>" 
                                                   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>
        </div>
    </div>
</section>

<!-- Quick Check-in Modal -->
<div class="modal fade" id="quickCheckinModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success">
                <h5 class="modal-title">Quick Walk-in Check-in</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="/HMSPOS/reservations/checkin/quick.php" method="POST">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php endif; ?>
                <div class="modal-body">
                    <div class="form-group mb-3">
                        <label>Guest Name</label>
                        <input type="text" class="form-control" name="guest_name" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Phone Number</label>
                        <input type="tel" class="form-control" name="phone" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Email</label>
                        <input type="email" class="form-control" name="email">
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Room Type</label>
                        <select class="form-control" name="room_type_id" required>
                            <option value="">Select Room Type</option>
                            <?php foreach ($room_types as $type): ?>
                                <option value="<?php echo $type['room_type_id'] ?? 0; ?>">
                                    <?php echo htmlspecialchars($type['type_name'] ?? ''); ?> - 
                                    <?php echo function_exists('format_currency') ? format_currency($type['base_price'] ?? 0) : 'RWF ' . number_format($type['base_price'] ?? 0); ?>/night
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Nights</label>
                        <input type="number" class="form-control" name="nights" value="1" min="1" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Adults</label>
                        <input type="number" class="form-control" name="adults" value="2" min="1" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Children</label>
                        <input type="number" class="form-control" name="children" value="0" min="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Process Check-in</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
$(document).ready(function() {
    // Room Status Chart
    const ctx = document.getElementById('roomStatusChart').getContext('2d');
    
    <?php
    $chart_labels = [];
    $chart_data = [];
    $chart_colors = [];
    
    foreach ($room_status as $status) {
        $chart_labels[] = ucfirst($status['status'] ?? 'unknown');
        $chart_data[] = $status['count'] ?? 0;
        
        switch($status['status'] ?? '') {
            case 'available':
                $chart_colors[] = '#28a745';
                break;
            case 'occupied':
                $chart_colors[] = '#dc3545';
                break;
            case 'maintenance':
                $chart_colors[] = '#ffc107';
                break;
            case 'housekeeping':
                $chart_colors[] = '#17a2b8';
                break;
            default:
                $chart_colors[] = '#6c757d';
        }
    }
    ?>
    
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode($chart_labels); ?>,
            datasets: [{
                data: <?php echo json_encode($chart_data); ?>,
                backgroundColor: <?php echo json_encode($chart_colors); ?>,
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
});

function quickCheckIn() {
    const modal = new bootstrap.Modal(document.getElementById('quickCheckinModal'));
    modal.show();
}
</script>

<style>
.mr-1 { margin-right: 0.25rem; }
.mr-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mb-4 { margin-bottom: 1.5rem; }
.mt-4 { margin-top: 1.5rem; }
.text-right { text-align: right; }
.table-responsive { overflow-x: auto; }
</style>

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