<?php
include '../db.php';

$id = $_GET['id'];
$stmt = $conn->prepare("SELECT i.*, c.name, c.email FROM invoices i JOIN clients c ON i.client_id=c.id WHERE i.id=?");
$stmt->execute([$id]);
$invoice = $stmt->fetch();

$items = $conn->prepare("SELECT * FROM invoice_items WHERE invoice_id=?");
$items->execute([$id]);
$items = $items->fetchAll();

if (!$invoice) {
    echo "Invoice not found.";
    exit;
}
?>

<h2>Invoice <?=htmlspecialchars($invoice['invoice_number'])?></h2>
<p><strong>Client:</strong> <?=htmlspecialchars($invoice['name'])?></p>
<p><strong>Email:</strong> <?=htmlspecialchars($invoice['email'])?></p>
<p><strong>Date:</strong> <?=htmlspecialchars($invoice['created_at'])?></p>

<table border="1" cellpadding="5" cellspacing="0">
    <tr>
        <th>Service Type</th>
        <th>Description</th>
        <th>Amount (?)</th>
    </tr>
    <?php foreach ($items as $item): ?>
    <tr>
        <td><?=htmlspecialchars($item['service_type'])?></td>
        <td><?=htmlspecialchars($item['description'])?></td>
        <td align="right"><?=number_format($item['amount'],2)?></td>
    </tr>
    <?php endforeach; ?>
    <tr>
        <td colspan="2" align="right"><strong>Subtotal</strong></td>
        <td align="right"><?=number_format($invoice['total_amount'],2)?></td>
    </tr>
    <tr>
        <td colspan="2" align="right"><strong>GST (<?=number_format($invoice['gst_percentage'],2)?>%)</strong></td>
        <td align="right"><?=number_format($invoice['gst_amount'],2)?></td>
    </tr>
    <tr>
        <td colspan="2" align="right"><strong>Total</strong></td>
        <td align="right"><?=number_format($invoice['net_amount'],2)?></td>
    </tr>
</table>

<br>
<button onclick="window.print()">Print Invoice</button>
<a href="invoice_pdf.php?id=<?= $invoice['id'] ?>" target="_blank">Download PDF</a>
