<?php
require_once "db.php";

if (!isset($_GET['id'])) {
    echo "Invalid Request";
    exit();
}
$sale_id = intval($_GET['id']);

// Fetch sale
$stmt = $conn->prepare("SELECT s.*, c.customer_name, c.customer_phone, c.customer_address 
                        FROM sales s 
                        LEFT JOIN customers c ON s.customer_id=c.customer_id
                        WHERE s.sale_id=?");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$sale = $stmt->get_result()->fetch_assoc();

// Fetch items
$stmtItems = $conn->prepare("SELECT * FROM sale_items WHERE sale_id=?");
$stmtItems->bind_param("i", $sale_id);
$stmtItems->execute();
$items = $stmtItems->get_result();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Sale Invoice</title>
    <style>
        body { font-family: Arial; margin: 20px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        table, th, td { border: 1px solid black; }
        th, td { padding: 8px; text-align: left; }
    </style>
</head>
<body onload="window.print()" class="global-print">
    <?php
    include("global/global-print-heading.php");
?>
    <main class="print-body-content">
    <h2>Sale Invoice</h2>
    <p><strong>Customer:</strong> <?php echo htmlspecialchars($sale['customer_name']); ?><br>
       <strong>Phone:</strong> <?php echo htmlspecialchars($sale['customer_phone']); ?><br>
       <strong>Address:</strong> <?php echo htmlspecialchars($sale['customer_address']); ?><br>
       <strong>Date:</strong> <?php echo htmlspecialchars($sale['sale_date']); ?></p>

    <table>
        <tr>
            <th>Product</th>
            <th>Size</th>
            <th>Rate</th>
            <th>Qty</th>
            <th>Subtotal</th>
        </tr>
        <?php while($item = $items->fetch_assoc()): ?>
        <tr>
            <td><?php echo htmlspecialchars($item['product']); ?></td>
            <td><?php echo htmlspecialchars($item['size']); ?></td>
            <td><?php echo number_format($item['rate'],2); ?></td>
            <td><?php echo $item['qty']; ?></td>
            <td><?php echo number_format($item['subtotal'],2); ?></td>
        </tr>
        
        <?php endwhile; ?>
        <tr>
            <td colspan="4" style="text-align: right"><strong>Total</strong></td>
            <td><?php echo number_format($sale['total'],2); ?></td>
        </tr>
    </table>

    <h3>Total: ৳<?php echo number_format($sale['total'],2); ?></h3>
    <h3>Paid: ৳<?php echo number_format($sale['paid'],2); ?></h3>
    <h3>Due: ৳<?php echo number_format($sale['due'],2); ?></h3>
</main>
     <?php
    include("global/global-print-footer.php");
?>
</body>
</html>
