<?php
include 'db.php';

$id = intval($_GET['id']);
$invoice = $conn->query("SELECT * FROM invoices WHERE id=$id")->fetch_assoc();
$items = $conn->query("SELECT * FROM invoice_items WHERE invoice_id=$id");

$total = 0;
while ($row = $items->fetch_assoc()) {
    $total += $row['total'];
    $invoice_items[] = $row;
}
$items->data_seek(0); // rewind
$sst = $invoice['sst_enabled'] ? $total * 0.08 : 0;
$grandTotal = $total + $sst;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Invoice #<?php echo $invoice['id']; ?> - VSONIC ENGINEERING</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4 bg-light">

<div class="container bg-white p-4 rounded shadow">
    <h2 class="mb-4">Invoice #<?php echo $invoice['id']; ?></h2>

    <p><strong>Partner:</strong> <?php echo htmlspecialchars($invoice['partner_name']); ?><br>
       <strong>Address:</strong><br><?php echo nl2br(htmlspecialchars($invoice['partner_address'])); ?><br>
       <strong>Date:</strong> <?php echo $invoice['created_at']; ?>
    </p>

    <h5>Items</h5>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Description</th>
                <th width="100">Qty</th>
                <th width="150">Unit Price</th>
                <th width="150">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($item = $items->fetch_assoc()) { ?>
            <tr>
                <td><?php echo htmlspecialchars($item['description']); ?></td>
                <td><?php echo $item['quantity']; ?></td>
                <td><?php echo number_format($item['unit_price'],2); ?></td>
                <td><?php echo number_format($item['total'],2); ?></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>

    <div class="text-end">
        <p><strong>Subtotal:</strong> <?php echo number_format($total,2); ?></p>
        <?php if ($invoice['sst_enabled']) { ?>
            <p><strong>SST (8%):</strong> <?php echo number_format($sst,2); ?></p>
        <?php } ?>
        <h4>Total: <?php echo number_format($grandTotal,2); ?></h4>
    </div>

    <a href="list_invoices.php" class="btn btn-secondary">Back</a>
    <a href="export_invoice_pdf.php?id=<?php echo $invoice['id']; ?>" class="btn btn-danger">Download PDF</a>
</div>
</body>
</html>
