<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
    body { font-family: sans-serif; font-size: 12px; color: #1a1a1a; }
    h1 { font-size: 20px; margin-bottom: 4px; }
    .muted { color: #666; }
    table { width: 100%; border-collapse: collapse; margin-top: 16px; }
    th, td { border-bottom: 1px solid #ddd; padding: 6px 8px; text-align: left; }
    th { background: #f5f5f5; }
    .text-right { text-align: right; }
    .totals { width: 260px; margin-left: auto; margin-top: 12px; }
    .totals td { border: none; padding: 3px 8px; }
    .totals .grand { font-weight: bold; border-top: 1px solid #333; }
</style>
</head>
<body>
    <h1>Invoice <?= htmlspecialchars($invoice['invoice_number']) ?></h1>
    <p class="muted">Status: <?= htmlspecialchars(ucfirst($invoice['status'])) ?></p>

    <table>
        <tr>
            <td><strong>Project:</strong> <?= htmlspecialchars($invoice['project_name'] ?? 'N/A') ?></td>
            <td><strong>Contractor/Supplier:</strong> <?= htmlspecialchars($invoice['contractor_name'] ?? 'N/A') ?></td>
        </tr>
        <tr>
            <td><strong>Invoice Date:</strong> <?= htmlspecialchars($invoice['date'] ?? '') ?></td>
            <td><strong>Due Date:</strong> <?= htmlspecialchars($invoice['due_date'] ?? 'N/A') ?></td>
        </tr>
        <?php if (!empty($invoice['po_reference'])): ?>
        <tr><td colspan="2"><strong>PO Reference:</strong> <?= htmlspecialchars($invoice['po_reference']) ?></td></tr>
        <?php endif; ?>
    </table>

    <table>
        <thead>
            <tr><th>Description</th><th class="text-right">Qty</th><th class="text-right">Unit Price</th><th class="text-right">Total</th></tr>
        </thead>
        <tbody>
            <?php foreach ($invoice['items'] ?? [] as $item): ?>
            <tr>
                <td><?= htmlspecialchars($item['description']) ?></td>
                <td class="text-right"><?= htmlspecialchars($item['qty']) ?></td>
                <td class="text-right"><?= number_format((float)$item['unit_price'], 2) ?></td>
                <td class="text-right"><?= number_format((float)$item['total'], 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <table class="totals">
        <tr><td>Subtotal</td><td class="text-right"><?= number_format((float)($invoice['subtotal'] ?? 0), 2) ?></td></tr>
        <tr><td>Tax (<?= htmlspecialchars($invoice['tax_percent'] ?? 0) ?>%)</td><td class="text-right"><?= number_format((float)($invoice['tax_amount'] ?? 0), 2) ?></td></tr>
        <tr class="grand"><td>Total</td><td class="text-right"><?= htmlspecialchars($invoice['currency'] ?? DEFAULT_CURRENCY) ?> <?= number_format((float)($invoice['total'] ?? 0), 2) ?></td></tr>
    </table>

    <?php if (!empty($invoice['notes'])): ?>
    <p><strong>Notes:</strong><br><?= nl2br(htmlspecialchars($invoice['notes'])) ?></p>
    <?php endif; ?>
</body>
</html>
