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

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

// Calculate the correct base path
$base_path = null;

// Method 1: Try going up 2 levels from current file
// Current file: /HMSPOS/reports/occupancy.php
$base_path = dirname(__DIR__, 2);

// Method 2: Manual calculation if method 1 fails
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(__DIR__));
}

// Method 3: Absolute path as last resort (adjust this to your actual path)
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Verify the base path works
if (!file_exists($base_path . '/config/config.php')) {
    die("Error: Cannot find system files at: " . $base_path . "/config/config.php");
}

// Initialize system
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/constants.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Load csrf if it exists
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}

// Define helper functions if they don't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        return '';
    }
}

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

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

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

// Require authentication and permission
require_auth();

// Check if permission function exists
if (function_exists('require_permission')) {
    require_permission('reports.view');
}

// Set page title
$page_title = 'Occupancy Report';

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

// Get report parameters with validation
$report_type = isset($_GET['type']) ? $_GET['type'] : 'daily';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-d', strtotime('-30 days'));
$date_to = isset($_GET['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 = isset($_GET['export']) ? $_GET['export'] : '';

// Get room types for filter with error handling
$room_types = [];
try {
    $room_types = db_fetch_all("SELECT room_type_id, type_name FROM room_types ORDER BY type_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
    $room_types = [];
}

// Get report data based on type with error handling
$report_data = [
    'summary' => [
        'avg_occupancy' => 0,
        'total_room_nights' => 0,
        'peak_occupancy' => 0,
        'total_available' => 0
    ],
    'headers' => ['Date', 'Available Rooms', 'Occupied Rooms', 'Occupancy %', 'Room Nights'],
    'rows' => [],
    'chart' => ['labels' => [], 'data' => []]
];

try {
    switch ($report_type) {
        case 'daily':
            $report_data = get_daily_occupancy($date_from, $date_to, $room_type_id);
            break;
        case 'monthly':
            $report_data = get_monthly_occupancy($date_from, $date_to, $room_type_id);
            break;
        case 'room_type':
            $report_data = get_room_type_occupancy($date_from, $date_to, $room_type_id);
            break;
        case 'forecast':
            $report_data = get_occupancy_forecast($date_from, $date_to, $room_type_id);
            break;
        default:
            $report_data = get_daily_occupancy($date_from, $date_to, $room_type_id);
    }
} catch (Exception $e) {
    error_log("Error generating report: " . $e->getMessage());
    // Keep default empty data structure
}

// Handle export
if ($export === 'pdf') {
    export_pdf($report_data, $report_type, $date_from, $date_to, $room_type_id);
} 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 - check multiple possible locations
$header_paths = [
    $base_path . '/views/partials/header.php',
    $base_path . '/includes/header.php',
    dirname(__DIR__, 2) . '/views/partials/header.php'
];

$header_found = false;
foreach ($header_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $header_found = true;
        break;
    }
}

if (!$header_found) {
    // 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>Occupancy Report</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; display: block; }
            .small-box > .inner { padding: 10px; }
            .small-box h3 { font-size: 2.2rem; font-weight: bold; margin: 0 0 10px 0; white-space: nowrap; padding: 0; }
            .small-box p { font-size: 1rem; }
            .small-box .icon { position: absolute; top: 10px; right: 10px; z-index: 0; font-size: 70px; color: rgba(0,0,0,0.15); }
            .bg-info { background-color: #007bff !important; color: #fff; }
            .bg-success { background-color: #28a745 !important; color: #fff; }
            .bg-warning { background-color: #ffc107 !important; color: #1f2d3d; }
            .bg-danger { background-color: #dc3545 !important; color: #fff; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Ruhondo Beach Resort</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="<?php echo base_url('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">Occupancy Report</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('public/dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="dashboard.php">Reports</a></li>
                    <li class="breadcrumb-item active">Occupancy</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-2">
                        <label for="report_type" class="form-label">Report Type:</label>
                        <select class="form-select" id="report_type" name="type">
                            <option value="daily" <?php echo $report_type == 'daily' ? 'selected' : ''; ?>>Daily Occupancy</option>
                            <option value="monthly" <?php echo $report_type == 'monthly' ? 'selected' : ''; ?>>Monthly Summary</option>
                            <option value="room_type" <?php echo $report_type == 'room_type' ? 'selected' : ''; ?>>By Room Type</option>
                            <option value="forecast" <?php echo $report_type == 'forecast' ? 'selected' : ''; ?>>Occupancy Forecast</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label for="date_from" class="form-label">From:</label>
                        <input type="date" class="form-control" id="date_from" name="date_from" 
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label for="date_to" class="form-label">To:</label>
                        <input type="date" class="form-control" id="date_to" name="date_to" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label for="room_type_id" class="form-label">Room Type:</label>
                        <select class="form-select" 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 htmlspecialchars($type['type_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-4 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 isset($report_data['summary']['avg_occupancy']) ? $report_data['summary']['avg_occupancy'] : 0; ?>%</h3>
                        <p>Average Occupancy</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 isset($report_data['summary']['total_room_nights']) ? $report_data['summary']['total_room_nights'] : 0; ?></h3>
                        <p>Room Nights Sold</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-warning">
                    <div class="inner">
                        <h3><?php echo isset($report_data['summary']['peak_occupancy']) ? $report_data['summary']['peak_occupancy'] : 0; ?>%</h3>
                        <p>Peak Occupancy</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo isset($report_data['summary']['total_available']) ? $report_data['summary']['total_available'] : 0; ?></h3>
                        <p>Total Available</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-door-open"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chart -->
        <?php if (!empty($report_data['chart']['labels']) && !empty($report_data['chart']['data'])): ?>
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            Occupancy Trend
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="occupancyChart" 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 mr-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 htmlspecialchars($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['chart']['labels']) && !empty($report_data['chart']['data'])): ?>
    // Occupancy Chart
    const ctx = document.getElementById('occupancyChart').getContext('2d');
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($report_data['chart']['labels']); ?>,
            datasets: [{
                label: 'Occupancy %',
                data: <?php echo json_encode($report_data['chart']['data']); ?>,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        callback: function(value) {
                            return 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 occupancy data
 */
function get_daily_occupancy($date_from, $date_to, $room_type_id = null) {
    $data = [
        'summary' => [
            'avg_occupancy' => 0,
            'total_room_nights' => 0,
            'peak_occupancy' => 0,
            'total_available' => 0
        ],
        'headers' => ['Date', 'Available Rooms', 'Occupied Rooms', 'Occupancy %', 'Room Nights'],
        'rows' => [],
        'chart' => ['labels' => [], 'data' => []]
    ];
    
    try {
        // Get total rooms
        $total_rooms_sql = "SELECT COUNT(*) FROM rooms WHERE is_active = 1";
        $params = [];
        
        if ($room_type_id) {
            $total_rooms_sql .= " AND room_type_id = ?";
            $params[] = $room_type_id;
        }
        
        $total_rooms = (int)db_fetch_value($total_rooms_sql, $params);
        if ($total_rooms === null) $total_rooms = 0;
        
        $data['summary']['total_available'] = $total_rooms;
        
        // Generate date range
        $current = strtotime($date_from);
        $end = strtotime($date_to);
        
        $days = 0;
        
        while ($current <= $end) {
            $days++;
            $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 = (int)db_fetch_value($occupied_sql, $params);
            $available = max(0, $total_rooms - $occupied);
            $occupancy_rate = $total_rooms > 0 ? round(($occupied / $total_rooms) * 100, 1) : 0;
            
            $data['rows'][] = [
                format_date($date),
                $available,
                $occupied,
                $occupancy_rate . '%',
                $occupied
            ];
            
            $data['chart']['labels'][] = date('M d', $current);
            $data['chart']['data'][] = $occupancy_rate;
            
            $data['summary']['total_room_nights'] += $occupied;
            $data['summary']['peak_occupancy'] = max($data['summary']['peak_occupancy'], $occupancy_rate);
            
            $current = strtotime('+1 day', $current);
        }
        
        $data['summary']['avg_occupancy'] = $days > 0 && $total_rooms > 0 ? 
            round(($data['summary']['total_room_nights'] / ($days * $total_rooms)) * 100, 1) : 0;
        
    } catch (Exception $e) {
        error_log("Error in daily occupancy: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Get monthly occupancy data
 */
function get_monthly_occupancy($date_from, $date_to, $room_type_id = null) {
    $data = [
        'summary' => [
            'avg_occupancy' => 0,
            'total_room_nights' => 0,
            'peak_occupancy' => 0,
            'total_available' => 0
        ],
        'headers' => ['Month', 'Available Rooms', 'Occupied Rooms', 'Occupancy %', 'Room Nights'],
        'rows' => [],
        'chart' => ['labels' => [], 'data' => []]
    ];
    
    try {
        // Get total rooms
        $total_rooms_sql = "SELECT COUNT(*) FROM rooms WHERE is_active = 1";
        $params = [];
        
        if ($room_type_id) {
            $total_rooms_sql .= " AND room_type_id = ?";
            $params[] = $room_type_id;
        }
        
        $total_rooms = (int)db_fetch_value($total_rooms_sql, $params);
        if ($total_rooms === null) $total_rooms = 0;
        
        $data['summary']['total_available'] = $total_rooms;
        
        // Group by month
        $current = strtotime($date_from);
        $end = strtotime($date_to);
        
        while ($current <= $end) {
            $month_start = date('Y-m-01', $current);
            $month_end = date('Y-m-t', $current);
            $month_name = date('F Y', $current);
            
            // Get occupied room nights for the month
            $occupied_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) {
                $occupied_sql .= " AND room_type_id = ?";
                $params[] = $room_type_id;
            }
            
            $room_nights = (int)db_fetch_value($occupied_sql, $params);
            $days_in_month = date('t', $current);
            $available_room_nights = $total_rooms * $days_in_month;
            $occupancy_rate = $available_room_nights > 0 ? round(($room_nights / $available_room_nights) * 100, 1) : 0;
            
            $data['rows'][] = [
                $month_name,
                number_format($available_room_nights - $room_nights),
                number_format($room_nights),
                $occupancy_rate . '%',
                number_format($room_nights)
            ];
            
            $data['chart']['labels'][] = date('M Y', $current);
            $data['chart']['data'][] = $occupancy_rate;
            
            $data['summary']['total_room_nights'] += $room_nights;
            $data['summary']['peak_occupancy'] = max($data['summary']['peak_occupancy'], $occupancy_rate);
            
            $current = strtotime('+1 month', $current);
        }
        
        $months = count($data['rows']);
        $total_available_nights = 0;
        $temp_current = strtotime($date_from);
        while ($temp_current <= $end) {
            $days_in_month = date('t', $temp_current);
            $total_available_nights += $total_rooms * $days_in_month;
            $temp_current = strtotime('+1 month', $temp_current);
        }
        
        $data['summary']['avg_occupancy'] = $total_available_nights > 0 ? 
            round(($data['summary']['total_room_nights'] / $total_available_nights) * 100, 1) : 0;
        
    } catch (Exception $e) {
        error_log("Error in monthly occupancy: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Get room type occupancy data
 */
function get_room_type_occupancy($date_from, $date_to, $room_type_id = null) {
    $data = [
        'summary' => [
            'avg_occupancy' => 0,
            'total_room_nights' => 0,
            'peak_occupancy' => 0,
            'total_available' => 0
        ],
        'headers' => ['Room Type', 'Total Rooms', 'Room Nights', 'Occupancy %', 'Revenue', 'ADR'],
        'rows' => [],
        'chart' => ['labels' => [], 'data' => []]
    ];
    
    try {
        // Get room types
        $type_sql = "SELECT room_type_id, type_name FROM room_types";
        $type_params = [];
        
        if ($room_type_id) {
            $type_sql .= " WHERE room_type_id = ?";
            $type_params[] = $room_type_id;
        }
        
        $room_types = db_fetch_all($type_sql, $type_params) ?: [];
        
        $total_room_nights_all = 0;
        $total_available_nights_all = 0;
        $days_in_period = (strtotime($date_to) - strtotime($date_from)) / 86400 + 1;
        
        foreach ($room_types as $type) {
            // Get total rooms of this type
            $total_rooms = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE room_type_id = ? AND is_active = 1", [$type['room_type_id']]);
            
            // Get occupied room nights
            $occupied_sql = "
                SELECT COALESCE(SUM(
                    DATEDIFF(
                        LEAST(check_out_date, ?),
                        GREATEST(check_in_date, ?)
                    )
                ), 0)
                FROM reservations 
                WHERE room_type_id = ?
                AND check_in_date < ? AND check_out_date > ? 
                AND booking_status IN ('confirmed', 'checked_in')
            ";
            $room_nights = (int)db_fetch_value($occupied_sql, [$date_to, $date_from, $type['room_type_id'], $date_to, $date_from]);
            
            // Get revenue
            $revenue_sql = "
                SELECT COALESCE(SUM(total_amount), 0)
                FROM reservations 
                WHERE room_type_id = ?
                AND check_in_date >= ? AND check_out_date <= ?
                AND booking_status IN ('checked_in', 'checked_out')
            ";
            $revenue = (float)db_fetch_value($revenue_sql, [$type['room_type_id'], $date_from, $date_to]);
            
            $available_nights = $total_rooms * $days_in_period;
            $occupancy_rate = $available_nights > 0 ? round(($room_nights / $available_nights) * 100, 1) : 0;
            $adr = $room_nights > 0 ? round($revenue / $room_nights, 2) : 0;
            
            $data['rows'][] = [
                $type['type_name'],
                $total_rooms,
                number_format($room_nights),
                $occupancy_rate . '%',
                format_currency($revenue),
                format_currency($adr)
            ];
            
            $data['chart']['labels'][] = $type['type_name'];
            $data['chart']['data'][] = $occupancy_rate;
            
            $total_room_nights_all += $room_nights;
            $total_available_nights_all += $available_nights;
        }
        
        $data['summary']['total_room_nights'] = $total_room_nights_all;
        $data['summary']['avg_occupancy'] = $total_available_nights_all > 0 ? 
            round(($total_room_nights_all / $total_available_nights_all) * 100, 1) : 0;
        
        // Calculate peak occupancy from rows
        $peak = 0;
        foreach ($data['rows'] as $row) {
            $occ_percent = (float)str_replace('%', '', $row[3]);
            if ($occ_percent > $peak) {
                $peak = $occ_percent;
            }
        }
        $data['summary']['peak_occupancy'] = $peak;
        
    } catch (Exception $e) {
        error_log("Error in room type occupancy: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Get occupancy forecast
 */
function get_occupancy_forecast($date_from, $date_to, $room_type_id = null) {
    // Similar to daily occupancy but includes future bookings
    $data = get_daily_occupancy($date_from, $date_to, $room_type_id);
    $data['headers'][0] = 'Date (Forecast)';
    return $data;
}

/**
 * Export as PDF
 */
function export_pdf($data, $type, $date_from, $date_to, $room_type_id = null) {
    $params = 'report=occupancy&type=' . urlencode($type) . 
              '&from=' . urlencode($date_from) . 
              '&to=' . urlencode($date_to);
    
    if ($room_type_id) {
        $params .= '&room_type_id=' . $room_type_id;
    }
    
    header('Location: export-pdf.php?' . $params);
    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="occupancy_report_' . $type . '_' . $date_from . '_to_' . $date_to . '.xls"');
    
    echo "Occupancy 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 "Average Occupancy\t" . ($data['summary']['avg_occupancy'] ?? 0) . "%\n";
    echo "Total Room Nights\t" . ($data['summary']['total_room_nights'] ?? 0) . "\n";
    echo "Peak Occupancy\t" . ($data['summary']['peak_occupancy'] ?? 0) . "%\n";
    echo "Total Available\t" . ($data['summary']['total_available'] ?? 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="occupancy_report_' . $type . '_' . $date_from . '_to_' . $date_to . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, ['Occupancy 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, ['Average Occupancy', ($data['summary']['avg_occupancy'] ?? 0) . '%']);
    fputcsv($output, ['Total Room Nights', $data['summary']['total_room_nights'] ?? 0]);
    fputcsv($output, ['Peak Occupancy', ($data['summary']['peak_occupancy'] ?? 0) . '%']);
    fputcsv($output, ['Total Available', $data['summary']['total_available'] ?? 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 - check multiple possible locations
$footer_paths = [
    $base_path . '/views/partials/footer.php',
    $base_path . '/includes/footer.php',
    dirname(__DIR__, 2) . '/views/partials/footer.php'
];

$footer_found = false;
foreach ($footer_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $footer_found = true;
        break;
    }
}

if (!$footer_found) {
    echo '</div></div></body></html>';
}
?>