<?php
session_start();
require '../assets/db_connect.php';

$sale_id = $_GET['id'] ?? null;
if (!$sale_id) {
    die("Sale ID missing");
}

// Get sale info
$stmt = $pdo->prepare("SELECT s.*, u.username, c.name AS customer_name 
                       FROM sales s
                       LEFT JOIN users u ON s.created_by = u.id
                       LEFT JOIN customers c ON s.customer_id = c.id
                       WHERE s.id = ?");
$stmt->execute([$sale_id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$sale) die("Sale not found");

// Get sale items
$stmtItems = $pdo->prepare("SELECT sl.*, p.name AS product_name, b.batch_no 
                            FROM sale_lines sl
                            JOIN products p ON sl.product_id = p.id
                            JOIN product_batches b ON sl.batch_id = b.id
                            WHERE sl.sale_id = ?");
$stmtItems->execute([$sale_id]);
$items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals
$grandTotal = 0;
foreach($items as $it){
    $grandTotal += $it['line_total'];
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Invoice <?= $sale['invoice_no'] ?></title>
    <style>
        body { font-family: monospace; padding:10px; }
        .header { text-align:center; margin-bottom:10px; }
        .header h2 { margin:0; }
        table { width:100%; border-collapse: collapse; }
        th, td { padding:5px; text-align:left; }
        th { border-bottom:1px solid #000; }
        .totals { margin-top:10px; }
        .small-print { font-size:12px; }
        .receipt { width: 80mm; max-width: 100%; margin: auto; }
        @media print {
            .no-print { display:none; }
        }
    </style>
</head>
<body>
<div class="receipt">
    <div class="header">
        <h2>Mugana Pharmacy</h2>
        <div>Invoice: <?= $sale['invoice_no'] ?></div>
        <div>Date: <?= date('Y-m-d H:i', strtotime($sale['sale_date'])) ?></div>
        <?php if($sale['customer_name']): ?>
        <div>Customer: <?= htmlspecialchars($sale['customer_name']) ?></div>
        <?php endif; ?>
        <div>Cashier: <?= htmlspecialchars($sale['username']) ?></div>
        <hr>
    </div>

    <table>
        <thead>
            <tr>
                <th>Product</th>
                <th>Batch</th>
                <th>Qty</th>
                <th>Price</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($items as $it): ?>
            <tr>
                <td><?= htmlspecialchars($it['product_name']) ?></td>
                <td><?= htmlspecialchars($it['batch_no']) ?></td>
                <td><?= $it['qty'] ?></td>
                <td><?= number_format($it['unit_price'],2) ?></td>
                <td><?= number_format($it['line_total'],2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="totals">
        <strong>Grand Total: <?= number_format($grandTotal,2) ?></strong><br>
        Paid: <?= number_format($sale['paid'],2) ?><br>
        Balance: <?= number_format($grandTotal - $sale['paid'],2) ?>
    </div>

    <div class="small-print">
        <hr>
        Thank you for your purchase!<br>
        This is a computer-generated invoice.
    </div>

    <button class="no-print" onclick="window.print()">Print</button>
</div>

<script>
    // Auto print on page load
    window.onload = function(){
        window.print();
    }
</script>
</body>
</html>
