<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Executive Dashboard - COMPLETELY FIXED VERSION
 * Location: /HMSPOS/public/dashboard.php
 * Developer: JOACHIM'S INNOTECH
 */

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

// Define base path if not defined
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__DIR__));
}

// Load configuration
require_once BASE_PATH . '/config/config.php';
require_once BASE_PATH . '/config/database.php';
require_once BASE_PATH . '/config/auth.php';

// Require authentication
require_auth();

// =============================================
// HELPER FUNCTIONS (if not defined elsewhere)
// =============================================

// Define format_number function if it doesn't exist
if (!function_exists('format_number')) {
    function format_number($number, $decimals = 0) {
        return number_format($number, $decimals, '.', ',');
    }
}

// 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 escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// =============================================
// DASHBOARD-SPECIFIC FUNCTIONS
// =============================================

/**
 * Get dashboard statistics
 */
if (!function_exists('get_dashboard_stats')) {
    function get_dashboard_stats() {
        $stats = [];
        
        try {
            // Today's check-ins
            $stats['checkins_today'] = (int)db_fetch_value("
                SELECT COUNT(*) FROM reservations 
                WHERE DATE(check_in_date) = CURDATE() 
                AND booking_status IN ('confirmed', 'pending')
            ") ?: 0;
            
            // Today's check-outs
            $stats['checkouts_today'] = (int)db_fetch_value("
                SELECT COUNT(*) FROM reservations 
                WHERE DATE(check_out_date) = CURDATE() 
                AND booking_status = 'checked_in'
            ") ?: 0;
            
            // Occupied rooms
            $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;
            
            // Total reservations
            $stats['total_reservations'] = (int)db_fetch_value("
                SELECT COUNT(*) FROM reservations 
                WHERE booking_status IN ('confirmed', '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;
            
            // Monthly revenue
            $stats['revenue_month'] = (float)db_fetch_value("
                SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
                WHERE MONTH(posted_at) = MONTH(CURDATE())
                AND YEAR(posted_at) = YEAR(CURDATE())
                AND charge_type != 'payment'
                AND is_voided = 0
            ") ?: 0;
            
            // Yearly revenue
            $stats['revenue_year'] = (float)db_fetch_value("
                SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
                WHERE YEAR(posted_at) = YEAR(CURDATE())
                AND charge_type != 'payment'
                AND is_voided = 0
            ") ?: 0;
            
            // Occupancy rate
            $stats['occupancy_rate'] = $stats['total_rooms'] > 0 
                ? round(($stats['occupied_rooms'] / $stats['total_rooms']) * 100, 2) 
                : 0;
            
        } catch (Exception $e) {
            error_log("Error in get_dashboard_stats: " . $e->getMessage());
            // Set default values
            $stats = [
                'checkins_today' => 0,
                'checkouts_today' => 0,
                'occupied_rooms' => 0,
                'available_rooms' => 0,
                'total_rooms' => 1,
                'total_reservations' => 0,
                'revenue_today' => 0,
                'revenue_month' => 0,
                'revenue_year' => 0,
                'occupancy_rate' => 0
            ];
        }
        
        return $stats;
    }
}

/**
 * Get recent activities
 */
if (!function_exists('get_recent_activities')) {
    function get_recent_activities($limit = 10) {
        $limit = max(1, (int)$limit);
        
        try {
            $sql = "
                (SELECT 
                    'reservation' as type, 
                    r.booking_code as reference, 
                    CONCAT('New booking from ', g.first_name, ' ', g.last_name) as description,
                    r.created_at as activity_date
                 FROM reservations r
                 INNER JOIN guests g ON r.guest_id = g.guest_id
                 ORDER BY r.created_at DESC 
                 LIMIT :limit1)
                
                UNION ALL
                
                (SELECT 
                    'payment' as type, 
                    p.payment_number as reference,
                    CONCAT('Payment of ', FORMAT(p.amount, 0), ' received') as description,
                    p.created_at as activity_date
                 FROM payments p
                 ORDER BY p.created_at DESC 
                 LIMIT :limit2)
                
                UNION ALL
                
                (SELECT 
                    'checkin' as type, 
                    r.booking_code as reference,
                    CONCAT('Guest checked in: ', g.first_name, ' ', g.last_name) as description,
                    r.updated_at as activity_date
                 FROM reservations r
                 INNER JOIN guests g ON r.guest_id = g.guest_id
                 WHERE r.booking_status = 'checked_in'
                 ORDER BY r.updated_at DESC 
                 LIMIT :limit3)
                
                ORDER BY activity_date DESC
                LIMIT :limit4
            ";
            
            $params = [
                'limit1' => $limit,
                'limit2' => $limit,
                'limit3' => $limit,
                'limit4' => $limit
            ];
            
            $results = db_fetch_all($sql, $params);
            
            // Format results
            foreach ($results as &$row) {
                $row['created_at'] = $row['activity_date'];
                unset($row['activity_date']);
            }
            
            return $results ?: [];
            
        } catch (Exception $e) {
            error_log("Error in get_recent_activities: " . $e->getMessage());
            return [];
        }
    }
}

/**
 * Get occupancy chart data
 */
if (!function_exists('get_occupancy_chart_data')) {
    function get_occupancy_chart_data() {
        $data = ['labels' => [], 'occupancy' => []];
        
        try {
            for ($i = 6; $i >= 0; $i--) {
                $date = date('Y-m-d', strtotime("-$i days"));
                $data['labels'][] = date('D, M d', strtotime($date));
                
                $occupied = (int)db_fetch_value(
                    "SELECT COUNT(DISTINCT room_id) FROM reservations 
                     WHERE check_in_date <= ? AND check_out_date > ? 
                     AND booking_status IN ('confirmed', 'checked_in')",
                    [$date, $date]
                ) ?: 0;
                
                $total_rooms = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE is_active = 1") ?: 1;
                $occupancy_rate = $total_rooms > 0 ? round(($occupied / $total_rooms) * 100, 2) : 0;
                
                $data['occupancy'][] = $occupancy_rate;
            }
        } catch (Exception $e) {
            error_log("Error in get_occupancy_chart_data: " . $e->getMessage());
        }
        
        return $data;
    }
}

/**
 * Get revenue chart data
 */
if (!function_exists('get_revenue_chart_data')) {
    function get_revenue_chart_data() {
        $data = ['labels' => [], 'revenue' => [], 'occupancy' => []];
        
        try {
            for ($i = 6; $i >= 0; $i--) {
                $date = date('Y-m-d', strtotime("-$i days"));
                $data['labels'][] = date('D, M d', strtotime($date));
                
                $revenue = (float)db_fetch_value(
                    "SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
                     WHERE DATE(posted_at) = ? AND charge_type != 'payment' AND is_voided = 0",
                    [$date]
                ) ?: 0;
                
                $data['revenue'][] = (float)$revenue;
                
                $occupied = (int)db_fetch_value(
                    "SELECT COUNT(DISTINCT room_id) FROM reservations 
                     WHERE check_in_date <= ? AND check_out_date > ? 
                     AND booking_status IN ('confirmed', 'checked_in')",
                    [$date, $date]
                ) ?: 0;
                
                $total_rooms = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE is_active = 1") ?: 1;
                $occupancy_rate = $total_rooms > 0 ? round(($occupied / $total_rooms) * 100, 2) : 0;
                
                $data['occupancy'][] = $occupancy_rate;
            }
        } catch (Exception $e) {
            error_log("Error in get_revenue_chart_data: " . $e->getMessage());
        }
        
        return $data;
    }
}

// =============================================
// MAIN DASHBOARD CODE
// =============================================

try {
    // Get current user
    $current_user = current_user();

    // Get dashboard statistics
    $stats = get_dashboard_stats();

    // Get today's date range
    $today = date('Y-m-d');
    $tomorrow = date('Y-m-d', strtotime('+1 day'));
    $week_start = date('Y-m-d', strtotime('monday this week'));
    $week_end = date('Y-m-d', strtotime('sunday this week'));
    $month_start = date('Y-m-01');
    $month_end = date('Y-m-t');

    // Get occupancy data for chart
    $occupancy_data = get_occupancy_chart_data();
    $revenue_data = get_revenue_chart_data();

    // Get recent activities
    $recent_activities = get_recent_activities(10);

    // Get upcoming check-ins
    $upcoming_checkins = 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 DATE(r.check_in_date) = CURDATE()
         AND r.booking_status IN ('confirmed', 'pending')
         ORDER BY r.check_in_date
         LIMIT 10"
    ) ?: [];

    // Get upcoming check-outs
    $upcoming_checkouts = 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 DATE(r.check_out_date) = CURDATE()
         AND r.booking_status = 'checked_in'
         ORDER BY r.check_out_date
         LIMIT 10"
    ) ?: [];

    // Get top selling products
    $top_products = db_fetch_all(
        "SELECT p.product_name, p.product_code, SUM(si.quantity) as total_quantity, SUM(si.total_amount) as total_revenue
         FROM pos_sale_items si
         JOIN pos_products p ON si.product_id = p.product_id
         JOIN pos_sales s ON si.sale_id = s.sale_id
         WHERE s.sale_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)
         GROUP BY si.product_id
         ORDER BY total_quantity DESC
         LIMIT 10"
    ) ?: [];

    // Get room status counts
    $room_status_counts = db_fetch_all(
        "SELECT status, COUNT(*) as count FROM rooms WHERE is_active = 1 GROUP BY status"
    ) ?: [];

    $room_status_labels = [];
    $room_status_data = [];
    $room_status_colors = [];

    foreach ($room_status_counts as $status) {
        $room_status_labels[] = ucfirst($status['status']);
        $room_status_data[] = (int)$status['count'];
        
        switch($status['status']) {
            case 'available':
                $room_status_colors[] = '#28a745';
                break;
            case 'occupied':
                $room_status_colors[] = '#dc3545';
                break;
            case 'maintenance':
                $room_status_colors[] = '#ffc107';
                break;
            case 'housekeeping':
                $room_status_colors[] = '#17a2b8';
                break;
            default:
                $room_status_colors[] = '#6c757d';
        }
    }

    // Get department KPIs
    $department_kpis = [
        'frontdesk' => [
            'occupancy_rate' => $stats['occupancy_rate'],
            'checkins_today' => $stats['checkins_today'],
            'checkouts_today' => $stats['checkouts_today'],
            'arrivals_tomorrow' => (int)db_fetch_value(
                "SELECT COUNT(*) FROM reservations WHERE DATE(check_in_date) = ? AND booking_status IN ('confirmed', 'pending')",
                [$tomorrow]
            ) ?: 0
        ],
        'housekeeping' => [
            'clean_rooms' => (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'clean'") ?: 0,
            'dirty_rooms' => (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE housekeeping_status = 'dirty'") ?: 0,
            'maintenance_rooms' => (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE status = 'maintenance'") ?: 0,
            'pending_tasks' => (int)db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE status IN ('pending', 'assigned')") ?: 0
        ],
        'pos' => [
            'today_sales' => (float)db_fetch_value(
                "SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales WHERE DATE(sale_time) = CURDATE() AND payment_status = 'completed'"
            ) ?: 0,
            'today_transactions' => (int)db_fetch_value(
                "SELECT COUNT(*) FROM pos_sales WHERE DATE(sale_time) = CURDATE()"
            ) ?: 0,
            'active_shifts' => (int)db_fetch_value("SELECT COUNT(*) FROM pos_shifts WHERE status = 'open'") ?: 0
        ],
        'inventory' => [
            'low_stock_items' => (int)db_fetch_value(
                "SELECT COUNT(*) FROM pos_products WHERE stock_item = 1 AND current_stock <= min_stock"
            ) ?: 0,
            'pending_orders' => (int)db_fetch_value(
                "SELECT COUNT(*) FROM purchase_orders WHERE status IN ('ordered', 'partial')"
            ) ?: 0
        ],
        'billing' => [
            'outstanding_invoices' => (int)db_fetch_value(
                "SELECT COUNT(*) FROM invoices WHERE status IN ('sent', 'partial', 'overdue')"
            ) ?: 0,
            'overdue_amount' => (float)db_fetch_value(
                "SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE status = 'overdue'"
            ) ?: 0
        ]
    ];

} catch (Exception $e) {
    error_log("Dashboard Error: " . $e->getMessage());
    die("An error occurred loading the dashboard. Please check the error logs.");
}

// 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>Dashboard | <?php echo defined('APP_NAME') ? APP_NAME : 'Ruhondo Beach Resort'; ?></title>
        <!-- Bootstrap 5 CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <!-- Font Awesome 6 -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
        <div class="wrapper">
    <?php
}
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Executive Dashboard</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Dashboard</li>
                    </ol>
                </div>
            </div>
        </div>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Stats Cards Row -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3><?php echo $stats['occupied_rooms']; ?>/<?php echo $stats['total_rooms']; ?></h3>
                            <p>Rooms Occupied</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-bed"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <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 function_exists('format_currency') ? format_currency($stats['revenue_today']) : 'RWF ' . number_format($stats['revenue_today']); ?></h3>
                            <p>Today's Revenue</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <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['checkins_today']; ?></h3>
                            <p>Today's Check-ins</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-sign-in-alt"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <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 $stats['checkouts_today']; ?></h3>
                            <p>Today's Check-outs</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-sign-out-alt"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <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="small-box bg-primary">
                        <div class="inner">
                            <h3><?php echo $stats['occupancy_rate']; ?>%</h3>
                            <p>Occupancy Rate</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
                
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-secondary">
                        <div class="inner">
                            <h3><?php echo function_exists('format_currency') ? format_currency($stats['revenue_month']) : 'RWF ' . number_format($stats['revenue_month']); ?></h3>
                            <p>Monthly Revenue</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
                
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-dark">
                        <div class="inner">
                            <h3><?php echo function_exists('format_currency') ? format_currency($stats['revenue_year']) : 'RWF ' . number_format($stats['revenue_year']); ?></h3>
                            <p>Yearly Revenue</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-calendar"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
                
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3><?php echo $stats['total_reservations']; ?></h3>
                            <p>Active Reservations</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-calendar-check"></i>
                        </div>
                        <a href="#" class="small-box-footer">
                            More info <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Charts Row -->
            <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>
                                Revenue & Occupancy Trend (Last 7 Days)
                            </h3>
                        </div>
                        <div class="card-body">
                            <canvas id="revenueChart" style="min-height: 300px; height: 300px; max-height: 300px; max-width: 100%;"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-chart-pie mr-1"></i>
                                Room Status Distribution
                            </h3>
                        </div>
                        <div class="card-body">
                            <canvas id="roomStatusChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Department KPIs Row -->
            <div class="row">
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-header bg-info text-white">
                            <h3 class="card-title">
                                <i class="fas fa-concierge-bell mr-1"></i>
                                Front Desk
                            </h3>
                        </div>
                        <div class="card-body">
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Occupancy Rate
                                    <span class="badge bg-primary rounded-pill"><?php echo $department_kpis['frontdesk']['occupancy_rate']; ?>%</span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Check-ins Today
                                    <span class="badge bg-success rounded-pill"><?php echo $department_kpis['frontdesk']['checkins_today']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Check-outs Today
                                    <span class="badge bg-warning rounded-pill"><?php echo $department_kpis['frontdesk']['checkouts_today']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Arrivals Tomorrow
                                    <span class="badge bg-info rounded-pill"><?php echo $department_kpis['frontdesk']['arrivals_tomorrow']; ?></span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-header bg-success text-white">
                            <h3 class="card-title">
                                <i class="fas fa-broom mr-1"></i>
                                Housekeeping
                            </h3>
                        </div>
                        <div class="card-body">
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Clean Rooms
                                    <span class="badge bg-success rounded-pill"><?php echo $department_kpis['housekeeping']['clean_rooms']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Dirty Rooms
                                    <span class="badge bg-warning rounded-pill"><?php echo $department_kpis['housekeeping']['dirty_rooms']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Maintenance
                                    <span class="badge bg-danger rounded-pill"><?php echo $department_kpis['housekeeping']['maintenance_rooms']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Pending Tasks
                                    <span class="badge bg-info rounded-pill"><?php echo $department_kpis['housekeeping']['pending_tasks']; ?></span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-header bg-warning">
                            <h3 class="card-title">
                                <i class="fas fa-cash-register mr-1"></i>
                                Point of Sale
                            </h3>
                        </div>
                        <div class="card-body">
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Today's Sales
                                    <span class="badge bg-warning rounded-pill"><?php echo function_exists('format_currency') ? format_currency($department_kpis['pos']['today_sales']) : 'RWF ' . number_format($department_kpis['pos']['today_sales']); ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Transactions
                                    <span class="badge bg-success rounded-pill"><?php echo $department_kpis['pos']['today_transactions']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Active Shifts
                                    <span class="badge bg-info rounded-pill"><?php echo $department_kpis['pos']['active_shifts']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Avg. Transaction
                                    <span class="badge bg-primary rounded-pill">
                                        <?php 
                                        $avg = $department_kpis['pos']['today_transactions'] > 0 
                                            ? $department_kpis['pos']['today_sales'] / $department_kpis['pos']['today_transactions'] 
                                            : 0;
                                        echo function_exists('format_currency') ? format_currency($avg) : 'RWF ' . number_format($avg);
                                        ?>
                                    </span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-header bg-danger text-white">
                            <h3 class="card-title">
                                <i class="fas fa-boxes mr-1"></i>
                                Inventory & Billing
                            </h3>
                        </div>
                        <div class="card-body">
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Low Stock Items
                                    <span class="badge bg-danger rounded-pill"><?php echo $department_kpis['inventory']['low_stock_items']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Pending Orders
                                    <span class="badge bg-warning rounded-pill"><?php echo $department_kpis['inventory']['pending_orders']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Outstanding Invoices
                                    <span class="badge bg-info rounded-pill"><?php echo $department_kpis['billing']['outstanding_invoices']; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    Overdue Amount
                                    <span class="badge bg-danger rounded-pill"><?php echo function_exists('format_currency') ? format_currency($department_kpis['billing']['overdue_amount']) : 'RWF ' . number_format($department_kpis['billing']['overdue_amount']); ?></span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tables Row -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-calendar-check mr-1"></i>
                                Today's Check-ins
                            </h3>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Room Type</th>
                                            <th>Booking Code</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($upcoming_checkins)): ?>
                                            <tr>
                                                <td colspan="4" class="text-center text-muted py-3">
                                                    No check-ins scheduled for today
                                                </td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($upcoming_checkins as $reservation): ?>
                                            <tr>
                                                <td><?php echo escape_html($reservation['first_name'] . ' ' . $reservation['last_name']); ?></td>
                                                <td><?php echo escape_html($reservation['type_name'] ?? ''); ?></td>
                                                <td><?php echo escape_html($reservation['booking_code'] ?? ''); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo ($reservation['booking_status'] ?? '') == 'confirmed' ? 'success' : 'warning'; ?>">
                                                        <?php echo ucfirst($reservation['booking_status'] ?? 'pending'); ?>
                                                    </span>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-calendar-times mr-1"></i>
                                Today's Check-outs
                            </h3>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Room</th>
                                            <th>Booking Code</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($upcoming_checkouts)): ?>
                                            <tr>
                                                <td colspan="4" class="text-center text-muted py-3">
                                                    No check-outs scheduled for today
                                                </td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($upcoming_checkouts as $reservation): ?>
                                            <tr>
                                                <td><?php echo escape_html($reservation['first_name'] . ' ' . $reservation['last_name']); ?></td>
                                                <td>
                                                    <span class="badge bg-info">Room <?php echo escape_html($reservation['room_number'] ?? 'N/A'); ?></span>
                                                </td>
                                                <td><?php echo escape_html($reservation['booking_code'] ?? ''); ?></td>
                                                <td>
                                                    <span class="badge bg-success">Checked In</span>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Activity and Top Products -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-history mr-1"></i>
                                Recent Activities
                            </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 activities</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 = '';
                                                    switch($activity['type'] ?? '') {
                                                        case 'reservation':
                                                            $icon = 'fa-calendar-plus text-primary';
                                                            break;
                                                        case 'payment':
                                                            $icon = 'fa-dollar-sign text-success';
                                                            break;
                                                        case 'checkin':
                                                            $icon = 'fa-sign-in-alt text-info';
                                                            break;
                                                        default:
                                                            $icon = 'fa-info-circle text-secondary';
                                                    }
                                                    ?>
                                                    <i class="fas <?php echo $icon; ?> mr-2"></i>
                                                    <?php echo escape_html($activity['description'] ?? ''); ?>
                                                </h6>
                                                <small class="text-muted"><?php echo time_ago($activity['created_at']); ?></small>
                                            </div>
                                            <small class="text-muted">Ref: <?php echo escape_html($activity['reference'] ?? ''); ?></small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-chart-bar mr-1"></i>
                                Top Selling Products (30 days)
                            </h3>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($top_products)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-box-open fa-3x mb-3"></i>
                                    <p>No sales data available</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Product</th>
                                                <th>Code</th>
                                                <th class="text-right">Quantity</th>
                                                <th class="text-right">Revenue</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($top_products as $product): ?>
                                            <tr>
                                                <td><?php echo escape_html($product['product_name'] ?? ''); ?></td>
                                                <td><?php echo escape_html($product['product_code'] ?? ''); ?></td>
                                                <td class="text-right"><?php echo format_number($product['total_quantity'] ?? 0); ?></td>
                                                <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($product['total_revenue'] ?? 0) : 'RWF ' . number_format($product['total_revenue'] ?? 0); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

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

<script>
$(document).ready(function() {
    try {
        // Revenue Chart
        const revenueCtx = document.getElementById('revenueChart').getContext('2d');
        new Chart(revenueCtx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($revenue_data['labels'] ?? []); ?>,
                datasets: [{
                    label: 'Revenue (<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?>)',
                    data: <?php echo json_encode($revenue_data['revenue'] ?? []); ?>,
                    borderColor: 'rgb(75, 192, 192)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    tension: 0.1,
                    yAxisID: 'y'
                }, {
                    label: 'Occupancy %',
                    data: <?php echo json_encode($revenue_data['occupancy'] ?? []); ?>,
                    borderColor: 'rgb(255, 99, 132)',
                    backgroundColor: 'rgba(255, 99, 132, 0.2)',
                    tension: 0.1,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                stacked: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: {
                            display: true,
                            text: 'Revenue (<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?>)'
                        },
                        ticks: {
                            callback: function(value) {
                                return '<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?>' + ' ' + value.toLocaleString();
                            }
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: {
                            display: true,
                            text: 'Occupancy %'
                        },
                        grid: {
                            drawOnChartArea: false,
                        },
                        min: 0,
                        max: 100,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        });
        
        // Room Status Chart
        const roomStatusCtx = document.getElementById('roomStatusChart').getContext('2d');
        
        new Chart(roomStatusCtx, {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode($room_status_labels); ?>,
                datasets: [{
                    data: <?php echo json_encode($room_status_data); ?>,
                    backgroundColor: <?php echo json_encode($room_status_colors); ?>,
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                    }
                }
            }
        });
    } catch (e) {
        console.error('Chart error:', e);
    }
});
</script>

<style>
    .small-box {
        border-radius: 0.25rem;
        box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2);
        display: block;
        margin-bottom: 20px;
        position: relative;
        color: #fff;
    }
    .small-box > .inner {
        padding: 10px;
    }
    .small-box h3 {
        font-size: 2.2rem;
        font-weight: 700;
        margin: 0 0 10px 0;
        white-space: nowrap;
        padding: 0;
    }
    .small-box p {
        font-size: 1rem;
    }
    .small-box .icon {
        color: rgba(0,0,0,0.15);
        z-index: 0;
        position: absolute;
        top: -10px;
        right: 10px;
        font-size: 70px;
        transform: rotate(-10deg);
        transition: transform 0.3s linear;
    }
    .small-box-footer {
        display: block;
        padding: 5px 0;
        text-align: center;
        background: rgba(0,0,0,0.1);
        color: #fff;
        text-decoration: none;
    }
    .small-box-footer:hover {
        background: rgba(0,0,0,0.2);
        color: #fff;
    }
    .bg-info {
        background-color: #17a2b8 !important;
    }
    .bg-success {
        background-color: #28a745 !important;
    }
    .bg-warning {
        background-color: #ffc107 !important;
    }
    .bg-danger {
        background-color: #dc3545 !important;
    }
    .bg-primary {
        background-color: #007bff !important;
    }
    .bg-secondary {
        background-color: #6c757d !important;
    }
    .bg-dark {
        background-color: #343a40 !important;
    }
    .content-wrapper {
        background: #f4f6f9;
        padding: 20px;
    }
    .content-header {
        padding: 15px 0;
    }
    .breadcrumb {
        background: transparent;
        padding: 0;
        margin: 0;
    }
    .breadcrumb-item a {
        color: #007bff;
    }
    .list-group-item {
        border: none;
        border-bottom: 1px solid rgba(0,0,0,.125);
    }
    .badge {
        padding: 5px 10px;
        font-weight: 500;
    }
    .rounded-pill {
        border-radius: 50px !important;
    }
</style>

<?php
// Include footer
$footer_path = BASE_PATH . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    ?>
        </div>
        <!-- Bootstrap JS -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    <?php
}
?>