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

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

// Calculate the correct base path
// Current file: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/reports/revenue.php
// We need to go to: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/

$base_path = null;

// Method 1: Use dirname with correct levels
$base_path = dirname(__DIR__, 2); // Goes up 2 levels: reports/ -> HMSPOS/

// Verify the path exists
if (!file_exists($base_path . '/config/config.php')) {
    // If not found, try manual construction
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Final verification
if (!file_exists($base_path . '/config/config.php')) {
    die("Error: Cannot find config.php at: " . $base_path . "/config/config.php");
}

// Now require files with the correct path
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('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

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 '';
        $timestamp = strtotime($date);
        return $timestamp ? date($format, $timestamp) : $date;
    }
}

// Require authentication
require_auth();

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

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

// Get report parameters
$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');
$revenue_type = isset($_GET['revenue_type']) ? $_GET['revenue_type'] : 'all';
$export = isset($_GET['export']) ? $_GET['export'] : '';

// Get report data
$report_data = get_revenue_data($report_type, $date_from, $date_to, $revenue_type);

// Handle export
if ($export === 'pdf') {
    export_pdf($report_data, $report_type, $date_from, $date_to, $revenue_type);
} 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>
    <head>
        <title>Revenue 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">
    </head>
    <body>
        <div class="container-fluid mt-3">
    <?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">Revenue 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">Revenue</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>Report Type:</label>
                        <select class="form-select" name="type">
                            <option value="daily" <?php echo $report_type == 'daily' ? 'selected' : ''; ?>>Daily Revenue</option>
                            <option value="monthly" <?php echo $report_type == 'monthly' ? 'selected' : ''; ?>>Monthly Summary</option>
                            <option value="by_source" <?php echo $report_type == 'by_source' ? 'selected' : ''; ?>>By Source</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label>From:</label>
                        <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label>To:</label>
                        <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label>Revenue Type:</label>
                        <select class="form-select" name="revenue_type">
                            <option value="all" <?php echo $revenue_type == 'all' ? 'selected' : ''; ?>>All Revenue</option>
                            <option value="rooms" <?php echo $revenue_type == 'rooms' ? 'selected' : ''; ?>>Rooms Only</option>
                            <option value="fnb" <?php echo $revenue_type == 'fnb' ? 'selected' : ''; ?>>F&B Only</option>
                        </select>
                    </div>
                    
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">Generate</button>
                        <button type="button" class="btn btn-success me-2" onclick="exportReport('pdf')">PDF</button>
                        <button type="button" class="btn btn-info me-2" onclick="exportReport('excel')">Excel</button>
                        <button type="button" class="btn btn-secondary" onclick="exportReport('csv')">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 format_currency($report_data['summary']['total_revenue']); ?></h3>
                        <p>Total Revenue</p>
                    </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']['rooms_revenue']); ?></h3>
                        <p>Rooms Revenue</p>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo format_currency($report_data['summary']['fnb_revenue']); ?></h3>
                        <p>F&B Revenue</p>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo format_currency($report_data['summary']['avg_daily']); ?></h3>
                        <p>Avg Daily</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Data Table -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Revenue Data</h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($report_data['rows'])): ?>
                            <div class="alert alert-info m-3">
                                No revenue data found for the selected period.
                            </div>
                        <?php else: ?>
                            <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>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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

<?php
/**
 * Get revenue data
 */
