<?php
include("../db/cn.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 HERE, BEFORE HTML OUTPUT
        ------------------------------------------- */
        /* 1) TOTAL NET AMOUNT OF ALL PRODUCTS */
        $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']);
        }

        /* 2) DISCOUNT (ALREADY STORED IN DB) */
        if (!isset($discounted)) { 
            $discounted = 0; 
        }
        
        $discounted = floatval($discounted);

        /* 3) FINAL AMOUNT AFTER DISCOUNT */
        $discountedAmount = floatval($totalSub) - floatval($discounted);

        /* 4) PREVIOUS BALANCE */
        $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);
        }

        /* 5) GRAND TOTAL = Final Amount + Previous Amount */
        $preAmount = floatval($preAmount);
        $close = floatval($discountedAmount) + floatval($preAmount);

        /* 6) CASH AND CHANGE */
        $cashAmount = floatval($cashAmount ?? 0);
        $changeAmount = floatval($cashAmount) - floatval($close);
    }
}

$content = ob_get_clean();

// Function to send data to the printer
function sendToPrinter($result) {
    $printerName = "EPSON_TM_T88V_Receipt";
    $handle = @fopen("USB", "w");
    if (!$handle) {
        // Silently fail - don't show error on screen
        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>
        /* 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;
            font-family: 'Courier New', 'Monaco', monospace;
        }
        
        /* 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 */
        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            .receipt {
                width: 100%;
                max-width: 100%;
                box-shadow: none;
                margin: 0;
                padding: 0;
            }
            .no-print {
                display: none !important;
            }
            @page {
                size: 80mm auto;
                margin: 0mm;
            }
            .receipt-content {
                padding: 2mm 3mm;
            }
        }
        
        .receipt-content {
            padding: 8px 10px;
        }
        
        /* Header Styles */
        .text-center {
            text-align: center;
        }
        
        .text-left {
            text-align: left;
        }
        
        .text-right {
            text-align: right;
        }
        
        .shop-name {
            font-size: 16px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 5px;
        }
        
        .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 */
        .info-row {
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            margin-bottom: 3px;
        }
        
        .info-label {
            font-weight: bold;
        }
        
        /* Items Header */
        .items-header {
            display: flex;
            font-size: 9px;
            font-weight: bold;
            border-bottom: 1px dotted #000;
            padding-bottom: 4px;
            margin-bottom: 4px;
        }
        
        .item-row {
            display: flex;
            font-size: 9px;
            padding: 3px 0;
            border-bottom: 1px dotted #eee;
        }
        
        .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: 8px;
            word-break: break-word;
            white-space: normal;
            line-height: 1.2;
        }
        
        /* Totals */
        .total-row {
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            margin-bottom: 4px;
        }
        
        .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;
        }
        
        /* Footer */
        .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;
        }
        
        /* Buttons */
        .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 */
        .barcode {
            text-align: center;
            font-family: monospace;
            font-size: 10px;
            letter-spacing: 1px;
            margin: 8px 0;
        }
        
        /* Signature */
        .signature {
            font-size: 8px;
            text-align: center;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px dotted #000;
        }
    </style>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<div class="receipt">
    <div class="receipt-content">
        <!-- Header Section -->
        <div class="text-center">
            <div class="shop-name"><?php echo $tx ?? 'ATR Software'; ?></div>
            <div class="shop-address">
                Al Hafeez<br>
                Shop No: 40, 2nd Floor, Kiyani Market<br>
                Bara Bazar, Rawalpindi
            </div>
            <div class="shop-contact">
                ATR Sales & Marketing Services
            </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 date('d-m-Y h:i A', strtotime($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[strtolower($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['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 Section -->
        <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 class="total-amount">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 class="divider-double"></div>
        
        <!-- Barcode -->
        <div class="barcode">
            * <?php echo $orderId; ?> *
        </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>
        <button class="btn-exit" onclick="window.location.href='order_detail_v.php'">
            ✖️ Exit
        </button>
    </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>


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>