<?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 = null;

if ($orderId) {
    $query = "SELECT * FROM log_user_sales WHERE order_id = '$orderId'";
    $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 = floatval($order['net_amount']);
        $paidBy = $order['paid_by'];
        $customerName = $order['customer_name'];
        $customerPhone = $order['customer_phone'];
        $discountedAmount = floatval($order['discount_amount']);
        $discounted = floatval($order['discounted']);
        $discountPer = $order['discount_per'];
        $cashAmount = floatval($order['cash_amount']);
        $changeAmount = floatval($order['change_amount']);
        $taxAmount = $order['tax_amount'];
        $pre = floatval($order['pre_amount']);
        $close = floatval($order['grand_amount']);
    }
}

$content = ob_get_clean();

// Handle exit and update customer balance
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($customerName) && $customerName != 'walkin') {
        $checkQuery = "SELECT 1 FROM creditor_closing WHERE creditor_name = '$customerName' LIMIT 1";
        $checkResult = mysqli_query($connection, $checkQuery);

        if (mysqli_num_rows($checkResult) > 0) {
            $updateQuery = "UPDATE creditor_closing SET remain_balance = $changeAmount WHERE creditor_name = '$customerName'";
            $updateResult = mysqli_query($connection, $updateQuery);
        } else {
            $insertQuery = "INSERT INTO creditor_closing (
                creditor_name, opening_cash, credit_sales, credit_recieved,
                remain_balance, date_time, login_user, user_role,
                outlet_name, outlet_address
            ) VALUES (
                '$customerName', 0, 0, 0, $changeAmount, NOW(), '$loginUser', '$userRole', '$outletName', '$outletAddress'
            )";
            $insertResult = mysqli_query($connection, $insertQuery);
        }
    }
    header("Location: mainpos.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thermal Receipt | <?php echo $tx; ?></title>
    <style>
        /* Thermal Receipt Styles - 80mm width */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: #e8ecf1;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        
        /* Receipt Container - 80mm width */
        .receipt {
            width: 80mm;
            max-width: 80mm;
            background: white;
            margin: 0 auto;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        
        /* Print Styles - Thermal Printer - FIXED EXTRA TOP MARGIN + MAX VISIBILITY */
        @media print {
            /* Remove ALL default browser margins and paddings */
            * {
                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;
                min-height: auto !important;
                height: auto !important;
            }
            
            body {
                padding: 0 !important;
                margin: 0 !important;
                justify-content: normal !important;
                align-items: normal !important;
                background: white !important;
            }
            
            .receipt {
                width: 100%;
                max-width: 100%;
                margin: 0 !important;
                padding: 0 !important;
                box-shadow: none;
                border: none;
            }
            
            .receipt-content {
                padding: 0 2mm 2mm 2mm !important; /* top padding removed to eliminate extra margin */
                margin: 0 !important;
            }
            
            /* Ensure the very first element has no top spacing */
            .receipt-content > :first-child {
                margin-top: 0 !important;
                padding-top: 0 !important;
            }
            
            @page {
                size: 80mm auto;
                margin: 0mm;  /* critical: removes default page margins */
            }
            
            .no-print {
                display: none !important;
            }
            
            /* --- ENHANCED VISIBILITY & DESIGN FOR PRINT --- */
            body, .receipt, .receipt-content, .info-row, .item-row, .total-row {
                font-family: 'Courier New', 'Monaco', monospace !important;
                font-size: 11pt !important;      /* larger base font */
                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;
            }
            
            .divider-dotted {
                border-top: 1px dotted #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;
                Color:#000;
            }
            
            .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: 40%; text-align: left; }
            .col-qty { width: 12%; text-align: center; }
            .col-price { width: 15%; text-align: right; }
            .col-discount { width: 10%; text-align: right; }
            .col-total { width: 13%; text-align: right; }
            
            .product-name {
                font-size: 10pt !important;
                font-weight: bold !important;
                word-break: break-word;
            }
            
            .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-policy {
                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-policy p {
                margin: 1.5mm 0 !important;
            }
            
            .exchange-header {
                font-weight: 900 !important;
                font-size: 10pt !important;
                margin-bottom: 1mm !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) */
        .receipt-content {
            padding: 8px 8px;
        }
        
        .shop-name {
            font-size: 16px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 5px;
            color:#000;
        }
        
        .shop-address {
            font-size: 9px;
            line-height: 1.3;
            margin-bottom: 5px;
        }
        
        .shop-contact {
            font-size: 9px;
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .divider {
            border-top: 1px dashed #000;
            margin: 6px 0;
        }
        
        .divider-double {
            border-top: 2px solid #000;
            margin: 6px 0;
        }
        
        .divider-dotted {
            border-top: 1px dotted #000;
            margin: 5px 0;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            margin-bottom: 3px;
            font-family: 'Courier New', monospace;
            color:#000;
            font-weight:700;
        }
        
        .info-label {
            font-weight: bold;
            color:#000;
        }
        
        .items-header {
            display: flex;
            font-size: 9px;
            font-weight: bold;
            border-bottom: 1px dotted #000;
            padding-bottom: 4px;
            margin-bottom: 4px;
            font-family: 'Courier New', monospace;
        }
        
        .item-row {
            display: flex;
            font-size: 9px;
            padding: 3px 0;
            border-bottom: 1px dotted #eee;
            font-family: 'Courier New', monospace;
        }
        
        .col-sr { width: 10%; text-align: center; }
        .col-product { width: 40%; text-align: left; }
        .col-qty { width: 12%; text-align: center; }
        .col-price { width: 15%; text-align: right; }
        .col-discount { width: 10%; text-align: right; }
        .col-total { width: 13%; text-align: right; }
        
        .product-name {
            font-size: 8px;
            word-break: break-word;
            white-space: normal;
            line-height: 1.2;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            margin-bottom: 4px;
            font-family: 'Courier New', monospace;
        }
        
        .total-label {
            font-weight: bold;
        }
        
        .total-amount {
            font-weight: bold;
        }
        
        .grand-total {
            font-size: 11px;
            font-weight: bold;
            border-top: 1px dashed #000;
            margin-top: 5px;
            padding-top: 5px;
        }
        
        .thankyou {
            font-size: 11px;
            font-weight: bold;
            text-align: center;
            margin: 10px 0 5px;
        }
        
        .footer-note {
            font-size: 7px;
            text-align: center;
            color: #666;
            line-height: 1.3;
        }
        
        .exchange-policy {
            font-size: 7px;
            margin-top: 8px;
            padding: 5px;
            background: #f9f9f9;
            border: 1px dotted #ccc;
        }
        
        .exchange-policy p {
            margin: 2px 0;
        }
        
        .exchange-header {
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .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-print:hover {
            background: #063544;
        }
        
        .btn-exit {
            background: #e5e7eb;
            color: #333;
        }
        
        .btn-exit:hover {
            background: #d1d5db;
        }
        
        .barcode {
            text-align: center;
            font-family: monospace;
            font-size: 10px;
            letter-spacing: 1px;
            margin: 8px 0;
        }
        
        .signature {
            font-size: 8px;
            text-align: center;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px dotted #000;
        }
        
        .payment-badge {
            display: inline-block;
            padding: 2px 6px;
            background: #f0fdf4;
            border-radius: 4px;
            font-size: 8px;
        }
    </style>
</head>
<body>
<div class="receipt">
    <div class="receipt-content">
        <!-- Header Section -->
        <div class="text-center" style="text-align:center;">
            <div class="shop-name" style="text-align:center;"><?php echo $tx; ?></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"></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 Info -->
        <?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>
                <?php 
                    $paymentIcons = ['cash' => '💰', 'credit' => '💳', 'bank1' => '🏦', 'bank2' => '🏦', 'bank3' => '🏦'];
                    echo ($paymentIcons[$paidBy] ?? '💰') . ' ' . ucfirst($paidBy);
                ?>
            </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 List -->
        <?php $sr = 1; ?>
        <?php 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['discount']); ?>%</div>
            <div class="col-total"><?php echo number_format(floatval($order['net_amount']), 0); ?></div>
        </div>
        <?php endforeach; ?>
        
        <div class="divider"></div>
        
        <!-- Calculate totals -->
        <?php
        $subTotal = 0;
        foreach ($orderDetails as $item) {
            $subTotal += floatval($item['product_total']);
        }
        ?>
        
        <!-- Totals Section -->
        <div class="total-row">
            <span class="total-label">Subtotal:</span>
            <span>Rs. <?php echo number_format($subTotal, 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 class="total-amount">Rs. <?php echo number_format($discountedAmount, 0); ?>/-</span>
        </div>
        
        <?php if($pre > 0): ?>
        <div class="total-row">
            <span class="total-label">Previous Due:</span>
            <span>Rs. <?php echo number_format($pre, 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 class="divider-double"></div>
        
        <!-- Barcode -->
        <div class="barcode">
            * <?php echo $orderId; ?> *
        </div>
        
        <!-- Exchange Policy -->
        <div class="exchange-policy">
            <div class="exchange-header">📋 Exchange Policy:</div>
            <p>1. Exchanges accepted within 7 days</p>
            <p>2. Original condition with tags attached</p>
            <p>3. Valid receipt required for exchange</p>
        </div>
        
        <!-- Footer -->
        <div class="thankyou">
            ✨ THANK YOU! ✨
        </div>
        <div class="footer-note">
            This is a computer generated invoice<br>
            No signature required
        </div>
        
        <div class="signature">
            Authorized Signature
        </div>
    </div>
    
    <!-- Buttons - Hidden when printing -->
    <div class="button-group no-print">
        <button class="btn-print" onclick="window.print();">
            🖨️ Print Receipt
        </button>
        <form method="post" style="display:inline;">
            <button type="submit" name="exit" class="btn-exit">
                ✖️ Exit
            </button>
        </form>
    </div>
</div>

<!-- Print Scripts -->
<script>
// Handle print events
window.onbeforeprint = function() {
    var buttons = document.querySelectorAll('.button-group');
    buttons.forEach(function(btn) {
        btn.style.display = 'none';
    });
}

window.onafterprint = function() {
    var buttons = document.querySelectorAll('.button-group');
    buttons.forEach(function(btn) {
        btn.style.display = 'flex';
    });
}

// Keyboard shortcut for print (Ctrl+P)
document.addEventListener('keydown', function(e) {
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
});

// Auto print on page load (optional - uncomment to enable)
// window.onload = function() {
//     setTimeout(function() {
//         window.print();
//     }, 500);
// }
</script>

</body>
</html>