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

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

// Calculate the correct path using multiple fallbacks
$base_path = null;

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

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/billing/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 3);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 1) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// 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 has_permission function if it doesn't exist
if (!function_exists('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// 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');
    }
}

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

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

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

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

// Define constants if not defined
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('dashboard.billing');
}

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

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get date ranges
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$month_start = date('Y-m-01');
$month_end = date('Y-m-t');
$last_month_start = date('Y-m-01', strtotime('-1 month'));
$last_month_end = date('Y-m-t', strtotime('-1 month'));

// Initialize stats with default values
$stats = [
    'revenue_today' => 0,
    'payments_today' => 0,
    'invoices_today' => 0,
    'revenue_month' => 0,
    'revenue_last_month' => 0,
    'outstanding_invoices' => 0,
    'outstanding_amount' => 0,
    'overdue_invoices' => 0,
    'overdue_amount' => 0,
    'total_invoices' => 0,
    'paid_invoices' => 0,
    'average_invoice' => 0,
    'revenue_growth' => 0
];

// Get billing statistics with error handling
if (function_exists('db_fetch_value')) {
    try {
        $stats['revenue_today'] = (float)db_fetch_value("
            SELECT COALESCE(SUM(amount), 0) FROM payments 
            WHERE DATE(payment_date) = CURDATE()
            AND status = 'completed'
        ") ?: 0;
        
        $stats['payments_today'] = (int)db_fetch_value("
            SELECT COUNT(*) FROM payments 
            WHERE DATE(payment_date) = CURDATE()
            AND status = 'completed'
        ") ?: 0;
        
        $stats['invoices_today'] = (int)db_fetch_value("
            SELECT COUNT(*) FROM invoices 
            WHERE DATE(created_at) = CURDATE()
        ") ?: 0;
        
        $stats['revenue_month'] = (float)db_fetch_value("
            SELECT COALESCE(SUM(amount), 0) FROM payments 
            WHERE MONTH(payment_date) = MONTH(CURDATE())
            AND YEAR(payment_date) = YEAR(CURDATE())
            AND status = 'completed'
        ") ?: 0;
        
        $stats['revenue_last_month'] = (float)db_fetch_value("
            SELECT COALESCE(SUM(amount), 0) FROM payments 
            WHERE MONTH(payment_date) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
            AND YEAR(payment_date) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
            AND status = 'completed'
        ") ?: 0;
        
        $stats['outstanding_invoices'] = (int)db_fetch_value("
            SELECT COUNT(*) FROM invoices 
            WHERE status IN ('sent', 'partial', 'overdue')
        ") ?: 0;
        
        $stats['outstanding_amount'] = (float)db_fetch_value("
            SELECT COALESCE(SUM(balance), 0) FROM invoices 
            WHERE status IN ('sent', 'partial', 'overdue')
        ") ?: 0;
        
        $stats['overdue_invoices'] = (int)db_fetch_value("
            SELECT COUNT(*) FROM invoices 
            WHERE status = 'overdue'
        ") ?: 0;
        
        $stats['overdue_amount'] = (float)db_fetch_value("
            SELECT COALESCE(SUM(balance), 0) FROM invoices 
            WHERE status = 'overdue'
        ") ?: 0;
        
        $stats['total_invoices'] = (int)db_fetch_value("SELECT COUNT(*) FROM invoices") ?: 0;
        $stats['paid_invoices'] = (int)db_fetch_value("SELECT COUNT(*) FROM invoices WHERE status = 'paid'") ?: 0;
        $stats['average_invoice'] = (float)db_fetch_value("
            SELECT COALESCE(AVG(total_amount), 0) FROM invoices 
            WHERE MONTH(created_at) = MONTH(CURDATE())
        ") ?: 0;
    } catch (Exception $e) {
        error_log("Error fetching billing stats: " . $e->getMessage());
    }
}

// Calculate month-over-month growth
$stats['revenue_growth'] = $stats['revenue_last_month'] > 0 
    ? round((($stats['revenue_month'] - $stats['revenue_last_month']) / $stats['revenue_last_month']) * 100, 1)
    : 0;

// Get recent payments
$recent_payments = [];
if (function_exists('db_fetch_all')) {
    try {
        $recent_payments = db_fetch_all("
            SELECT 
                p.*,
                g.first_name, g.last_name, g.email,
                pm.method_name
            FROM payments p
            JOIN guests g ON p.guest_id = g.guest_id
            JOIN payment_methods pm ON p.payment_method_id = pm.payment_method_id
            ORDER BY p.payment_date DESC
            LIMIT 20
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching recent payments: " . $e->getMessage());
    }
}

// Get overdue invoices
$overdue_invoices = [];
if (function_exists('db_fetch_all')) {
    try {
        $overdue_invoices = db_fetch_all("
            SELECT 
                i.*,
                g.first_name, g.last_name, g.email, g.phone,
                DATEDIFF(CURDATE(), i.due_date) as days_overdue
            FROM invoices i
            JOIN guests g ON i.guest_id = g.guest_id
            WHERE i.status = 'overdue'
            ORDER BY i.due_date ASC
            LIMIT 20
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching overdue invoices: " . $e->getMessage());
    }
}

// Get top debtors
$top_debtors = [];
if (function_exists('db_fetch_all')) {
    try {
        $top_debtors = db_fetch_all("
            SELECT 
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                COUNT(i.invoice_id) as invoice_count,
                SUM(i.balance) as total_balance,
                MAX(i.due_date) as oldest_invoice
            FROM guests g
            JOIN invoices i ON g.guest_id = i.guest_id
            WHERE i.status IN ('sent', 'partial', 'overdue')
            GROUP BY g.guest_id
            HAVING total_balance > 0
            ORDER BY total_balance DESC
            LIMIT 15
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching top debtors: " . $e->getMessage());
    }
}

// Get revenue by payment method
$payment_methods = [];
if (function_exists('db_fetch_all')) {
    try {
        $payment_methods = db_fetch_all("
            SELECT 
                pm.method_name,
                COUNT(p.payment_id) as count,
                COALESCE(SUM(p.amount), 0) as total
            FROM payment_methods pm
            LEFT JOIN payments p ON pm.payment_method_id = p.payment_method_id
                AND MONTH(p.payment_date) = MONTH(CURDATE())
                AND YEAR(p.payment_date) = YEAR(CURDATE())
            WHERE pm.is_active = 1
            GROUP BY pm.payment_method_id
            ORDER BY total DESC
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching payment methods: " . $e->getMessage());
    }
}

// Get daily revenue for the month
$daily_revenue = ['labels' => [], 'data' => []];
$days_in_month = date('t');
for ($day = 1; $day <= $days_in_month; $day++) {
    $date = date('Y-m') . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);
    if ($date <= $today) {
        $daily_revenue['labels'][] = date('M d', strtotime($date));
        if (function_exists('db_fetch_value')) {
            try {
                $daily_revenue['data'][] = (float)db_fetch_value("
                    SELECT COALESCE(SUM(amount), 0) FROM payments 
                    WHERE DATE(payment_date) = ?
                    AND status = 'completed'
                ", [$date]) ?: 0;
            } catch (Exception $e) {
                $daily_revenue['data'][] = 0;
            }
        } else {
            $daily_revenue['data'][] = 0;
        }
    }
}

// Get invoice status distribution
$invoice_status = [];
$status_colors = [
    'paid' => '#28a745',
    'partial' => '#ffc107',
    'sent' => '#17a2b8',
    'overdue' => '#dc3545',
    'draft' => '#6c757d',
    'cancelled' => '#343a40'
];

if (function_exists('db_fetch_all')) {
    try {
        $invoice_status = db_fetch_all("
            SELECT 
                status,
                COUNT(*) as count,
                COALESCE(SUM(total_amount), 0) as total
            FROM invoices
            GROUP BY status
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching invoice status: " . $e->getMessage());
    }
}

// Get recent invoices
$recent_invoices = [];
if (function_exists('db_fetch_all')) {
    try {
        $recent_invoices = db_fetch_all("
            SELECT 
                i.*,
                g.first_name, g.last_name
            FROM invoices i
            JOIN guests g ON i.guest_id = g.guest_id
            ORDER BY i.created_at DESC
            LIMIT 15
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching recent invoices: " . $e->getMessage());
    }
}

// Get guest balances for in-house guests
$guest_balances = [];
if (function_exists('db_fetch_all')) {
    try {
        $guest_balances = db_fetch_all("
            SELECT 
                g.guest_id, g.first_name, g.last_name,
                r.reservation_id, r.booking_code,
                r.room_id, rm.room_number,
                r.total_amount, r.paid_amount,
                (r.total_amount - r.paid_amount) as balance,
                r.check_in_date, r.check_out_date
            FROM guests g
            JOIN reservations r ON g.guest_id = r.guest_id
            LEFT JOIN rooms rm ON r.room_id = rm.room_id
            WHERE r.booking_status = 'checked_in'
            AND r.total_amount > r.paid_amount
            ORDER BY balance DESC
            LIMIT 15
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching guest balances: " . $e->getMessage());
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Billing 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>
        <script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.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; }
            .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; }
            .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-secondary { background-color: #6c757d !important; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-4 { margin-bottom: 1.5rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-3 { margin-top: 1rem; }
            .text-end { text-align: right; }
            .progress-xs { height: 5px; margin-top: 5px; }
        </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="#">Billing 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">Billing 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"><a href="/HMSPOS/billing/dashboard.php">Billing</a></li>
                    <li class="breadcrumb-item active">Dashboard</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Quick Actions Row -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <a href="/HMSPOS/billing/invoices/create.php" class="btn btn-primary me-2 mb-2">
                            <i class="fas fa-file-invoice me-1"></i> New Invoice
                        </a>
                        <a href="/HMSPOS/billing/payments/add.php" class="btn btn-success me-2 mb-2">
                            <i class="fas fa-dollar-sign me-1"></i> Record Payment
                        </a>
                        <a href="/HMSPOS/billing/payments/refund.php" class="btn btn-warning me-2 mb-2">
                            <i class="fas fa-undo-alt me-1"></i> Process Refund
                        </a>
                        <a href="/HMSPOS/billing/debtor/index.php" class="btn btn-danger me-2 mb-2">
                            <i class="fas fa-exclamation-triangle me-1"></i> Debtor Management
                        </a>
                        <a href="/HMSPOS/reports/revenue.php" class="btn btn-info me-2 mb-2">
                            <i class="fas fa-chart-bar me-1"></i> Revenue Reports
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['revenue_today']); ?></h3>
                        <p>Today's Revenue</p>
                        <small><?php echo $stats['payments_today']; ?> payments</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['revenue_month']); ?></h3>
                        <p>Monthly Revenue</p>
                        <small>
                            <?php echo $stats['revenue_growth'] >= 0 ? '+' : ''; ?><?php echo $stats['revenue_growth']; ?>% vs last month
                        </small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['outstanding_amount']); ?></h3>
                        <p>Outstanding</p>
                        <small><?php echo $stats['outstanding_invoices']; ?> invoices</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['overdue_amount']); ?></h3>
                        <p>Overdue</p>
                        <small><?php echo $stats['overdue_invoices']; ?> invoices</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <a href="#overdue" class="small-box-footer text-white">
                        View Details <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-file-invoice"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Total Invoices</span>
                        <span class="info-box-number"><?php echo $stats['total_invoices']; ?></span>
                        <span class="info-box-text"><?php echo $stats['paid_invoices']; ?> paid</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-check-circle"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Paid Invoices</span>
                        <span class="info-box-number"><?php echo $stats['paid_invoices']; ?></span>
                        <span class="info-box-percent">
                            <?php 
                            $paid_percent = $stats['total_invoices'] > 0 
                                ? round(($stats['paid_invoices'] / $stats['total_invoices']) * 100, 1) 
                                : 0;
                            echo $paid_percent; ?>%
                        </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-calculator"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Average Invoice</span>
                        <span class="info-box-number"><?php echo format_currency($stats['average_invoice']); ?></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-credit-card"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Payment Methods</span>
                        <span class="info-box-number"><?php echo count($payment_methods); ?></span>
                    </div>
                </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 me-1"></i>
                            Daily Revenue - <?php echo date('F Y'); ?>
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="revenueChart" style="height: 300px;"></canvas>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie me-1"></i>
                            Invoice Status
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="statusChart" style="height: 250px;"></canvas>
                        
                        <div class="mt-3">
                            <?php 
                            foreach ($invoice_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 me-2" style="color: <?php echo $color; ?>"></i>
                                    <?php echo ucfirst($status['status'] ?? ''); ?>
                                </span>
                                <span>
                                    <span class="badge bg-secondary"><?php echo $status['count'] ?? 0; ?></span>
                                    <span class="text-muted ms-2"><?php echo format_currency($status['total'] ?? 0); ?></span>
                                </span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Overdue Invoices -->
            <div class="col-md-6" id="overdue">
                <div class="card card-danger">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exclamation-triangle me-1"></i>
                            Overdue Invoices
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/billing/invoices/index.php?status=overdue" class="btn btn-sm btn-danger">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($overdue_invoices)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                <p>No overdue invoices</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Invoice #</th>
                                            <th>Guest</th>
                                            <th>Due Date</th>
                                            <th>Days</th>
                                            <th class="text-end">Amount</th>
                                            <th class="text-end">Balance</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($overdue_invoices as $invoice): ?>
                                        <tr>
                                            <td>
                                                <a href="/HMSPOS/billing/invoices/view.php?id=<?php echo $invoice['invoice_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($invoice['invoice_number'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/guests/view.php?id=<?php echo $invoice['guest_id'] ?? 0; ?>">
                                                    <?php echo escape_html(($invoice['first_name'] ?? '') . ' ' . ($invoice['last_name'] ?? '')); ?>
                                                </a>
                                            </td>
                                            <td><?php echo isset($invoice['due_date']) ? date('M d, Y', strtotime($invoice['due_date'])) : 'N/A'; ?></td>
                                            <td>
                                                <span class="badge bg-danger"><?php echo $invoice['days_overdue'] ?? 0; ?> days</span>
                                            </td>
                                            <td class="text-end"><?php echo format_currency($invoice['total_amount'] ?? 0); ?></td>
                                            <td class="text-end">
                                                <span class="badge bg-danger"><?php echo format_currency($invoice['balance'] ?? 0); ?></span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/billing/payments/add.php?invoice_id=<?php echo $invoice['invoice_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-dollar-sign"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Top Debtors -->
            <div class="col-md-6">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-users me-1"></i>
                            Top Debtors
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($top_debtors)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-users fa-3x mb-3"></i>
                                <p>No debtors</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th class="text-center">Invoices</th>
                                            <th class="text-end">Balance</th>
                                            <th>Oldest</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($top_debtors as $debtor): ?>
                                        <tr>
                                            <td>
                                                <a href="/HMSPOS/guests/view.php?id=<?php echo $debtor['guest_id'] ?? 0; ?>">
                                                    <strong><?php echo escape_html(($debtor['first_name'] ?? '') . ' ' . ($debtor['last_name'] ?? '')); ?></strong>
                                                </a>
                                                <br>
                                                <small class="text-muted"><?php echo escape_html($debtor['email'] ?? ''); ?></small>
                                            </td>
                                            <td class="text-center"><?php echo $debtor['invoice_count'] ?? 0; ?></td>
                                            <td class="text-end">
                                                <span class="badge bg-warning"><?php echo format_currency($debtor['total_balance'] ?? 0); ?></span>
                                            </td>
                                            <td>
                                                <?php echo !empty($debtor['oldest_invoice']) ? date('M d, Y', strtotime($debtor['oldest_invoice'])) : 'N/A'; ?>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/billing/debtor/statement.php?guest_id=<?php echo $debtor['guest_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-info">
                                                    <i class="fas fa-file-invoice"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Recent Payments -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history me-1"></i>
                            Recent Payments
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/billing/payments/index.php" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($recent_payments)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-dollar-sign fa-3x mb-3"></i>
                                <p>No recent payments</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Guest</th>
                                            <th>Method</th>
                                            <th class="text-end">Amount</th>
                                            <th>Status</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_payments as $payment): ?>
                                        <tr>
                                            <td><?php echo isset($payment['payment_date']) ? date('M d, H:i', strtotime($payment['payment_date'])) : 'N/A'; ?></td>
                                            <td>
                                                <a href="/HMSPOS/guests/view.php?id=<?php echo $payment['guest_id'] ?? 0; ?>">
                                                    <?php echo escape_html(($payment['first_name'] ?? '') . ' ' . ($payment['last_name'] ?? '')); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?php echo htmlspecialchars($payment['method_name'] ?? ''); ?></span>
                                            </td>
                                            <td class="text-end"><?php echo format_currency($payment['amount'] ?? 0); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo ($payment['status'] ?? '') == 'completed' ? 'success' : 'warning'; ?>">
                                                    <?php echo ucfirst($payment['status'] ?? ''); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/billing/payments/index.php?receipt=<?php echo urlencode($payment['payment_number'] ?? ''); ?>" 
                                                   class="btn btn-sm btn-info">
                                                    <i class="fas fa-receipt"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Guest Balances (In-House) -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-hotel me-1"></i>
                            In-House Guest Balances
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($guest_balances)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-smile fa-3x mb-3"></i>
                                <p>All in-house guests have zero balance</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Room</th>
                                            <th>Check-out</th>
                                            <th class="text-end">Total</th>
                                            <th class="text-end">Paid</th>
                                            <th class="text-end">Balance</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($guest_balances as $guest): ?>
                                        <tr>
                                            <td>
                                                <a href="/HMSPOS/guests/view.php?id=<?php echo $guest['guest_id'] ?? 0; ?>">
                                                    <?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?php echo htmlspecialchars($guest['room_number'] ?? ''); ?></span>
                                            </td>
                                            <td><?php echo isset($guest['check_out_date']) ? date('M d, Y', strtotime($guest['check_out_date'])) : 'N/A'; ?></td>
                                            <td class="text-end"><?php echo format_currency($guest['total_amount'] ?? 0); ?></td>
                                            <td class="text-end"><?php echo format_currency($guest['paid_amount'] ?? 0); ?></td>
                                            <td class="text-end">
                                                <span class="badge bg-<?php echo !empty($guest['balance']) && $guest['balance'] > 0 ? 'warning' : 'success'; ?>">
                                                    <?php echo format_currency($guest['balance'] ?? 0); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/reservations/folio/view.php?reservation_id=<?php echo $guest['reservation_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-primary">
                                                    <i class="fas fa-file-invoice"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Payment Methods Breakdown -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-credit-card me-1"></i>
                            Revenue by Payment Method (This Month)
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Payment Method</th>
                                        <th class="text-center">Transactions</th>
                                        <th class="text-end">Amount</th>
                                        <th class="text-end">% of Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $total_revenue = array_sum(array_column($payment_methods, 'total'));
                                    foreach ($payment_methods as $method): 
                                    ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo escape_html($method['method_name'] ?? ''); ?></strong>
                                        </td>
                                        <td class="text-center"><?php echo $method['count'] ?? 0; ?></td>
                                        <td class="text-end"><?php echo format_currency($method['total'] ?? 0); ?></td>
                                        <td class="text-end">
                                            <?php 
                                            $percentage = $total_revenue > 0 
                                                ? round((($method['total'] ?? 0) / $total_revenue) * 100, 1) 
                                                : 0;
                                            ?>
                                            <div class="progress progress-xs">
                                                <div class="progress-bar bg-info" style="width: <?php echo $percentage; ?>%"></div>
                                            </div>
                                            <small><?php echo $percentage; ?>%</small>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Invoices -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-file-invoice me-1"></i>
                            Recent Invoices
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/billing/invoices/index.php" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Invoice #</th>
                                        <th>Guest</th>
                                        <th>Date</th>
                                        <th>Due Date</th>
                                        <th class="text-end">Total</th>
                                        <th class="text-end">Paid</th>
                                        <th class="text-end">Balance</th>
                                        <th>Status</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_invoices as $invoice): ?>
                                    <tr>
                                        <td>
                                            <a href="/HMSPOS/billing/invoices/view.php?id=<?php echo $invoice['invoice_id'] ?? 0; ?>">
                                                <?php echo htmlspecialchars($invoice['invoice_number'] ?? ''); ?>
                                            </a>
                                        </td>
                                        <td>
                                            <a href="/HMSPOS/guests/view.php?id=<?php echo $invoice['guest_id'] ?? 0; ?>">
                                                <?php echo escape_html(($invoice['first_name'] ?? '') . ' ' . ($invoice['last_name'] ?? '')); ?>
                                            </a>
                                        </td>
                                        <td><?php echo isset($invoice['invoice_date']) ? date('M d, Y', strtotime($invoice['invoice_date'])) : 'N/A'; ?></td>
                                        <td><?php echo isset($invoice['due_date']) ? date('M d, Y', strtotime($invoice['due_date'])) : 'N/A'; ?></td>
                                        <td class="text-end"><?php echo format_currency($invoice['total_amount'] ?? 0); ?></td>
                                        <td class="text-end"><?php echo format_currency($invoice['paid_amount'] ?? 0); ?></td>
                                        <td class="text-end">
                                            <span class="badge bg-<?php 
                                                $balance = $invoice['balance'] ?? 0;
                                                echo $balance == 0 ? 'success' : 
                                                    ((!empty($invoice['due_date']) && strtotime($invoice['due_date']) < time()) ? 'danger' : 'warning');
                                            ?>">
                                                <?php echo format_currency($balance); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php 
                                                $status = $invoice['status'] ?? '';
                                                echo $status == 'paid' ? 'success' : 
                                                    ($status == 'overdue' ? 'danger' : 
                                                    ($status == 'partial' ? 'warning' : 
                                                    ($status == 'sent' ? 'info' : 'secondary')));
                                            ?>">
                                                <?php echo ucfirst($status); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="btn-group">
                                                <a href="/HMSPOS/billing/invoices/pdf.php?id=<?php echo $invoice['invoice_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success" target="_blank">
                                                    <i class="fas fa-file-pdf"></i>
                                                </a>
                                                <a href="/HMSPOS/billing/invoices/email.php?id=<?php echo $invoice['invoice_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-info">
                                                    <i class="fas fa-envelope"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Revenue Chart
    const revenueCtx = document.getElementById('revenueChart')?.getContext('2d');
    if (revenueCtx) {
        new Chart(revenueCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($daily_revenue['labels']); ?>,
                datasets: [{
                    label: 'Daily Revenue',
                    data: <?php echo json_encode($daily_revenue['data']); ?>,
                    backgroundColor: '#28a745',
                    borderColor: '#218838',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value, index, values) {
                                return '<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?>' + value;
                            }
                        }
                    }
                }
            }
        });
    }
    
    // Status Chart
    const statusCtx = document.getElementById('statusChart')?.getContext('2d');
    if (statusCtx) {
        <?php
        $status_labels = [];
        $status_counts = [];
        $status_colors_array = [];
        
        foreach ($invoice_status as $status) {
            $status_labels[] = ucfirst($status['status'] ?? '');
            $status_counts[] = $status['count'] ?? 0;
            $status_colors_array[] = $status_colors[$status['status'] ?? ''] ?? '#6c757d';
        }
        ?>
        
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode($status_labels); ?>,
                datasets: [{
                    data: <?php echo json_encode($status_counts); ?>,
                    backgroundColor: <?php echo json_encode($status_colors_array); ?>,
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }
});

// Auto-refresh every 5 minutes
setTimeout(function() {
    location.reload();
}, 300000);
</script>

<style>
.progress-xs {
    height: 5px;
    margin-top: 5px;
}
</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>';
}
?>