<?php
include 'includes/auth.php';
include 'db.php';

$id = intval($_GET['id']);

// Sale
$sale = $conn->query("
    SELECT s.*, c.name AS customer_name
    FROM sales s
    LEFT JOIN customers c ON s.customer_id=c.id
    WHERE s.id=$id
")->fetch_assoc();

// ================= TAX (INCLUSIVE) =================
$total_incl = floatval($sale['total']); // already inclusive

$total_tax_rate = 0.175 + 0.01; // 18.5%

$taxable_base = $total_incl / (1 + $total_tax_rate);

$vat = $taxable_base * 0.175;
$tourism = $taxable_base * 0.01;

// Items
$items = $conn->query("
    SELECT si.*, p.name
    FROM sale_items si
    LEFT JOIN products p ON si.product_id=p.id
    WHERE si.sale_id=$id
");

// Logo
$logo = 'assets/logo.png'; // Update path to your logo
$phone = '0993 899 382';  // Your contact number
?>

<!DOCTYPE html>
<html>
<head>
<title>Receipt #<?= $id ?></title>
<style>
body{
    font-family: monospace; 
    width:300px; 
    margin:auto;
}
.center{text-align:center;}
table{
    width:100%; 
    font-size:12px; 
    border-collapse: collapse;
}
table th, table td{
    padding:3px;
    border-bottom:1px dotted #000;
}
hr{border:0; border-top:1px dashed #000; margin:5px 0;}
@media print{
    button{display:none;}
}
</style>
</head>
<body onload="window.print()">

<!-- Header with Logo and Phone -->
<div class="center">
    <img src="<?= $logo ?>" style="height:60px;"><br>
    <strong>🍺 RAMS LOUNGE RECEIPT</strong><br>
    
        Web:www.ramslodgemw.com<br>
        Phone:+265 993 899 382<br>
         Phone:+265 883 899 382<br>
       
    
    Phone: <?= $phone ?><br>
    Sale #: <?= $id ?><br>
    Date: <?= $sale['sale_date'] ?><br>
    Customer: <?= $sale['customer_name'] ?>
</div>

<hr>

<table>
<tr><th>Item</th><th>Qty</th><th>Total</th></tr>
<?php while($it = $items->fetch_assoc()): ?>
<tr>
    <td><?= $it['name'] ?></td>
    <td style="text-align:center;"><?= $it['qty'] ?></td>
    <td style="text-align:right;"><?= number_format($it['price']*$it['qty'],2) ?></td>
</tr>
<?php endwhile; ?>
</table>

<hr>

<table>
<tr>
    <td>Subtotal (Incl)</td>
    <td style="text-align:right;">MK <?= number_format($total_incl,2) ?></td>
</tr>
<tr>
    <td>VAT (17.5%)</td>
    <td style="text-align:right;">MK <?= number_format($vat,2) ?></td>
</tr>
<tr>
    <td>Tourism Levy (1%)</td>
    <td style="text-align:right;">MK <?= number_format($tourism,2) ?></td>
</tr>
<tr>
    <td><strong>Total</strong></td>
    <td style="text-align:right;"><strong>MK <?= number_format($total_incl,2) ?></strong></td>
</tr>
</table>

<p>Payment Method: <?= htmlspecialchars($sale['payment_method']) ?></p>

<div class="center">
    <p class="center">* Prices are Tax Inclusive *</p>
<p>Thank you for your patronage!</p>
<button onclick="window.print()">Print</button>
</div>

</body>
</html>
