<?php
include 'includes/config.php';
$ref_no = $_GET['ref_no'] ?? '';
if(!$ref_no) exit('Invalid Ref');

$companyStmt = $conn->query("SELECT `id`, `name`, `address`, `phone` FROM `companies` ORDER BY id DESC LIMIT 1");
$company = $companyStmt->fetch(PDO::FETCH_ASSOC);

$stmt = $conn->prepare("SELECT p.id AS line_id, pr.name AS ProductName, p.quantity, p.purchase_price, p.purchase_date, c.name AS supplier_name
                        FROM purchase_lines p
                        LEFT JOIN products pr ON p.product_id = pr.id
                        LEFT JOIN contacts c ON p.supplier_id = c.id
                        WHERE p.ref_no=:ref_no");
$stmt->bindValue(':ref_no',$ref_no);
$stmt->execute();
$items = $stmt->fetchAll();

$supplier = $items[0]['supplier_name'] ?? '';
$date = !empty($items[0]['purchase_date']) ? date('d-m-Y', strtotime($items[0]['purchase_date'])) : '';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bill Ref: <?php echo htmlspecialchars($ref_no); ?></title>
<style>
body {
    width: 58mm; /* thermal width */
    font-family: monospace;
    font-size: 13px; /* slightly bigger */
    margin: 0;
    padding: 5px;
}
.center { text-align: center; font-weight: bold; }
hr { border:0; border-top:1px dashed #000; margin:5px 0; }
table { width:100%; border-collapse: collapse; }
td, th { padding:2px 3px; border:1px solid #000; font-weight: bold; }
td.right, th.right { text-align:right; }
</style>
</head>
<body>
<div class="center">
    <div><?php echo htmlspecialchars($company['name']); ?></div>
    <div><?php echo htmlspecialchars($company['address']); ?></div>
    <div><?php echo htmlspecialchars($company['phone']); ?></div>
    <hr>
    <div>Bill Ref: <?php echo $ref_no; ?></div>
    <div>Supplier: <?php echo $supplier; ?></div>
    <div>Date: <?php echo $date; ?></div>
    <hr>
</div>

<table>
<thead>
<tr>
    <th>#</th>
    <th>Item</th>
    <th class="right">Qty</th>
    <th class="right">Price</th>
    <th class="right">Total</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
$grand_total = 0;
foreach($items as $item){
    $line_total = $item['quantity'] * $item['purchase_price'];
    echo "<tr>";
    echo "<td>".$i++."</td>";
    echo "<td>".substr($item['ProductName'],0,14)."</td>"; 
    echo "<td class='right'>".$item['quantity']."</td>";
    echo "<td class='right'>".number_format($item['purchase_price'],2)."</td>";
    echo "<td class='right'>".number_format($line_total,2)."</td>";
    echo "</tr>";
    $grand_total += $line_total;
}
?>
<tr>
    <td colspan="4" class="total right">Total</td>
    <td class="total right"><?php echo number_format($grand_total,2); ?></td>
</tr>
</tbody>
</table>

<div class="center">
<hr>
<div>Thank You!</div>
</div>

<script>window.print();</script>
</body>
</html>
