<?php 
include 'config.php';

$id = $_GET['id'];

// Sale + Customer Info
$sale = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT sales.*, customers.name AS customer_name, customers.contact, customers.address
    FROM sales
    JOIN customers ON sales.customer_id = customers.id
    WHERE sales.id = $id
"));

// Sale Items
$items = mysqli_query($conn, "
    SELECT sale_items.*, inventory.name AS product_name
    FROM sale_items
    JOIN inventory ON sale_items.inventory_id = inventory.id
    WHERE sale_items.sale_id = $id
");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Invoice View</title>

    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .invoice-box {
            width: 800px;
            margin: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid #000;
        }
        th, td {
            padding: 8px;
            text-align: center;
        }
        .text-right {
            text-align: right;
        }

        @media print {
            button, a {
                display: none;
            }
        }
    </style>
</head>
<body>

<div class="invoice-box">

<h2>Invoice</h2>

<hr>

<p><strong>Invoice No:</strong> <?php echo $sale['invoice_no']; ?></p>
<p><strong>Date:</strong> <?php echo $sale['sale_date']; ?></p>

<hr>

<h3>Customer Details</h3>
<p><strong>Name:</strong> <?php echo $sale['customer_name']; ?></p>
<p><strong>Contact:</strong> <?php echo $sale['contact']; ?></p>
<p><strong>Address:</strong> <?php echo $sale['address']; ?></p>

<hr>

<h3>Products</h3>

<table>
    <tr>
        <th>Product</th>
        <th>Quantity</th>
        <th>Unit Price</th>
        <th>Subtotal</th>
    </tr>

    <?php while($row = mysqli_fetch_assoc($items)){ ?>
        <tr>
            <td><?php echo $row['product_name']; ?></td>
            <td><?php echo $row['quantity']; ?></td>
            <td><?php echo number_format($row['unit_price'], 2); ?></td>
            <td><?php echo number_format($row['subtotal'], 2); ?></td>
        </tr>
    <?php } ?>

    <tr>
        <td colspan="3" class="text-right"><strong>Total</strong></td>
        <td><strong><?php echo number_format($sale['grand_total'], 2); ?></strong></td>
    </tr>

</table>

<br><br>

<button onclick="window.print()">Print Invoice</button>
<br><br>
<a href="sales_list.php">Back to Sales</a>

</div>

</body>
</html>
