<?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
$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, sh.phone as shop_phone
        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 sale items
$sql = "SELECT sl.*, p.name as product_name, p.sku, p.unit,
               pb.batch_no, pb.expiry_date
        FROM sale_lines sl
        JOIN products p ON sl.product_id = p.id
        LEFT JOIN product_batches pb ON sl.batch_id = pb.id
        WHERE sl.sale_id = ?
        ORDER BY sl.id";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sale_id]);
$sale_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch payments for this sale
$sql = "SELECT * FROM payments WHERE sale_id = ? ORDER BY paid_at";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sale_id]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals
$subtotal = 0;
$total_discount = 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;
    $total_discount += $discount_amount;
}

$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']));
$print_date = date('d-M-Y H:i');
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Receipt - <?=htmlspecialchars($sale['invoice_no'])?></title>
    <style>
        * { 
            margin: 0; 
            padding: 0; 
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.3;
        }
        
        body { 
            width: 80mm; 
            margin: 0 auto; 
            padding: 2mm; 
            background: white;
        }
        
        @media print { 
            body { margin: 0; padding: 0; }
            .no-print { display: none !important; }
        }
        
        .text-center { text-align: center; }
        .text-right { text-align: right; }
        .text-left { text-align: left; }
        .bold { font-weight: bold; }
        
        .header {
            text-align: center;
            margin-bottom: 5px;
            border-bottom: 1px dashed #000;
            padding-bottom: 5px;
        }
        
        .shop-name {
            font-size: 16px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .shop-details {
            font-size: 11px;
            margin: 2px 0;
        }
        
        .receipt-title {
            font-size: 14px;
            font-weight: bold;
            margin: 5px 0;
            text-transform: uppercase;
        }
        
        .info-section {
            margin: 5px 0;
            font-size: 12px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
        }
        
        .info-label {
            font-weight: bold;
        }
        
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 5px 0;
            font-size: 12px;
        }
        
        .items-table th {
            border-bottom: 1px dashed #000;
            padding: 3px 0;
            text-align: left;

        }
        
        .items-table td {
            padding: 2px 0;
            vertical-align: top;
        }
        
        .item-name {
            width: 50%;
            word-break: break-word;
        }
        
        .item-qty {
            width: 15%;
            text-align: center;
        }
        
        .item-price {
            width: 20%;
            text-align: right;
        }
        
        .item-total {
            width: 15%;
            text-align: right;
        }
        
        .totals {
            margin: 5px 0;
            border-top: 1px dashed #000;
            padding-top: 5px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .grand-total {
            font-weight: bold;
            font-size: 15px;
            border-top: 2px solid #000;
            padding-top: 5px;
            margin-top: 5px;
        }
        
        .payment-info {
            margin: 5px 0;
            padding: 5px;
            border: 1px dashed #000;
            border-radius: 3px;
            font-size: 12px;
        }
        
        .balance {
            font-weight: bold;
            color: <?= $balance > 0 ? '#d9534f' : '#5cb85c' ?>;
        }
        
        .footer {
            text-align: center;
            margin-top: 10px;
            padding-top: 5px;
            border-top: 1px dashed #000;
            font-size: 11px;
        }
        
        .thank-you {
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .payment-history {
            margin-top: 5px;
            font-size: 11px;
        }
        
        .payment-item {
            display: flex;
            justify-content: space-between;
            padding: 1px 0;
            border-bottom: 1px dotted #ccc;
        }
        
        .payment-item:last-child {
            border-bottom: none;
        }
        
        .badge {
            display: inline-block;
            padding: 1px 4px;
            border-radius: 2px;
            font-size: 10px;
            font-weight: bold;
            margin-left: 3px;
        }
        
        .badge-paid { background: #5cb85c; color: white; }
        .badge-partial { background: #f0ad4e; color: white; }
        .badge-open { background: #777; color: white; }
        
        .buttons {
            text-align: center;
            margin-top: 10px;
        }
        
        button {
            padding: 5px 10px;
            margin: 0 5px;
            border: 1px solid #ccc;
            background: #f8f9fa;
            cursor: pointer;
            border-radius: 3px;
        }
        
        button:hover {
            background: #e9ecef;
        }
    </style>
</head>
<body onload="setTimeout(function() { window.print(); }, 500);">
    <div class="header">
        <div class="shop-name"><?=htmlspecialchars($sale['shop_name'])?></div>
        <?php if(!empty($sale['shop_address'])): ?>
        <div class="shop-details"><?=htmlspecialchars($sale['shop_address'])?></div>
        <?php endif; ?>
        <?php if(!empty($sale['shop_phone'])): ?>
        <div class="shop-details">Tel: <?=htmlspecialchars($sale['shop_phone'])?></div>
        <?php endif; ?>
        <div class="receipt-title">TAX INVOICE</div>
    </div>
    
    <div class="info-section">
        <div class="info-row">
            <span class="info-label">Invoice:</span>
            <span><?=htmlspecialchars($sale['invoice_no'])?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Date:</span>
            <span><?=$sale_date?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Customer:</span>
            <span><?=htmlspecialchars($sale['customer_name'])?></span>
        </div>
        <?php if(!empty($sale['customer_phone'])): ?>
        <div class="info-row">
            <span class="info-label">Phone:</span>
            <span><?=htmlspecialchars($sale['customer_phone'])?></span>
        </div>
        <?php endif; ?>
        <div class="info-row">
            <span class="info-label">Cashier:</span>
            <span><?=htmlspecialchars($sale['cashier'])?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Status:</span>
            <span>
                <?=ucfirst(str_replace('_', ' ', $sale['status']))?>
                <span class="badge badge-<?=$sale['status']?>">
                    <?php
                    switch($sale['status']) {
                        case 'paid': echo 'PAID'; break;
                        case 'partially_paid': echo 'PARTIAL'; break;
                        default: echo 'OPEN'; break;
                    }
                    ?>
                </span>
            </span>
        </div>
    </div>
    
    <table class="items-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 class="item-name">
                    <?=htmlspecialchars($item['product_name'])?>
                    <?php if($item['discount'] > 0): ?>
                        <br><small>(-<?=number_format($item['discount'],0)?>%)</small>
                    <?php endif; ?>
                    <?php if(!empty($item['batch_no'])): ?>
                        <br><small>Batch: <?=htmlspecialchars($item['batch_no'])?></small>
                    <?php endif; ?>
                </td>
                <td class="item-qty"><?=$item['qty']?></td>
                <td class="item-price"><?=number_format($item['unit_price'],2)?></td>
                <td class="item-total"><?=number_format($final_line_total,2)?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <div class="totals">
        <div class="total-row">
            <span>Subtotal:</span>
            <span><?=number_format($subtotal,2)?></span>
        </div>
        <?php if($total_discount > 0): ?>
        <div class="total-row">
            <span>Discount:</span>
            <span>-<?=number_format($total_discount,2)?></span>
        </div>
        <?php endif; ?>
        <div class="total-row">
            <span>VAT (18%):</span>
            <span><?=number_format($vat,2)?></span>
        </div>
        <div class="total-row grand-total">
            <span>TOTAL:</span>
            <span><?=number_format($grand_total,2)?></span>
        </div>
        
        <div class="payment-info">
            <div class="total-row">
                <span>Paid:</span>
                <span class="text-success"><?=number_format($sale['paid'],2)?></span>
            </div>
            <div class="total-row">
                <span>Method:</span>
                <span>
                    <?php 
                    if(!empty($payments)) {
                        echo htmlspecialchars(end($payments)['method']);
                    } else {
                        echo 'Not specified';
                    }
                    ?>
                </span>
            </div>
            <div class="total-row">
                <span>BALANCE:</span>
                <span class="balance"><?=number_format($balance,2)?></span>
            </div>
            
            <?php if(!empty($payments)): ?>
            <div class="payment-history">
                <div style="text-align: center; margin-bottom: 3px; font-weight: bold;">Payment History</div>
                <?php foreach($payments as $payment): ?>
                <div class="payment-item">
                    <span><?=date('d-M H:i', strtotime($payment['paid_at']))?></span>
                    <span><?=htmlspecialchars($payment['method'])?></span>
                    <span class="text-success"><?=number_format($payment['amount'],2)?></span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="footer">
        <div class="thank-you">THANK YOU FOR YOUR BUSINESS!</div>
        <?php if($balance > 0): ?>
        <div>Outstanding balance: <?=number_format($balance,2)?></div>
        <?php endif; ?>
        <div>For inquiries: <?=htmlspecialchars($sale['shop_name'])?></div>
        <div>Printed: <?=$print_date?></div>
        <div>Computer generated receipt</div>
    </div>
    
    <div class="buttons no-print">
        <button onclick="window.print()">Print</button>
        <button onclick="window.close()">Close</button>
    </div>
    
    <script>
    // Auto-close after printing
    window.onafterprint = function() {
        setTimeout(function() {
            window.close();
        }, 1000);
    };
    </script>
</body>
</html>