<?php
require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/database.php';

function excelText($value) {
    $safe = str_replace('"', '""', (string)$value);
    return '="' . $safe . '"';
}

if (!isLoggedIn()) {
    http_response_code(401);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Unauthorized';
    exit();
}

$currentUser = getCurrentUser();
if (!isset($currentUser['user_type']) || !in_array($currentUser['user_type'], ['admin', 'staff'], true)) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Forbidden';
    exit();
}

$type = strtolower(trim((string)($_GET['type'] ?? '')));
if ($type !== 'revenue') {
    http_response_code(400);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Invalid report type';
    exit();
}

$invoiceType = strtolower(trim((string)($_GET['invoice_type'] ?? 'all')));
$allowedInvoiceTypes = ['all', 'room', 'service'];
if (!in_array($invoiceType, $allowedInvoiceTypes, true)) {
    $invoiceType = 'all';
}

$fileName = 'revenue-report-' . $invoiceType . '-' . date('Y-m-d-His') . '.csv';
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Pragma: no-cache');
header('Expires: 0');

$out = fopen('php://output', 'w');
if ($out === false) {
    http_response_code(500);
    exit();
}

// UTF-8 BOM for Excel compatibility
fwrite($out, "\xEF\xBB\xBF");

$roomBookingsTotal = 0.0;
$roomRevenueTotal = 0.0;
$serviceBookingsTotal = 0.0;
$serviceRevenueTotal = 0.0;

$roomResult = $conn->query("
    SELECT
        r.id,
        r.created_at,
        r.check_in_date,
        r.check_out_date,
        r.total_price,
        r.status,
        r.payment_status,
        u.first_name,
        u.last_name,
        rm.room_number,
        rm.room_type
    FROM reservations r
    LEFT JOIN users u ON u.id = r.user_id
    LEFT JOIN rooms rm ON rm.id = r.room_id
    ORDER BY r.created_at DESC
");

$serviceResult = $conn->query("
    SELECT
        sr.id,
        sr.created_at,
        sr.service_start_date,
        sr.service_end_date,
        sr.total_price,
        sr.status,
        sr.payment_status,
        u.first_name,
        u.last_name,
        f.name AS service_name
    FROM service_reservations sr
    LEFT JOIN users u ON u.id = sr.user_id
    LEFT JOIN facilities f ON f.id = sr.facility_id
    ORDER BY sr.created_at DESC
");

$roomRows = [];
if ($invoiceType !== 'service' && $roomResult) {
    while ($row = $roomResult->fetch_assoc()) {
        $amount = (float)($row['total_price'] ?? 0);
        $status = (string)($row['status'] ?? '');
        $roomBookingsTotal += $amount;
        if ($status !== 'cancelled') {
            $roomRevenueTotal += $amount;
        }
        $roomRows[] = $row;
    }
}

$serviceRows = [];
if ($invoiceType !== 'room' && $serviceResult) {
    while ($row = $serviceResult->fetch_assoc()) {
        $amount = (float)($row['total_price'] ?? 0);
        $status = (string)($row['status'] ?? '');
        $serviceBookingsTotal += $amount;
        if ($status !== 'cancelled') {
            $serviceRevenueTotal += $amount;
        }
        $serviceRows[] = $row;
    }
}

$overallBookingsTotal = $roomBookingsTotal + $serviceBookingsTotal;
$overallRevenueTotal = $roomRevenueTotal + $serviceRevenueTotal;
$invoiceTypeLabel = $invoiceType === 'all'
    ? 'All Invoices'
    : ($invoiceType === 'room' ? 'Room Invoices' : 'Service Invoices');

// Build a unified invoice list so download matches the invoice table view in admin.
$invoiceRows = [];
foreach ($roomRows as $row) {
    $guestName = trim(((string)($row['first_name'] ?? '')) . ' ' . ((string)($row['last_name'] ?? '')));
    $roomLabel = trim(((string)($row['room_number'] ?? '')) . ' (' . strtoupper((string)($row['room_type'] ?? '')) . ')');
    $invoiceRows[] = [
        'invoice_no' => 'INV-R-' . (string)($row['id'] ?? ''),
        'invoice_type' => 'Room Booking Invoice',
        'guest' => $guestName !== '' ? $guestName : 'N/A',
        'item' => $roomLabel !== '' ? $roomLabel : 'N/A',
        'dates' => (string)($row['check_in_date'] ?? '-') . ' to ' . (string)($row['check_out_date'] ?? '-'),
        'amount' => (float)($row['total_price'] ?? 0),
        'payment' => (string)($row['payment_status'] ?? 'unpaid'),
        'status' => (string)($row['status'] ?? 'pending'),
        'created' => (string)($row['created_at'] ?? '')
    ];
}

foreach ($serviceRows as $row) {
    $guestName = trim(((string)($row['first_name'] ?? '')) . ' ' . ((string)($row['last_name'] ?? '')));
    $invoiceRows[] = [
        'invoice_no' => 'INV-S-' . (string)($row['id'] ?? ''),
        'invoice_type' => 'Service Booking Invoice',
        'guest' => $guestName !== '' ? $guestName : 'N/A',
        'item' => (string)($row['service_name'] ?? 'Service'),
        'dates' => (string)($row['service_start_date'] ?? '-') . ' to ' . (string)($row['service_end_date'] ?? '-'),
        'amount' => (float)($row['total_price'] ?? 0),
        'payment' => (string)($row['payment_status'] ?? 'unpaid'),
        'status' => (string)($row['status'] ?? 'pending'),
        'created' => (string)($row['created_at'] ?? '')
    ];
}

usort($invoiceRows, static function ($a, $b) {
    $aTime = strtotime((string)($a['created'] ?? ''));
    $bTime = strtotime((string)($b['created'] ?? ''));
    return $bTime <=> $aTime;
});

fputcsv($out, ['Revenue Invoices']);
fputcsv($out, ['Generated At: ' . date('Y-m-d H:i:s')]);
fputcsv($out, ['Invoice Type: ' . $invoiceTypeLabel]);
fputcsv($out, ['Total Records: ' . count($invoiceRows)]);
fputcsv($out, []);
fputcsv($out, ['Invoice #', 'Invoice Type', 'Guest', 'Item', 'Dates', 'Amount', 'Payment', 'Status', 'Created Date', 'Created Time']);
foreach ($invoiceRows as $invoiceRow) {
    $createdAt = (string)$invoiceRow['created'];
    $createdDate = '-';
    $createdTime = '-';
    if ($createdAt !== '') {
        $createdDate = substr($createdAt, 0, 10);
        $createdTime = substr($createdAt, 11, 8);
    }

    $payment = ucwords(str_replace('_', ' ', (string)$invoiceRow['payment']));
    $status = ucwords(str_replace('_', ' ', (string)$invoiceRow['status']));

    fputcsv($out, [
        excelText((string)$invoiceRow['invoice_no']),
        excelText((string)$invoiceRow['invoice_type']),
        excelText((string)$invoiceRow['guest']),
        excelText((string)$invoiceRow['item']),
        excelText((string)$invoiceRow['dates']),
        '$' . number_format((float)$invoiceRow['amount'], 2, '.', ''),
        $payment,
        $status,
        excelText($createdDate),
        excelText($createdTime)
    ]);
}

fclose($out);
exit();
