<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * ADR & RevPAR Report
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('reports.view');

// Set page title
$page_title = 'ADR & RevPAR Report';

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

// Get report parameters
$report_type = $_GET['type'] ?? 'daily';
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$room_type_id = isset($_GET['room_type_id']) && $_GET['room_type_id'] !== '' ? (int)$_GET['room_type_id'] : null;
$export = $_GET['export'] ?? '';

// Get room types for filter
$room_types = db_fetch_all("SELECT room_type_id, type_name FROM room_types ORDER BY type_name");

// Get report data based on type
switch ($report_type) {
    case 'daily':
        $report_data = get_daily_adr_revpar($date_from, $date_to, $room_type_id);
        break;
    case 'monthly':
        $report_data = get_monthly_adr_revpar($date_from, $date_to, $room_type_id);
        break;
    case 'comparison':
        $report_data = get_comparison_adr_revpar($date_from, $date_to, $room_type_id);
        break;
    default:
        $report_data = get_daily_adr_revpar($date_from, $date_to, $room_type_id);
}

// 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
require_once dirname(__DIR__, 2) . '/views/partials/header.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">ADR & RevPAR Report</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="dashboard.php">Reports</a></li>
                    <li class="breadcrumb-item active">ADR/RevPAR</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="form-inline">
                    <div class="form-group mb-2 mr-2">
                        <label for="report_type" class="mr-2">Report Type:</label>
                        <select class="form-control" id="report_type" name="type">
                            <option value="daily" <?php echo $report_type == 'daily' ? 'selected' : ''; ?>>Daily ADR/RevPAR</option>
                            <option value="monthly" <?php echo $report_type == 'monthly' ? 'selected' : ''; ?>>Monthly Summary</option>
                            <option value="comparison" <?php echo $report_type == 'comparison' ? 'selected' : ''; ?>>Year-over-Year Comparison</option>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="date_from" class="mr-2">From:</label>
                        <input type="date" class="form-control" id="date_from" name="date_from" 
                               value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="date_to" class="mr-2">To:</label>
                        <input type="date" class="form-control" id="date_to" name="date_to" 
                               value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="room_type_id" class="mr-2">Room Type:</label>
                        <select class="form-control" id="room_type_id" name="room_type_id">
                            <option value="">All Types</option>
                            <?php foreach ($room_types as $type): ?>
                                <option value="<?php echo $type['room_type_id']; ?>" 
                                        <?php echo $room_type_id == $type['room_type_id'] ? 'selected' : ''; ?>>
                                    <?php echo $type['type_name']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary mb-2 mr-2">
                        <i class="fas fa-sync-alt"></i> Generate
                    </button>
                    
                    <button type="button" class="btn btn-success mb-2 mr-2" onclick="exportReport('pdf')">
                        <i class="fas fa-file-pdf"></i> PDF
                    </button>
                    
                    <button type="button" class="btn btn-info mb-2 mr-2" onclick="exportReport('excel')">
                        <i class="fas fa-file-excel"></i> Excel
                    </button>
                    
                    <button type="button" class="btn btn-secondary mb-2" onclick="exportReport('csv')">
                        <i class="fas fa-file-csv"></i> CSV
                    </button>
                </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 format_currency($report_data['summary']['avg_adr']); ?></h3>
                        <p>Average ADR</p>
                    </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-success">
                    <div class="inner">
                        <h3><?php echo format_currency($report_data['summary']['avg_revpar']); ?></h3>
                        <p>Average RevPAR</p>
                    </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-warning">
                    <div class="inner">
                        <h3><?php echo $report_data['summary']['avg_occupancy']; ?>%</h3>
                        <p>Average Occupancy</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-bed"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $report_data['summary']['peak_adr']; ?></h3>
                        <p>Peak ADR</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            ADR Trend
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="adrChart" 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-line mr-1"></i>
                            RevPAR Trend
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="revparChart" style="height: 300px;"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 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 mr-1"></i>
                            <?php echo ucfirst($report_type); ?> Data
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <?php foreach ($report_data['headers'] as $header): ?>
                                            <th><?php echo $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>
                                <?php if (!empty($report_data['totals'])): ?>
                                <tfoot>
                                    <tr class="table-active">
                                        <?php foreach ($report_data['totals'] as $total): ?>
                                            <td><strong><?php echo $total; ?></strong></td>
                                        <?php endforeach; ?>
                                    </tr>
                                </tfoot>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Comparison Section (for year-over-year) -->
        <?php if ($report_type == 'comparison'): ?>
        <div class="row mt-4">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar mr-1"></i>
                            Year-over-Year Comparison
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h5>ADR Comparison</h5>
                                <canvas id="adrComparisonChart" style="height: 300px;"></canvas>
                            </div>
                            <div class="col-md-6">
                                <h5>RevPAR Comparison</h5>
                                <canvas id="revparComparisonChart" style="height: 300px;"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </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() {
    // ADR Chart
    const adrCtx = document.getElementById('adrChart').getContext('2d');
    
    new Chart(adrCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($report_data['chart']['adr_labels']); ?>,
            datasets: [{
                label: 'ADR',
                data: <?php echo json_encode($report_data['chart']['adr_data']); ?>,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '<?php echo CURRENCY_SYMBOL; ?>' + value;
                        }
                    }
                }
            }
        }
    });
    
    // RevPAR Chart
    const revparCtx = document.getElementById('revparChart').getContext('2d');
    
    new Chart(revparCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($report_data['chart']['revpar_labels']); ?>,
            datasets: [{
                label: 'RevPAR',
                data: <?php echo json_encode($report_data['chart']['revpar_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: {
                        callback: function(value) {
                            return '<?php echo CURRENCY_SYMBOL; ?>' + value;
                        }
                    }
                }
            }
        }
    });
    
    <?php if ($report_type == 'comparison'): ?>
    // ADR Comparison Chart
    const adrCompCtx = document.getElementById('adrComparisonChart').getContext('2d');
    
    new Chart(adrCompCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($report_data['comparison']['labels']); ?>,
            datasets: [
                {
                    label: 'Current Period',
                    data: <?php echo json_encode($report_data['comparison']['adr_current']); ?>,
                    backgroundColor: '#007bff'
                },
                {
                    label: 'Previous Period',
                    data: <?php echo json_encode($report_data['comparison']['adr_previous']); ?>,
                    backgroundColor: '#6c757d'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '<?php echo CURRENCY_SYMBOL; ?>' + value;
                        }
                    }
                }
            }
        }
    });
    
    // RevPAR Comparison Chart
    const revparCompCtx = document.getElementById('revparComparisonChart').getContext('2d');
    
    new Chart(revparCompCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($report_data['comparison']['labels']); ?>,
            datasets: [
                {
                    label: 'Current Period',
                    data: <?php echo json_encode($report_data['comparison']['revpar_current']); ?>,
                    backgroundColor: '#28a745'
                },
                {
                    label: 'Previous Period',
                    data: <?php echo json_encode($report_data['comparison']['revpar_previous']); ?>,
                    backgroundColor: '#6c757d'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '<?php echo CURRENCY_SYMBOL; ?>' + value;
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
});

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

<?php
/**
 * Get daily ADR and RevPAR data
 */
function get_daily_adr_revpar($date_from, $date_to, $room_type_id = null) {
    $data = [
        'summary' => [
            'avg_adr' => 0,
            'avg_revpar' => 0,
            'avg_occupancy' => 0,
            'peak_adr' => 0
        ],
        'headers' => ['Date', 'Occupied Rooms', 'Total Revenue', 'ADR', 'RevPAR', 'Occupancy %'],
        'rows' => [],
        'chart' => [
            'adr_labels' => [],
            'adr_data' => [],
            'revpar_labels' => [],
            'revpar_data' => []
        ]
    ];
    
    // Get total rooms
    $total_rooms_sql = "SELECT COUNT(*) FROM rooms WHERE is_active = 1";
    if ($room_type_id) {
        $total_rooms_sql .= " AND room_type_id = $room_type_id";
    }
    $total_rooms = db_fetch_value($total_rooms_sql);
    
    $current = strtotime($date_from);
    $end = strtotime($date_to);
    
    $total_revenue = 0;
    $total_room_nights = 0;
    $days = 0;
    
    while ($current <= $end) {
        $date = date('Y-m-d', $current);
        
        // Get occupied rooms for this date
        $occupied_sql = "
            SELECT COUNT(DISTINCT room_id) 
            FROM reservations 
            WHERE check_in_date <= ? AND check_out_date > ? 
            AND booking_status IN ('confirmed', 'checked_in')
        ";
        $params = [$date, $date];
        
        if ($room_type_id) {
            $occupied_sql .= " AND room_type_id = ?";
            $params[] = $room_type_id;
        }
        
        $occupied = db_fetch_value($occupied_sql, $params);
        
        // Get room revenue for this date
        $revenue_sql = "
            SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
            WHERE charge_type = 'room' AND DATE(posted_at) = ? AND is_voided = 0
        ";
        if ($room_type_id) {
            $revenue_sql = "
                SELECT COALESCE(SUM(fc.amount), 0) 
                FROM folio_charges fc
                JOIN reservations r ON fc.reservation_id = r.reservation_id
                WHERE fc.charge_type = 'room' 
                AND DATE(fc.posted_at) = ? 
                AND fc.is_voided = 0
                AND r.room_type_id = ?
            ";
            $params = [$date, $room_type_id];
        } else {
            $params = [$date];
        }
        
        $revenue = db_fetch_value($revenue_sql, $params);
        
        $adr = $occupied > 0 ? round($revenue / $occupied, 2) : 0;
        $revpar = $total_rooms > 0 ? round($revenue / $total_rooms, 2) : 0;
        $occupancy_rate = $total_rooms > 0 ? round(($occupied / $total_rooms) * 100, 1) : 0;
        
        $data['rows'][] = [
            format_date($date),
            $occupied,
            format_currency($revenue),
            format_currency($adr),
            format_currency($revpar),
            $occupancy_rate . '%'
        ];
        
        $data['chart']['adr_labels'][] = date('M d', $current);
        $data['chart']['adr_data'][] = $adr;
        $data['chart']['revpar_labels'][] = date('M d', $current);
        $data['chart']['revpar_data'][] = $revpar;
        
        $total_revenue += $revenue;
        $total_room_nights += $occupied;
        $data['summary']['peak_adr'] = max($data['summary']['peak_adr'], $adr);
        
        $days++;
        $current = strtotime('+1 day', $current);
    }
    
    $data['summary']['avg_adr'] = $total_room_nights > 0 ? round($total_revenue / $total_room_nights, 2) : 0;
    $data['summary']['avg_revpar'] = $days > 0 ? round($total_revenue / ($days * $total_rooms), 2) : 0;
    $data['summary']['avg_occupancy'] = ($days * $total_rooms) > 0 ? round(($total_room_nights / ($days * $total_rooms)) * 100, 1) : 0;
    
    return $data;
}

/**
 * Get monthly ADR and RevPAR data
 */
function get_monthly_adr_revpar($date_from, $date_to, $room_type_id = null) {
    $data = [
        'summary' => [
            'avg_adr' => 0,
            'avg_revpar' => 0,
            'avg_occupancy' => 0,
            'peak_adr' => 0
        ],
        'headers' => ['Month', 'Room Nights', 'Revenue', 'ADR', 'RevPAR', 'Occupancy %'],
        'rows' => [],
        'chart' => [
            'adr_labels' => [],
            'adr_data' => [],
            'revpar_labels' => [],
            'revpar_data' => []
        ]
    ];
    
    // Get total rooms
    $total_rooms_sql = "SELECT COUNT(*) FROM rooms WHERE is_active = 1";
    if ($room_type_id) {
        $total_rooms_sql .= " AND room_type_id = $room_type_id";
    }
    $total_rooms = db_fetch_value($total_rooms_sql);
    
    $current = strtotime($date_from);
    $end = strtotime($date_to);
    
    $total_revenue = 0;
    $total_room_nights = 0;
    $months = 0;
    
    while ($current <= $end) {
        $month_start = date('Y-m-01', $current);
        $month_end = date('Y-m-t', $current);
        $month_name = date('F Y', $current);
        $days_in_month = date('t', $current);
        
        // Get room nights for month
        $room_nights_sql = "
            SELECT COALESCE(SUM(
                DATEDIFF(
                    LEAST(check_out_date, ?),
                    GREATEST(check_in_date, ?)
                )
            ), 0)
            FROM reservations 
            WHERE check_in_date < ? AND check_out_date > ? 
            AND booking_status IN ('confirmed', 'checked_in')
        ";
        $params = [$month_end, $month_start, $month_end, $month_start];
        
        if ($room_type_id) {
            $room_nights_sql .= " AND room_type_id = ?";
            $params[] = $room_type_id;
        }
        
        $room_nights = db_fetch_value($room_nights_sql, $params);
        
        // Get revenue for month
        $revenue_sql = "
            SELECT COALESCE(SUM(fc.amount), 0) 
            FROM folio_charges fc
            JOIN reservations r ON fc.reservation_id = r.reservation_id
            WHERE fc.charge_type = 'room' 
            AND DATE(fc.posted_at) BETWEEN ? AND ? 
            AND fc.is_voided = 0
        ";
        $params = [$month_start, $month_end];
        
        if ($room_type_id) {
            $revenue_sql .= " AND r.room_type_id = ?";
            $params[] = $room_type_id;
        }
        
        $revenue = db_fetch_value($revenue_sql, $params);
        
        $adr = $room_nights > 0 ? round($revenue / $room_nights, 2) : 0;
        $revpar = ($total_rooms * $days_in_month) > 0 ? round($revenue / ($total_rooms * $days_in_month), 2) : 0;
        $occupancy_rate = ($total_rooms * $days_in_month) > 0 ? round(($room_nights / ($total_rooms * $days_in_month)) * 100, 1) : 0;
        
        $data['rows'][] = [
            $month_name,
            $room_nights,
            format_currency($revenue),
            format_currency($adr),
            format_currency($revpar),
            $occupancy_rate . '%'
        ];
        
        $data['chart']['adr_labels'][] = date('M Y', $current);
        $data['chart']['adr_data'][] = $adr;
        $data['chart']['revpar_labels'][] = date('M Y', $current);
        $data['chart']['revpar_data'][] = $revpar;
        
        $total_revenue += $revenue;
        $total_room_nights += $room_nights;
        $data['summary']['peak_adr'] = max($data['summary']['peak_adr'], $adr);
        
        $months++;
        $current = strtotime('+1 month', $current);
    }
    
    $total_available_nights = $total_rooms * array_sum(array_map(function($date) {
        return date('t', strtotime($date));
    }, array_column($data['rows'], 0)));
    
    $data['summary']['avg_adr'] = $total_room_nights > 0 ? round($total_revenue / $total_room_nights, 2) : 0;
    $data['summary']['avg_revpar'] = $total_available_nights > 0 ? round($total_revenue / $total_available_nights, 2) : 0;
    $data['summary']['avg_occupancy'] = $total_available_nights > 0 ? round(($total_room_nights / $total_available_nights) * 100, 1) : 0;
    
    return $data;
}

/**
 * Get year-over-year comparison
 */
function get_comparison_adr_revpar($date_from, $date_to, $room_type_id = null) {
    $current_data = get_monthly_adr_revpar($date_from, $date_to, $room_type_id);
    
    // Calculate previous year dates
    $prev_date_from = date('Y-m-d', strtotime($date_from . ' -1 year'));
    $prev_date_to = date('Y-m-d', strtotime($date_to . ' -1 year'));
    $previous_data = get_monthly_adr_revpar($prev_date_from, $prev_date_to, $room_type_id);
    
    $data = $current_data;
    $data['comparison'] = [
        'labels' => $current_data['chart']['adr_labels'],
        'adr_current' => $current_data['chart']['adr_data'],
        'adr_previous' => $previous_data['chart']['adr_data'],
        'revpar_current' => $current_data['chart']['revpar_data'],
        'revpar_previous' => $previous_data['chart']['revpar_data']
    ];
    
    return $data;
}

/**
 * Export as PDF
 */
function export_pdf($data, $type, $date_from, $date_to) {
    header('Location: export-pdf.php?report=adr_revpar&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="adr_revpar_report_' . $type . '_' . $date_from . '_to_' . $date_to . '.xls"');
    
    echo "ADR & RevPAR Report\n";
    echo "Type: " . ucfirst($type) . "\n";
    echo "Period: " . format_date($date_from) . " to " . format_date($date_to) . "\n\n";
    
    echo "Summary\n";
    echo "Average ADR\t" . format_currency($data['summary']['avg_adr']) . "\n";
    echo "Average RevPAR\t" . format_currency($data['summary']['avg_revpar']) . "\n";
    echo "Average Occupancy\t" . $data['summary']['avg_occupancy'] . "%\n";
    echo "Peak ADR\t" . format_currency($data['summary']['peak_adr']) . "\n\n";
    
    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="adr_revpar_report_' . $type . '_' . $date_from . '_to_' . $date_to . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, ['ADR & RevPAR Report']);
    fputcsv($output, ['Type:', ucfirst($type)]);
    fputcsv($output, ['Period:', format_date($date_from) . ' to ' . format_date($date_to)]);
    fputcsv($output, []);
    
    fputcsv($output, ['Summary']);
    fputcsv($output, ['Average ADR', format_currency($data['summary']['avg_adr'])]);
    fputcsv($output, ['Average RevPAR', format_currency($data['summary']['avg_revpar'])]);
    fputcsv($output, ['Average Occupancy', $data['summary']['avg_occupancy'] . '%']);
    fputcsv($output, ['Peak ADR', format_currency($data['summary']['peak_adr'])]);
    fputcsv($output, []);
    
    fputcsv($output, $data['headers']);
    foreach ($data['rows'] as $row) {
        fputcsv($output, $row);
    }
    
    fclose($output);
    exit;
}

// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>