<?php
include("../db/cn.php");
include('common/tx.php');
ob_start();
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// Fetch order details from the database
$orderId = isset($_GET['order_id']) ? mysqli_real_escape_string($connection, $_GET['order_id']) : null;
$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = $preAmount = null;

if ($orderId) {
    $query = "SELECT * FROM log_user_sales WHERE order_id = '$orderId' && status='' && r_order_id = ''";
    $result = mysqli_query($connection, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $orderDetails = mysqli_fetch_all($result, MYSQLI_ASSOC);
        $order = $orderDetails[0];
        $outletName = $order['outlet_name'];
        $loginUser = $order['login_user'];
        $userRole = $order['user_role'];
        $outletAddress = $order['outlet_address'];
        $dateTime = $order['date_time'];
        $totalAmount = $order['net_amount'];
        $paidBy = $order['paid_by'];
        $customerName = $order['customer_name'];
        $customerPhone = $order['customer_phone'];
        $discountedAmount = $order['discount_amount'];
        $discounted = $order['discounted'];
        $discountPer = $order['discount_per'];
        $cashAmount = $order['cash_amount'];
        $changeAmount = $order['change_amount'];
        $taxAmount = $order['tax_amount'];
        $preAmount = $order['pre_amount'];
        
        // Calculate totals
        $totalSub = 0;
        $sb = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$orderId'");
        while ($tt = mysqli_fetch_array($sb)) {
            $totalSub += floatval($tt['net_amount']);
        }

        $discounted = floatval($discounted);
        $discountedAmount = floatval($totalSub) - $discounted;

        $pre = 0;
        $sub = mysqli_query($connection, "SELECT SUM(remain_balance) AS pre FROM creditor_closing WHERE creditor_name = '$customerName'");
        if ($rowSub = mysqli_fetch_assoc($sub)) {
            $pre = floatval($rowSub['pre'] ?? 0);
        }

        $preAmount = floatval($preAmount);
        $close = floatval($discountedAmount) + $preAmount;
        $cashAmount = floatval($cashAmount ?? 0);
        $changeAmount = $cashAmount - $close;
    }
}

$content = ob_get_clean();