function get_revenue_data($report_type, $date_from, $date_to, $revenue_type) {
    // Default structure
    $data = [
        'summary' => [
            'total_revenue' => 0,
            'avg_daily' => 0,
            'rooms_revenue' => 0,
            'fnb_revenue' => 0,
            'services_revenue' => 0,
            'other_revenue' => 0
        ],
        'headers' => ['Date', 'Rooms', 'F&B', 'Services', 'Other', 'Total'],
        'rows' => [],
        'chart' => ['labels' => [], 'data' => []],
        'totals' => []
    ];
    
    try {
        // Check if folio_charges table exists
        $table_check = db_fetch_value("SHOW TABLES LIKE 'folio_charges'");
        if (!$table_check) {
            error_log("Table 'folio_charges' does not exist");
            return $data;
        }
        
        $current = strtotime($date_from);
        $end = strtotime($date_to);
        $total_days = 0;
        
        while ($current <= $end) {
            $date = date('Y-m-d', $current);
            
            // Get rooms revenue
            $rooms_revenue = (float)db_fetch_value("
                SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
                WHERE charge_type = 'room' 
                AND DATE(posted_at) = ? 
                AND (is_voided = 0 OR is_voided IS NULL)
            ", [$date]);
            
            // Get F&B revenue
            $fnb_revenue = (float)db_fetch_value("
                SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
                WHERE charge_type = 'fnb' 
                AND DATE(posted_at) = ? 
                AND (is_voided = 0 OR is_voided IS NULL)
            ", [$date]);
            
            // Get services revenue
            $services_revenue = (float)db_fetch_value("
                SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
                WHERE charge_type = 'service' 
                AND DATE(posted_at) = ? 
                AND (is_voided = 0 OR is_voided IS NULL)
            ", [$date]);
            
            // Get other revenue
            $other_revenue = (float)db_fetch_value("
                SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
                WHERE charge_type NOT IN ('room', 'fnb', 'service', 'payment') 
                AND DATE(posted_at) = ? 
                AND (is_voided = 0 OR is_voided IS NULL)
            ", [$date]);
            
            $total = $rooms_revenue + $fnb_revenue + $services_revenue + $other_revenue;
            
            // Only add row if there's data
            if ($total > 0) {
                $data['rows'][] = [
                    format_date($date),
                    format_currency($rooms_revenue),
                    format_currency($fnb_revenue),
                    format_currency($services_revenue),
                    format_currency($other_revenue),
                    format_currency($total)
                ];
                
                $data['summary']['rooms_revenue'] += $rooms_revenue;
                $data['summary']['fnb_revenue'] += $fnb_revenue;
                $data['summary']['services_revenue'] += $services_revenue;
                $data['summary']['other_revenue'] += $other_revenue;
                $data['summary']['total_revenue'] += $total;
                
                $total_days++;
            }
            
            $current = strtotime('+1 day', $current);
        }
        
        $data['summary']['avg_daily'] = $total_days > 0 ? $data['summary']['total_revenue'] / $total_days : 0;
        
    } catch (Exception $e) {
        error_log("Error in get_revenue_data: " . $e->getMessage());
    }
    
    return $data;
}

/**
 * Export as PDF
 */
function export_pdf($data, $type, $date_from, $date_to, $revenue_type) {
    $params = 'report=revenue&type=' . urlencode($type) . 
              '&from=' . urlencode($date_from) . 
              '&to=' . urlencode($date_to) .
              '&revenue_type=' . urlencode($revenue_type);
    
    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="revenue_report_' . $type . '_' . $date_from . '_to_' . $date_to . '.xls"');
    
    echo "Revenue 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 Revenue\t" . format_currency($data['summary']['total_revenue']) . "\n";
    echo "Average Daily\t" . format_currency($data['summary']['avg_daily']) . "\n";
    echo "Rooms Revenue\t" . format_currency($data['summary']['rooms_revenue']) . "\n";
    echo "F&B Revenue\t" . format_currency($data['summary']['fnb_revenue']) . "\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="revenue_report_' . $type . '_' . $date_from . '_to_' . $date_to . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, ['Revenue 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 Revenue', format_currency($data['summary']['total_revenue'])]);
    fputcsv($output, ['Average Daily', format_currency($data['summary']['avg_daily'])]);
    fputcsv($output, ['Rooms Revenue', format_currency($data['summary']['rooms_revenue'])]);
    fputcsv($output, ['F&B Revenue', format_currency($data['summary']['fnb_revenue'])]);
    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></body></html>';
}
?>