<?php
session_start();
if (!isset($_SESSION['username'])) exit('Access denied');
require_once "db.php";

if (!isset($_GET['id'])) exit('Invalid purchase ID');
$purchase_id = intval($_GET['id']);

// Fetch purchase
$stmt = $conn->prepare("SELECT p.*, s.supplier_name 
                        FROM purchases p 
                        LEFT JOIN suppliers s ON p.supplier_id = s.supplier_id 
                        WHERE p.purchase_id=?");
$stmt->bind_param("i", $purchase_id);
$stmt->execute();
$purchase = $stmt->get_result()->fetch_assoc();
if (!$purchase) exit('Purchase not found');

// Fetch purchase items
$stmtItems = $conn->prepare("SELECT * FROM purchase_items WHERE purchase_id=?");
$stmtItems->bind_param("i", $purchase_id);
$stmtItems->execute();
$items = $stmtItems->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Invoice #<?php echo $purchase_id;?></title>
<style>
body{font-family:Arial,sans-serif;margin:20px;}
h2{text-align:center; font-size: 30px;}

table{width:100%;border-collapse:collapse;margin-top:20px;}
table, th, td{border:1px solid #000;}
th, td{padding:8px;text-align:left;}
tfoot td{font-weight:bold;}

</style>
</head>
<body class="global-print">
    
<?php
    include("global/global-print-heading.php");
?>
<main class="print-body-content">
    <p><strong>Invoice No:</strong> <?php echo $purchase['invoice_no'];?></p>
<p><strong>Supplier:</strong> <?php echo htmlspecialchars($purchase['supplier_name']);?></p>
<p><strong>Date:</strong> <?php echo $purchase['purchase_date'];?></p>

<table>
<thead>
<tr>
<th>Product</th>
<th>Size</th>
<th>Rate (৳)</th>
<th>Qty</th>
<th>Subtotal (৳)</th>
</tr>
</thead>
<tbody>
<?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;?>
</tbody>
<tfoot>
<tr>
<td colspan="4">Total</td>
<td><?php echo number_format($purchase['total'],2);?></td>
</tr>
<tr>
<td colspan="4">Paid</td>
<td><?php echo number_format($purchase['paid'],2);?></td>
</tr>
<tr>
<td colspan="4">Due</td>
<td><?php echo number_format($purchase['due'],2);?></td>
</tr>
</tfoot>
</table>
</main>
 <?php
    include("global/global-print-footer.php");
?>
<script>
window.onload = function(){ window.print(); }
</script>
</body>
</html>