function sendToPrinter($result) {
    $handle = @fopen("USB", "w");
    if (!$handle) return;
    fwrite($handle, $result);
    fclose($handle);
}
sendToPrinter($content);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Thermal Receipt | <?php echo $tx ?? 'Order'; ?></title>
    <style>
        /* BASE STYLES (screen only) */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: #eef2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
            font-family: 'Courier New', 'Monaco', monospace;
        }
        
        .receipt {
            width: 80mm;
            max-width: 80mm;
            background: white;
            margin: 0 auto;
            border-radius: 8px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .receipt-content {
            padding: 8px 10px;
        }
        
        /* Screen-only button group */
        .button-group {
            padding: 12px;
            background: #f8f9fc;
            border-top: 1px solid #e5e7eb;
            display: flex;
            gap: 10px;
            justify-content: center;
        }
        
        .btn-print, .btn-exit {
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
            font-family: 'Quicksand', sans-serif;
        }
        
        .btn-print {
            background: #0A4657;
            color: white;
        }
        
        .btn-exit {
            background: #e5e7eb;
            color: #333;
        }
        
        /* ========== PRINT MEDIA STYLES (Thermal 80mm) ========== */
        @media print {
            /* Remove all margins/paddings from browser */
            * {
                margin: 0 !important;
                padding: 0 !important;
                box-sizing: border-box !important;
            }
            
            html, body {
                margin: 0 !important;
                padding: 0 !important;
                width: 80mm;
                background: white;
                display: block !important;
            }
            
            body {
                padding: 0 !important;
                margin: 0 !important;
                background: white !important;
            }
            
            .receipt {
                width: 100%;
                max-width: 100%;
                margin: 0 !important;
                padding: 0 !important;
                box-shadow: none;
                border-radius: 0;
            }
            
            .receipt-content {
                padding: 1mm 2mm 2mm 2mm !important;
                margin: 0 !important;
            }
            
            @page {
                size: 80mm auto;
                margin: 0mm;
            }
            
            .no-print {
                display: none !important;
            }
            
            /* --- MAXIMUM VISIBILITY & CONTRAST --- */
            body, .receipt, .receipt-content, .info-row, .item-row, .total-row {
                font-family: 'Courier New', 'Monaco', monospace !important;
                font-size: 11pt !important;      /* even larger base */
                line-height: 1.5 !important;     /* more breathing */
                color: #000 !important;          /* pure black */
                background: white !important;
            }
            
            .shop-name {
                font-size: 18pt !important;
                font-weight: 900 !important;     /* extra bold */
                text-align: center !important;
                letter-spacing: 2px !important;
                margin-bottom: 4mm !important;
            }
            
            .shop-address, .shop-contact {
                font-size: 10pt !important;
                font-weight: bold !important;
                text-align: center !important;
                margin-bottom: 2mm !important;
            }
            
            .divider, .divider-dotted, .divider-double {
                margin: 2.5mm 0 !important;
            }
            
            .divider {
                border-top: 1px dashed #000 !important;
            }
            
            .divider-double {
                border-top: 2px solid #000 !important;
            }
            
            .info-row {
                display: flex !important;
                justify-content: space-between !important;
                margin-bottom: 2mm !important;
                font-size: 10pt !important;
                font-weight: bold !important;
            }
            
            .info-label {
                font-weight: 900 !important;
            }
            
            .items-header, .item-row {
                display: flex !important;
                width: 100% !important;
                font-size: 10pt !important;
            }
            
            .items-header {
                font-weight: 900 !important;
                border-bottom: 2px solid #000 !important;
                margin-bottom: 2.5mm !important;
                padding-bottom: 1.5mm !important;
            }
            
            .item-row {
                border-bottom: 1px dotted #000 !important;
                padding: 2mm 0 !important;
            }
            
            /* Fixed column widths - ensure alignment */
            .col-sr { width: 10%; text-align: center; }
            .col-product { width: 38%; text-align: left; }
            .col-qty { width: 10%; text-align: center; }
            .col-price { width: 14%; text-align: right; }
            .col-discount { width: 10%; text-align: right; }
            .col-total { width: 18%; text-align: right; }
            
            .product-name {
                font-size: 10pt !important;
                font-weight: bold !important;
                word-break: break-word;
            }
            
            .totals-box {
                margin-top: 4mm !important;
                padding: 2mm 0 !important;
            }
            
            .total-row {
                display: flex !important;
                justify-content: space-between !important;
                margin-bottom: 2mm !important;
                font-size: 10pt !important;
                font-weight: bold !important;
            }
            
            .grand-total {
                font-size: 14pt !important;
                font-weight: 900 !important;
                border-top: 2px dashed #000 !important;
                margin-top: 3mm !important;
                padding-top: 3mm !important;
            }
            
            .barcode {
                text-align: center !important;
                font-family: monospace !important;
                font-size: 13pt !important;
                letter-spacing: 3px !important;
                margin: 4mm 0 !important;
                font-weight: bold !important;
            }
            
            .exchange-box {
                margin-top: 4mm !important;
                padding: 2.5mm !important;
                border: 1px solid #000 !important;   /* solid for clarity */
                font-size: 9pt !important;
                line-height: 1.4 !important;
                font-weight: bold !important;
            }
            
            .exchange-box p {
                margin: 1.5mm 0 !important;
            }
            
            .thankyou {
                font-size: 16pt !important;
                font-weight: 900 !important;
                text-align: center !important;
                margin: 4mm 0 2mm !important;
                letter-spacing: 1px !important;
            }
            
            .footer-note, .signature {
                font-size: 9pt !important;
                font-weight: bold !important;
                text-align: center !important;
                margin-top: 2.5mm !important;
            }
            
            /* Prevent page breaks inside receipt */
            .receipt, .receipt-content {
                page-break-inside: avoid !important;
                break-inside: avoid !important;
            }
        }
        
        /* Screen styles (unchanged, only for preview) */
        .shop-name {
            font-size: 18px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 2px;
            margin-bottom: 6px;
            color: #000000;
        }
        .shop-address, .shop-contact {
            font-size: 9px;
            text-align: center;
            text-transform:capitalize;
        }
        .divider-double { border-top: 2px solid #333; margin: 6px 0; }
        .divider { border-top: 1px dashed #aaa; margin: 6px 0; }
        .divider-dotted { border-top: 1px dotted #888; margin: 5px 0; }
        .info-row { display: flex; justify-content: space-between; font-size: 9px; margin-bottom: 4px; color:#000;font-weight:700; }
        .info-label { font-weight: bold; color: #000000; }
        .payment-badge { display: inline-block; padding: 2px 8px; background: #e6f7e6; border-radius: 12px; font-size: 8px; font-weight: bold; color: #000000; }
        .items-header { display: flex; font-size: 9px; font-weight: bold; border-bottom: 1px solid #333; padding-bottom: 4px; margin-bottom: 5px; background: #f9fafb; padding: 4px 0; }
        .item-row { display: flex; font-size: 9px; padding: 4px 0; border-bottom: 1px dotted #ddd; font-weight:700;color:#000; }
        .col-sr { width: 10%; text-align: center; }
        .col-product { width: 38%; text-align: left; }
        .col-qty { width: 10%; text-align: center; color:#000;}
        .col-price { width: 14%; text-align: right; }
        .col-discount { width: 10%; text-align: right; }
        .col-total { width: 18%; text-align: right; }
        .totals-box { margin-top: 8px; background: #f9fafb; padding: 8px; border-radius: 4px; }
        .total-row { display: flex; justify-content: space-between; font-size: 9px; margin-bottom: 5px; }
        .grand-total { font-size: 12px; font-weight: bold; border-top: 1px dashed #333; margin-top: 6px; padding-top: 6px; color: #000000; }
        .barcode { text-align: center; font-family: monospace; font-size: 11px; letter-spacing: 2px; margin: 10px 0; background: #f3f3f3; padding: 4px; border-radius: 4px; }
        .exchange-box { background: #fef9e6; border: 1px dashed #ccb; padding: 5px; margin-top: 8px; font-size: 7px; border-radius: 4px; }
        .thankyou { font-size: 12px; font-weight: bold; text-align: center; margin: 12px 0 6px; color: #000000; }
        .footer-note, .signature { font-size: 7px; text-align: center; margin-top: 8px; }
    </style>
</head>
<body>
<div class="receipt">
    <div class="receipt-content">
        <!-- Header -->
        <div class="text-center">
            <div class="shop-name" style="text-align:center;"><?php echo $tx ?? 'ATR Software'; ?></div>
            <div class="shop-address">Allama Iqbal road near daim clinical<br> opposite MCB bank pattoki</div>
            <div class="shop-contact"> Phone: 0326-1737853 | 0307-4699434</div>
            <div class="divider-double"></div>
        </div>
        
        <!-- Invoice Info -->
        <div class="info-row"><span class="info-label">Invoice #:</span><span><?php echo $orderId; ?></span></div>
        <div class="info-row"><span class="info-label">Date:</span><span><?php echo $dateTime; ?></span></div>
        <div class="info-row"><span class="info-label">Cashier:</span><span><?php echo $loginUser; ?></span></div>
        <div class="divider-dotted"></div>
        
        <!-- Customer -->
        <?php if($customerName && $customerName != 'walkin' && $customerName != ''): ?>
        <div class="info-row"><span class="info-label">Customer:</span><span><?php echo htmlspecialchars($customerName); ?></span></div>
        <div class="info-row"><span class="info-label">Phone:</span><span><?php echo $customerPhone; ?></span></div>
        <?php else: ?>
        <div class="info-row"><span class="info-label">Customer:</span><span>Walk-in Customer</span></div>
        <?php endif; ?>
        
        <div class="info-row">
            <span class="info-label">Payment:</span>
            <span><span class="payment-badge"><?php 
                $paymentIcons = ['cash' => '💰', 'credit' => '💳', 'bank1' => '🏦', 'bank2' => '🏦', 'bank3' => '🏦'];
                echo ($paymentIcons[strtolower($paidBy)] ?? '💰') . ' ' . ucfirst($paidBy);
            ?></span></span>
        </div>
        
        <div class="divider"></div>
        
        <!-- Items Header -->
        <div class="items-header">
            <div class="col-sr">#</div>
            <div class="col-product">Item</div>
            <div class="col-qty">Qty</div>
            <div class="col-price">Price</div>
            <div class="col-discount">Dis</div>
            <div class="col-total">Total</div>
        </div>
        
        <!-- Items -->
        <?php $sr = 1; foreach ($orderDetails as $order): ?>
        <div class="item-row">
            <div class="col-sr"><?php echo $sr++; ?></div>
            <div class="col-product"><div class="product-name"><?php echo htmlspecialchars($order['product_name']); ?></div></div>
            <div class="col-qty"><?php echo $order['product_quantity']; ?></div>
            <div class="col-price"><?php echo number_format(floatval($order['product_price']), 0); ?></div>
            <div class="col-discount"><?php echo floatval($order['disc_amount']); ?></div>
            <div class="col-total"><?php echo number_format(floatval($order['net_amount']), 0); ?></div>
        </div>
        <?php endforeach; ?>
        
        <div class="divider"></div>
        
        <!-- Totals -->
        <div class="totals-box">
            <div class="total-row"><span class="total-label">Subtotal:</span><span>Rs. <?php echo number_format($totalSub, 0); ?>/-</span></div>
            <?php if($discounted > 0): ?>
            <div class="total-row"><span class="total-label">Discount:</span><span>- Rs. <?php echo number_format($discounted, 0); ?>/-</span></div>
            <?php endif; ?>
            <div class="total-row"><span class="total-label">Total Amount:</span><span>Rs. <?php echo number_format($discountedAmount, 0); ?>/-</span></div>
            <?php if($preAmount > 0): ?>
            <div class="total-row"><span class="total-label">Previous Due:</span><span>Rs. <?php echo number_format($preAmount, 0); ?>/-</span></div>
            <?php endif; ?>
            <div class="total-row grand-total"><span class="total-label">GRAND TOTAL:</span><span>Rs. <?php echo number_format($close, 0); ?>/-</span></div>
            <?php if($paidBy == 'cash' && $cashAmount > 0): ?>
            <div class="total-row"><span class="total-label">Cash Received:</span><span>Rs. <?php echo number_format($cashAmount, 0); ?>/-</span></div>
            <div class="total-row"><span class="total-label">Change:</span><span>Rs. <?php echo number_format(abs($changeAmount), 0); ?>/-</span></div>
            <?php endif; ?>
        </div>
        
        <div class="divider-double"></div>
        
        <!-- Barcode -->
        <div class="barcode">* <?php echo $orderId; ?> *</div>
        
        <!-- Exchange Policy -->
        <div class="exchange-box">
            <strong>📋 Exchange Policy</strong>
            <p>✓ Exchanges accepted within 7 days</p>
            <p>✓ Original condition with tags attached</p>
            <p>✓ Valid receipt required</p>
        </div>
        
        <!-- Footer -->
        <div class="thankyou">✨ THANK YOU! ✨</div>
        <div class="footer-note">This is a computer generated invoice | No signature required</div>
        <div class="signature">Authorized Signature</div>
    </div>
    
    <div class="button-group no-print">
        <button class="btn-print" onclick="window.print();">🖨️ Print Receipt</button>
        <button class="btn-exit" onclick="window.location.href='order_detail_v.php'">✖️ Exit</button>
    </div>
</div>

<script>
window.onbeforeprint = function() {
    document.querySelectorAll('.button-group').forEach(btn => btn.style.display = 'none');
};
window.onafterprint = function() {
    document.querySelectorAll('.button-group').forEach(btn => btn.style.display = 'flex');
};
document.addEventListener('keydown', function(e) {
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
});
</script>
</body> 
</html>