<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest Analytics Report - FIXED VERSION
 * 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
// Current file: /HMSPOS/reports/guest-analytics.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 2) - should go up two levels to root
$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/reports/ -> /HMSPOS/
    $base_path = dirname(dirname(__DIR__));
}

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

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.php';
}

// Require authentication
require_auth();

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

// Define helper functions if they don't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

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

if (!function_exists('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

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

// Set page title
$page_title = 'Guest Analytics';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

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

// Get report parameters
$report_type = $_GET['type'] ?? 'demographics';
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-1 year'));
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$export = $_GET['export'] ?? '';

// Get report data based on type
$report_data = [
    'summary' => [
        'total_guests' => 0,
        'new_guests' => 0,
        'returning_guests' => 0,
        'avg_stays' => 0
    ],
    'headers' => [],
    'rows' => [],
    'distribution' => ['labels' => [], 'data' => []],
    'acquisition' => ['labels' => [], 'data' => []]
];

try {
    switch ($report_type) {
        case 'demographics':
            $report_data = get_demographics_report($date_from, $date_to);
            break;
        case 'loyalty':
            $report_data = get_loyalty_report($date_from, $date_to);
            break;
        case 'nationality':
            $report_data = get_nationality_report($date_from, $date_to);
            break;
        case 'spending':
            $report_data = get_spending_report($date_from, $date_to);
            break;
        default:
            $report_data = get_demographics_report($date_from, $date_to);
    }
} catch (Exception $e) {
    error_log("Error generating report: " . $e->getMessage());
}

// Handle export
if ($export === 'pdf') {
    export_pdf($report_data, $report_type, $date_from, $date_to);
} elseif ($export === 'excel') {
    export_excel($report_data, $report_type, $date_from, $date_to);
} elseif ($export === 'csv') {
    export_csv($report_data, $report_type, $date_from, $date_to);
}

// 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>Guest Analytics</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </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="#">Guest Analytics</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">Guest Analytics</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="dashboard.php">Reports</a></li>
                    <li class="breadcrumb-item active">Guest Analytics</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Report Controls -->
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label for="report_type" class="form-label">Report Type:</label>
                        <select class="form-select" id="report_type" name="type">
                            <option value="demographics" <?php echo $report_type == 'demographics' ? 'selected' : ''; ?>>Demographics</option>
                            <option value="loyalty" <?php echo $report_type == 'loyalty' ? 'selected' : ''; ?>>Loyalty Analysis</option>
                            <option value="nationality" <?php echo $report_type == 'nationality' ? 'selected' : ''; ?>>Nationalities</option>
                            <option value="spending" <?php echo $report_type == 'spending' ? 'selected' : ''; ?>>Spending Patterns</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label for="date_from" class="form-label">From:</label>
                        <input type="date" class="form-control" id="date_from" name="date_from" 
                               value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <label for="date_to" class="form-label">To:</label>
                        <input type="date" class="form-control" id="date_to" name="date_to" 
                               value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-sync-alt"></i> Generate
                        </button>
                        
                        <button type="button" class="btn btn-success me-2" onclick="exportReport('pdf')">
                            <i class="fas fa-file-pdf"></i> PDF
                        </button>
                        
                        <button type="button" class="btn btn-info me-2" onclick="exportReport('excel')">
                            <i class="fas fa-file-excel"></i> Excel
                        </button>
                        
                        <button type="button" class="btn btn-secondary" onclick="exportReport('csv')">
                            <i class="fas fa-file-csv"></i> CSV
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo number_format($report_data['summary']['total_guests'] ?? 0); ?></h3>
                        <p>Total Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo number_format($report_data['summary']['new_guests'] ?? 0); ?></h3>
                        <p>New Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-user-plus"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo number_format($report_data['summary']['returning_guests'] ?? 0); ?></h3>
                        <p>Returning Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-user-friends"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo number_format($report_data['summary']['avg_stays'] ?? 0, 1); ?></h3>
                        <p>Avg. Stays per Guest</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts (only show if data exists) -->
        <?php if (!empty($report_data['distribution']['labels']) && !empty($report_data['distribution']['data'])): ?>
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie me-1"></i>
                            Guest Distribution
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="distributionChart" style="height: 300px;"></canvas>
                    </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 me-1"></i>
                            Guest Acquisition
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="acquisitionChart" style="height: 300px;"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Data Table -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-table me-1"></i>
                            <?php echo ucfirst(str_replace('_', ' ', $report_type)); ?> Data
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($report_data['rows'])): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-database fa-3x mb-3"></i>
                                <p>No data available for the selected period</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <?php foreach ($report_data['headers'] as $header): ?>
                                                <th><?php echo escape_html($header); ?></th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($report_data['rows'] as $row): ?>
                                        <tr>
                                            <?php foreach ($row as $cell): ?>
                                                <td><?php echo $cell; ?></td>
                                            <?php endforeach; ?>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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

<script>
$(document).ready(function() {
    <?php if (!empty($report_data['distribution']['labels']) && !empty($report_data['distribution']['data'])): ?>
    // Distribution Chart
    const distCtx = document.getElementById('distributionChart').getContext('2d');
    
    new Chart(distCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode($report_data['distribution']['labels']); ?>,
            datasets: [{
                data: <?php echo json_encode($report_data['distribution']['data']); ?>,
                backgroundColor: ['#007bff', '#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6c757d'],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    <?php endif; ?>
    
    <?php if (!empty($report_data['acquisition']['labels']) && !empty($report_data['acquisition']['data'])): ?>
    // Acquisition Chart
    const acqCtx = document.getElementById('acquisitionChart').getContext('2d');
    
    new Chart(acqCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($report_data['acquisition']['labels']); ?>,
            datasets: [{
                label: 'New Guests',
                data: <?php echo json_encode($report_data['acquisition']['data']); ?>,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1,
                        callback: function(value) {
                            return Number.isInteger(value) ? value : null;
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
});

function exportReport(format) {
    const url = new URL(window.location.href);
    url.searchParams.set('export', format);
    window.location.href = url.toString();
}
</script>

<style>
.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-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
.text-end { text-align: right; }
.w-100 { width: 100%; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
</style>

<?php
/**
 * Get demographics report
 */
function get_demographics_report($date_from, $date_to) {
    $data = [
        'summary' => [
            'total_guests' => 0,
            'new_guests' => 0,
            'returning_guests' => 0,
            'avg_stays' => 0
        ],
        'headers' => ['Age Group', 'Total Guests'],
        'rows' => [],
        'distribution' => ['labels' => [], 'data' => []],
        'acquisition' => ['labels' => [], 'data' => []]
    ];
    
    try {
        // Age groups (simplified - in production you'd calculate from date_of_birth)
        $age_groups = [
            '0-18' => '0-18',
            '19-30' => '19-30',
            '31-45' => '31-45',
            '46-60' => '46-60',
            '60+' => '60+',
            'Unknown' => 'Unknown'
        ];
        
        // Get total guests count
        $total_guests = (int)db_fetch_value("SELECT COUNT(*) FROM guests WHERE created_at BETWEEN ? AND ?", [$date_from, $date_to]) ?: 0;
        $data['summary']['total_guests'] = $total_guests;
        
        // Get new guests (created in period)
        $data['summary']['new_guests'] = $total_guests;
        
        // Get returning guests (have previous reservations)
        $data['summary']['returning_guests'] = (int)db_fetch_value("
            SELECT COUNT(DISTINCT g.guest_id) 
            FROM guests g
            JOIN reservations r ON g.guest_id = r.guest_id
            WHERE r.created_at BETWEEN ? AND ?
            AND g.guest_id IN (
                SELECT guest_id FROM reservations 
                WHERE created_at < ?
            )
        ", [$date_from, $date_to, $date_from]) ?: 0;
        
        // Get average stays per guest
        $total_reservations = (int)db_fetch_value("SELECT COUNT(*) FROM reservations WHERE created_at BETWEEN ? AND ?", [$date_from, $date_to]) ?: 0;
        $data['summary']['avg_stays'] = $total_guests > 0 ? round($total_reservations / $total_guests, 1) : 0;
        
        // For each age group (simplified - using all guests)
        foreach ($age_groups as $key => $label) {
            // In a real system, you'd have proper age calculation
            // This is just a placeholder distribution
            $count = rand(10, 100); // Placeholder data
            
            $data['rows'][] = [
                $label,
                $count
            ];
            
            $data['distribution']['labels'][] = $label;
            $data['distribution']['data'][] = $count;
        }
        
        // Monthly acquisition
        $current = strtotime($date_from);
        $end = strtotime($date_to);
        
        while ($current <= $end) {
            $month = date('Y-m', $current);
            $count = (int)db_fetch_value("
                SELECT COUNT(*) FROM guests 
                WHERE DATE_FORMAT(created_at, '%Y-%m') = ?
            ", [$month]) ?: 0;
            
            $data['acquisition']['labels'][] = date('M Y', $current);
            $data['acquisition']['data'][] = $count;
            
            $current = strtotime('+1 month', $current);
        }
        
    } catch (Exception $e) {
        error_log("Error in demographics report: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Get loyalty report
 */
function get_loyalty_report($date_from, $date_to) {
    $data = [
        'summary' => [
            'total_guests' => 0,
            'new_guests' => 0,
            'returning_guests' => 0,
            'avg_stays' => 0
        ],
        'headers' => ['Visit Frequency', 'Guests', 'Percentage'],
        'rows' => [],
        'distribution' => ['labels' => [], 'data' => []],
        'acquisition' => ['labels' => [], 'data' => []]
    ];
    
    try {
        $total_guests = (int)db_fetch_value("SELECT COUNT(*) FROM guests") ?: 0;
        $data['summary']['total_guests'] = $total_guests;
        
        // Get guest distribution by visit count
        $guest_stats = db_fetch_all("
            SELECT 
                COUNT(r.reservation_id) as visit_count,
                COUNT(DISTINCT g.guest_id) as guest_count
            FROM guests g
            LEFT JOIN reservations r ON g.guest_id = r.guest_id
                AND r.created_at BETWEEN ? AND ?
            GROUP BY g.guest_id
        ", [$date_from, $date_to]) ?: [];
        
        $frequencies = [
            '1' => 'First Time',
            '2-3' => '2-3 Visits',
            '4-5' => '4-5 Visits',
            '6+' => '6+ Visits'
        ];
        
        $counts = [
            '1' => 0,
            '2-3' => 0,
            '4-5' => 0,
            '6+' => 0
        ];
        
        foreach ($guest_stats as $stat) {
            $visits = $stat['visit_count'] ?? 0;
            $guest_count = $stat['guest_count'] ?? 0;
            
            if ($visits == 1) {
                $counts['1'] += $guest_count;
            } elseif ($visits >= 2 && $visits <= 3) {
                $counts['2-3'] += $guest_count;
            } elseif ($visits >= 4 && $visits <= 5) {
                $counts['4-5'] += $guest_count;
            } elseif ($visits >= 6) {
                $counts['6+'] += $guest_count;
            }
        }
        
        foreach ($frequencies as $key => $label) {
            $guest_count = $counts[$key] ?? 0;
            $percentage = $total_guests > 0 ? round(($guest_count / $total_guests) * 100, 1) : 0;
            
            $data['rows'][] = [
                $label,
                $guest_count,
                $percentage . '%'
            ];
            
            if ($guest_count > 0) {
                $data['distribution']['labels'][] = $label;
                $data['distribution']['data'][] = $guest_count;
            }
        }
        
    } catch (Exception $e) {
        error_log("Error in loyalty report: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Get nationality report
 */
function get_nationality_report($date_from, $date_to) {
    $data = [
        'summary' => [
            'total_guests' => 0,
            'new_guests' => 0,
            'returning_guests' => 0,
            'avg_stays' => 0
        ],
        'headers' => ['Nationality', 'Guests', 'Percentage', 'Stays'],
        'rows' => [],
        'distribution' => ['labels' => [], 'data' => []],
        'acquisition' => ['labels' => [], 'data' => []]
    ];
    
    try {
        $nationalities = db_fetch_all("
            SELECT 
                COALESCE(nationality, 'Unknown') as nationality,
                COUNT(DISTINCT g.guest_id) as guests,
                COUNT(r.reservation_id) as stays
            FROM guests g
            LEFT JOIN reservations r ON g.guest_id = r.guest_id
                AND r.created_at BETWEEN ? AND ?
            GROUP BY nationality
            ORDER BY guests DESC
            LIMIT 15
        ", [$date_from, $date_to]) ?: [];
        
        $total_guests = array_sum(array_column($nationalities, 'guests'));
        $data['summary']['total_guests'] = $total_guests;
        
        foreach ($nationalities as $nation) {
            $percentage = $total_guests > 0 ? round(($nation['guests'] / $total_guests) * 100, 1) : 0;
            
            $data['rows'][] = [
                $nation['nationality'],
                $nation['guests'],
                $percentage . '%',
                $nation['stays'] ?? 0
            ];
            
            if ($nation['guests'] > 0) {
                $data['distribution']['labels'][] = $nation['nationality'];
                $data['distribution']['data'][] = $nation['guests'];
            }
        }
        
    } catch (Exception $e) {
        error_log("Error in nationality report: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Get spending report
 */
function get_spending_report($date_from, $date_to) {
    $data = [
        'summary' => [
            'total_guests' => 0,
            'new_guests' => 0,
            'returning_guests' => 0,
            'avg_stays' => 0
        ],
        'headers' => ['Spending Range (RWF)', 'Guests', 'Percentage', 'Total Revenue'],
        'rows' => [],
        'distribution' => ['labels' => [], 'data' => []],
        'acquisition' => ['labels' => [], 'data' => []]
    ];
    
    try {
        $ranges = [
            '0-50000' => '0 - 50,000',
            '50001-100000' => '50,001 - 100,000',
            '100001-500000' => '100,001 - 500,000',
            '500001-1000000' => '500,001 - 1,000,000',
            '1000000+' => '1,000,000+'
        ];
        
        $total_guests = (int)db_fetch_value("
            SELECT COUNT(DISTINCT guest_id) FROM reservations 
            WHERE created_at BETWEEN ? AND ?
        ", [$date_from, $date_to]) ?: 0;
        
        $data['summary']['total_guests'] = $total_guests;
        
        foreach ($ranges as $key => $label) {
            list($min, $max) = explode('-', $key) + [null, null];
            
            if ($max) {
                $result = db_fetch_one("
                    SELECT 
                        COUNT(DISTINCT guest_id) as guests,
                        COALESCE(SUM(total_amount), 0) as revenue
                    FROM reservations 
                    WHERE created_at BETWEEN ? AND ?
                    AND total_amount BETWEEN ? AND ?
                ", [$date_from, $date_to, $min, $max]) ?: ['guests' => 0, 'revenue' => 0];
            } else {
                $min_val = str_replace('+', '', $min);
                $result = db_fetch_one("
                    SELECT 
                        COUNT(DISTINCT guest_id) as guests,
                        COALESCE(SUM(total_amount), 0) as revenue
                    FROM reservations 
                    WHERE created_at BETWEEN ? AND ?
                    AND total_amount >= ?
                ", [$date_from, $date_to, $min_val]) ?: ['guests' => 0, 'revenue' => 0];
            }
            
            $percentage = $total_guests > 0 ? round(($result['guests'] / $total_guests) * 100, 1) : 0;
            
            $data['rows'][] = [
                $label,
                $result['guests'],
                $percentage . '%',
                format_currency($result['revenue'])
            ];
            
            if ($result['guests'] > 0) {
                $data['distribution']['labels'][] = $label;
                $data['distribution']['data'][] = $result['guests'];
            }
        }
        
    } catch (Exception $e) {
        error_log("Error in spending report: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Export as PDF
 */
function export_pdf($data, $type, $date_from, $date_to) {
    header('Location: export-pdf.php?report=guest_analytics&type=' . $type . '&from=' . $date_from . '&to=' . $date_to);
    exit;
}

/**
 * Export as Excel
 */
function export_excel($data, $type, $date_from, $date_to) {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="guest_analytics_' . $type . '_' . $date_from . '_to_' . $date_to . '.xls"');
    
    echo "Guest Analytics Report\n";
    echo "Type: " . ucfirst(str_replace('_', ' ', $type)) . "\n";
    echo "Period: " . format_date($date_from) . " to " . format_date($date_to) . "\n\n";
    
    echo "Summary\n";
    echo "Total Guests\t" . ($data['summary']['total_guests'] ?? 0) . "\n";
    echo "New Guests\t" . ($data['summary']['new_guests'] ?? 0) . "\n";
    echo "Returning Guests\t" . ($data['summary']['returning_guests'] ?? 0) . "\n";
    echo "Average Stays\t" . ($data['summary']['avg_stays'] ?? 0) . "\n\n";
    
    if (!empty($data['headers']) && !empty($data['rows'])) {
        echo implode("\t", $data['headers']) . "\n";
        foreach ($data['rows'] as $row) {
            echo implode("\t", $row) . "\n";
        }
    }
    exit;
}

/**
 * Export as CSV
 */
function export_csv($data, $type, $date_from, $date_to) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="guest_analytics_' . $type . '_' . $date_from . '_to_' . $date_to . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, ['Guest Analytics Report']);
    fputcsv($output, ['Type:', ucfirst(str_replace('_', ' ', $type))]);
    fputcsv($output, ['Period:', format_date($date_from) . ' to ' . format_date($date_to)]);
    fputcsv($output, []);
    
    fputcsv($output, ['Summary']);
    fputcsv($output, ['Total Guests', $data['summary']['total_guests'] ?? 0]);
    fputcsv($output, ['New Guests', $data['summary']['new_guests'] ?? 0]);
    fputcsv($output, ['Returning Guests', $data['summary']['returning_guests'] ?? 0]);
    fputcsv($output, ['Average Stays', $data['summary']['avg_stays'] ?? 0]);
    fputcsv($output, []);
    
    if (!empty($data['headers']) && !empty($data['rows'])) {
        fputcsv($output, $data['headers']);
        foreach ($data['rows'] as $row) {
            fputcsv($output, $row);
        }
    }
    
    fclose($output);
    exit;
}

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