<?php
// print_receipt_thermal.php
session_start();
require_once '../config/db_connect.php';

$sale_id = isset($_GET['sale_id']) ? intval($_GET['sale_id']) : 0;

if ($sale_id <= 0) die("Invalid sale ID.");

// Fetch sale details (same as above)
$sql = "SELECT s.*, COALESCE(c.name, 'Walk-in Customer') as customer_name,
               c.phone as customer_phone, u.fullname as cashier,
               sh.name as shop_name, sh.address as shop_address
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        LEFT JOIN users u ON s.created_by = u.id
        LEFT JOIN shops sh ON s.shop_id = sh.id
        WHERE s.id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sale_id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sale) die("Sale not found.");

// Fetch items
$sql = "SELECT sl.*, p.name as product_name, p.sku, p.unit
        FROM sale_lines sl
        JOIN products p ON sl.product_id = p.id
        WHERE sl.sale_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sale_id]);
$sale_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals
$subtotal = 0;
foreach ($sale_items as $item) {
    $line_total = $item['qty'] * $item['unit_price'];
    $discount_amount = $line_total * ($item['discount'] / 100);
    $after_discount = $line_total - $discount_amount;
    $subtotal += $after_discount;
}

$vat = $subtotal * 0.18;
$grand_total = $subtotal + $vat;
$balance = $sale['total'] - $sale['paid'];

// Format dates
$sale_date = date('d-M-Y H:i', strtotime($sale['sale_date']));
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Thermal Receipt</title>
    <style>
        * { margin: 0; padding: 0; font-family: 'Courier New', monospace; }
        body { width: 80mm; margin: 0 auto; padding: 5mm; font-size: 12px; }
        @media print { 
            body { margin: 0; padding: 0; }
            .no-print { display: none; }
        }
        .text-center { text-align: center; }
        .text-right { text-align: right; }
        .bold { font-weight: bold; }
        .underline { border-bottom: 1px dashed #000; padding-bottom: 2px; }
        .divider { border-top: 1px dashed #000; margin: 5px 0; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 2px 0; }
        .item-name { width: 60%; }
        .item-qty { width: 10%; text-align: center; }
        .item-price { width: 15%; text-align: right; }
        .item-total { width: 15%; text-align: right; }
        .footer { font-size: 10px; margin-top: 10px; text-align: center; }
    </style>
</head>
<body onload="window.print(); setTimeout(window.close, 1000);">
    <div class="text-center bold">
        <div><?=htmlspecialchars($sale['shop_name'])?></div>
        <?php if(!empty($sale['shop_address'])): ?>
        <div style="font-size: 10px;"><?=htmlspecialchars($sale['shop_address'])?></div>
        <?php endif; ?>
        <div class="divider"></div>
        <div>TAX INVOICE</div>
    </div>
    
    <div style="margin: 5px 0;">
        <div>Invoice: <?=htmlspecialchars($sale['invoice_no'])?></div>
        <div>Date: <?=$sale_date?></div>
        <div>Customer: <?=htmlspecialchars($sale['customer_name'])?></div>
        <div>Cashier: <?=htmlspecialchars($sale['cashier'])?></div>
        <div class="divider"></div>
    </div>
    
    <table>
        <thead>
            <tr>
                <th class="item-name">Item</th>
                <th class="item-qty">Qty</th>
                <th class="item-price">Price</th>
                <th class="item-total">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($sale_items as $item): 
                $line_total = $item['qty'] * $item['unit_price'];
                $discount_amount = $line_total * ($item['discount'] / 100);
                $final_line_total = $line_total - $discount_amount;
            ?>
            <tr>
                <td><?=htmlspecialchars($item['product_name'])?></td>
                <td class="text-center"><?=$item['qty']?></td>
                <td class="text-right"><?=number_format($item['unit_price'], 2)?></td>
                <td class="text-right"><?=number_format($final_line_total, 2)?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <div class="divider"></div>
    
    <div>
        <div style="display: flex; justify-content: space-between;">
            <span>Subtotal:</span>
            <span><?=number_format($subtotal, 2)?></span>
        </div>
        <div style="display: flex; justify-content: space-between;">
            <span>VAT (18%):</span>
            <span><?=number_format($vat, 2)?></span>
        </div>
        <div style="display: flex; justify-content: space-between; font-weight: bold;">
            <span>TOTAL:</span>
            <span><?=number_format($grand_total, 2)?></span>
        </div>
        <div style="display: flex; justify-content: space-between;">
            <span>Paid:</span>
            <span><?=number_format($sale['paid'], 2)?></span>
        </div>
        <div style="display: flex; justify-content: space-between; font-weight: bold;">
            <span>BALANCE:</span>
            <span><?=number_format($balance, 2)?></span>
        </div>
    </div>
    
    <div class="divider"></div>
    
    <div class="footer">
        <div>Thank you for your business!</div>
        <?php if($balance > 0): ?>
        <div>Outstanding: <?=number_format($balance, 2)?></div>
        <?php endif; ?>
        <div>Computer generated receipt</div>
        <div><?=date('d-M-Y H:i')?></div>
    </div>
    
    <div class="no-print" style="text-align: center; margin-top: 20px;">
        <button onclick="window.print()">Print</button>
        <button onclick="window.close()">Close</button>
    </div>
</body>
</html>