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

if (!isLoggedIn()) {
    http_response_code(401);
    echo 'Unauthorized';
    exit();
}

$currentUser = getCurrentUser();
if (!isset($currentUser['user_type']) || !in_array($currentUser['user_type'], ['admin', 'staff'], true)) {
    http_response_code(403);
    echo 'Forbidden';
    exit();
}

$type = strtolower(trim((string)($_GET['type'] ?? '')));
if ($type !== 'revenue') {
    http_response_code(400);
    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';
}

$autoPrint = isset($_GET['autoprint']) && $_GET['autoprint'] === '1';

$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
");

$invoiceRows = [];

if ($invoiceType !== 'service' && $roomResult) {
    while ($row = $roomResult->fetch_assoc()) {
        $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',
            'invoice_category' => 'room',
            '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'] ?? '')
        ];
    }
}

if ($invoiceType !== 'room' && $serviceResult) {
    while ($row = $serviceResult->fetch_assoc()) {
        $guestName = trim(((string)($row['first_name'] ?? '')) . ' ' . ((string)($row['last_name'] ?? '')));
        $invoiceRows[] = [
            'invoice_no' => 'INV-S-' . (string)($row['id'] ?? ''),
            'invoice_type' => 'Service Booking Invoice',
            'invoice_category' => 'service',
            '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;
});

$totalAmount = 0.0;
foreach ($invoiceRows as $invoiceRow) {
    $totalAmount += (float)($invoiceRow['amount'] ?? 0);
}

$invoiceTypeLabel = $invoiceType === 'all'
    ? 'All Invoices'
    : ($invoiceType === 'room' ? 'Room Invoices' : 'Service Invoices');

$escape = static function ($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
};

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Revenue Invoices Report</title>
    <style>
        :root {
            --text-dark: #1f2f45;
            --text-light: #54667a;
            --border: #dfe7f1;
            --panel: #ffffff;
            --bg: #f3f5f8;
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: Jost, Arial, sans-serif;
            color: var(--text-dark);
            background: var(--bg);
        }
        .report-wrap {
            max-width: 1180px;
            margin: 0 auto;
            padding: 20px;
        }
        .report-head {
            background: var(--panel);
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 16px;
            margin-bottom: 14px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            flex-wrap: wrap;
        }
        .report-title {
            margin: 0;
            font-size: 28px;
            line-height: 1.2;
        }
        .report-meta {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 8px;
            width: 100%;
            font-size: 13px;
            color: var(--text-light);
        }
        .report-meta span {
            background: #f7faff;
            border: 1px solid #e8eef6;
            border-radius: 8px;
            padding: 8px 10px;
        }
        .toolbar {
            display: inline-flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        .toolbar a {
            text-decoration: none;
            color: #1f5a9d;
            border: 1px solid #c9d9ec;
            border-radius: 8px;
            padding: 8px 12px;
            font-size: 13px;
            font-weight: 600;
            background: #f5faff;
        }
        .panel {
            background: var(--panel);
            border: 1px solid var(--border);
            border-radius: 10px;
            overflow: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 920px;
        }
        th, td {
            padding: 10px 12px;
            border-bottom: 1px solid #e8eef6;
            vertical-align: middle;
            text-align: left;
            font-size: 14px;
        }
        th {
            background: #f7f9fc;
            color: #2a3b52;
            font-weight: 700;
            white-space: nowrap;
        }
        .badge {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 700;
            line-height: 1.2;
        }
        .invoice-room { background: #e8f2ff; color: #1c4d86; }
        .invoice-service { background: #eaf8ef; color: #1f6b3b; }
        .payment-paid { background: #e8f7ee; color: #2f855a; }
        .payment-partial { background: #fff5df; color: #b7791f; }
        .payment-unpaid { background: #ffecec; color: #c53030; }
        .status-pending { background: #fff3e0; color: #ff9800; }
        .status-confirmed { background: #e3f2fd; color: #2196f3; }
        .status-completed { background: #f3e5f5; color: #9c27b0; }
        .status-checked_in { background: #e8f5e9; color: #4caf50; }
        .status-checked_out { background: #ede7f6; color: #673ab7; }
        .status-cancelled { background: #ffebee; color: #f44336; }
        .money { font-weight: 700; color: #1f3f63; white-space: nowrap; }
        tfoot td {
            background: #f7f9fc;
            font-weight: 700;
            border-top: 2px solid #d7e2ef;
            border-bottom: 0;
        }
        .total-label {
            text-transform: uppercase;
            color: #2a3b52;
            letter-spacing: 0.02em;
        }
        .total-amount {
            color: #1b4f85;
        }
        .muted { color: var(--text-light); font-size: 13px; }
        @media (max-width: 767px) {
            .report-wrap { padding: 12px; }
            .report-title { font-size: 22px; }
            .report-meta { grid-template-columns: 1fr; }
            .toolbar { width: 100%; }
            .toolbar a { flex: 1; text-align: center; }
        }
        @media print {
            body { background: #fff; }
            .report-wrap { max-width: none; padding: 0; }
            .report-head { border: 0; border-bottom: 1px solid #ddd; border-radius: 0; padding: 0 0 10px; margin: 0 0 12px; }
            .toolbar { display: none; }
            .panel { border: 0; border-radius: 0; overflow: visible; }
            table { min-width: 0; }
            th, td { font-size: 11px; padding: 7px 8px; }
        }
    </style>
</head>
<body>
    <div class="report-wrap">
        <div class="report-head">
            <h1 class="report-title">Revenue Invoices</h1>
            <div class="toolbar">
                <a href="#" onclick="window.print(); return false;">Print / Save PDF</a>
                <a href="download-report.php?type=revenue&amp;invoice_type=<?php echo $escape($invoiceType); ?>">Download CSV</a>
            </div>
            <div class="report-meta">
                <span><strong>Generated:</strong> <?php echo $escape(date('Y-m-d H:i:s')); ?></span>
                <span><strong>Type:</strong> <?php echo $escape($invoiceTypeLabel); ?></span>
                <span><strong>Total Records:</strong> <?php echo $escape((string)count($invoiceRows)); ?></span>
                <span><strong>Total Amount:</strong> $<?php echo $escape(number_format($totalAmount, 2)); ?></span>
            </div>
        </div>

        <div class="panel">
            <table>
                <thead>
                    <tr>
                        <th>Invoice #</th>
                        <th>Invoice Type</th>
                        <th>Guest</th>
                        <th>Item</th>
                        <th>Dates</th>
                        <th>Amount</th>
                        <th>Payment</th>
                        <th>Status</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($invoiceRows)): ?>
                        <tr>
                            <td colspan="9" class="muted">No invoices found.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($invoiceRows as $row): ?>
                            <?php
                            $paymentClass = 'payment-' . preg_replace('/[^a-z_]/', '', strtolower((string)$row['payment']));
                            $statusClass = 'status-' . preg_replace('/[^a-z_]/', '', strtolower((string)$row['status']));
                            $invoiceClass = ((string)$row['invoice_category'] === 'service') ? 'invoice-service' : 'invoice-room';
                            ?>
                            <tr>
                                <td><?php echo $escape($row['invoice_no']); ?></td>
                                <td><span class="badge <?php echo $escape($invoiceClass); ?>"><?php echo $escape($row['invoice_type']); ?></span></td>
                                <td><?php echo $escape($row['guest']); ?></td>
                                <td><?php echo $escape($row['item']); ?></td>
                                <td><?php echo $escape($row['dates']); ?></td>
                                <td class="money">$<?php echo $escape(number_format((float)$row['amount'], 2)); ?></td>
                                <td><span class="badge <?php echo $escape($paymentClass); ?>"><?php echo $escape(ucwords(str_replace('_', ' ', (string)$row['payment']))); ?></span></td>
                                <td><span class="badge <?php echo $escape($statusClass); ?>"><?php echo $escape(ucwords(str_replace('_', ' ', (string)$row['status']))); ?></span></td>
                                <td><?php echo $escape($row['created']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" class="total-label">Total Amount</td>
                        <td class="money total-amount">$<?php echo $escape(number_format($totalAmount, 2)); ?></td>
                        <td colspan="3"></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
    <?php if ($autoPrint): ?>
    <script>
        window.addEventListener('load', function () {
            window.print();
        });
    </script>
    <?php endif; ?>
</body>
</html>
