<?php
include("../db/cn.php");
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 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'];
        $rent = $order['rent'];
        
        /* CALCULATE TOTALS */
        $totalSub = 0;
        $totalQty = 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']);
            $totalQty += intval($tt['product_quantity']);
        }

        if (!isset($discounted)) { $discounted = 0; }
        $discounted = floatval($discounted);
        $discountedAmount = floatval($totalSub) - floatval($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) + floatval($preAmount) + floatval($rent);
        $cashAmount = floatval($cashAmount ?? 0);
        $changeAmount = floatval($cashAmount) - floatval($close);
    }
}

// ========== HTML STARTS HERE ==========
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thermal Print - <?php echo $orderId; ?></title>
    
    <!-- ====== CDN LIBRARIES FOR PDF DOWNLOAD ====== -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <style>
        /* Your original CSS remains exactly the same */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Courier New', 'Monospace', monospace;
            background: #fff;
            margin: 0;
            padding: 0;
            width: 72.1mm;
            max-width: 72.1mm;
            font-size: 10px;
            line-height: 1.2;
            font-weight: 600;
            color: #000;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
            color-adjust: exact !important;
        }

        .thermal-receipt {
            width: 72.1mm;
            max-width: 72.1mm;
            margin: 0 auto;
            padding: 3mm 2mm;
            background: white;
        }

        .header {
            text-align: center;
            margin-bottom: 2mm;
            border-bottom: 1px dashed #000;
            padding-bottom: 2mm;
        }

        .shop-name {
            font-size: 16px;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 1mm;
        }

        .shop-address {
            font-size: 8px;
            line-height: 1.2;
            font-weight: 600;
        }

        .shop-contact {
            font-size: 9px;
            font-weight: 900;
            margin-top: 1mm;
        }

        .invoice-title {
            font-size: 12px;
            font-weight: 900;
            margin: 2mm 0;
            text-transform: uppercase;
        }

        .info-line {
            display: flex;
            justify-content: space-between;
            font-size: 8px;
            margin-bottom: 0.8mm;
            font-weight: 600;
        }

        .divider {
            border-top: 1px dashed #000;
            margin: 2mm 0;
        }

        .divider-solid {
            border-top: 1px solid #000;
            margin: 2mm 0;
        }

        .divider-double {
            border-top: 2px solid #000;
            margin: 2mm 0;
        }

        .items-header {
            display: flex;
            font-weight: 900;
            border-bottom: 1px solid #000;
            padding-bottom: 1mm;
            margin-bottom: 1mm;
            font-size: 8px;
        }

        .item-row {
            display: flex;
            font-size: 8px;
            margin-bottom: 0.8mm;
            font-weight: 600;
        }

        .col-qty { width: 10%; text-align: center; }
        .col-item { width: 42%; padding-left: 1mm; }
        .col-price { width: 20%; text-align: right; }
        .col-total { width: 28%; text-align: right; padding-right: 1mm; }

        .qty-summary-row {
            display: flex;
            font-size: 8px;
            margin-top: 0.5mm;
            margin-bottom: 1mm;
            font-weight: 700;
            border-top: 1px dashed #000;
            padding-top: 1mm;
        }

        .summary-line {
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            margin-bottom: 0.8mm;
            font-weight: 600;
        }

        .summary-line.bold {
            font-weight: 900;
        }

        .summary-line.total {
            font-weight: 900;
            font-size: 10px;
            border-top: 1px solid #000;
            padding-top: 1.5mm;
            margin-top: 1.5mm;
        }

        .grand-total-container {
            margin: 2mm 0;
        }

        .grand-total-box {
            border-top: 2px solid #000;
            border-bottom: 2px solid #000;
            padding: 1.5mm 0;
            margin: 1mm 0;
        }

        .grand-total-row {
            display: flex;
            justify-content: space-between;
            font-weight: 900;
            font-size: 14px;
        }

        .payment-info {
            margin-top: 2mm;
            padding: 1.5mm 0;
            border-top: 1px dashed #000;
            border-bottom: 1px dashed #000;
        }

        .footer {
            text-align: center;
            margin-top: 3mm;
            font-size: 8px;
            font-weight: 600;
        }

        .thank-you {
            font-weight: 900;
            font-size: 11px;
            margin: 2mm 0;
            text-transform: uppercase;
        }

        .barcode-placeholder {
            text-align: center;
            margin: 2mm 0;
            font-family: 'Courier New', monospace;
            font-weight: 600;
        }

        .barcode-text {
            font-family: monospace;
            font-size: 18px;
            letter-spacing: 2px;
            font-weight: 900;
        }

        .urdu-text {
            font-weight: 700;
            color: #000;
            font-size: 8px;
            margin-top: 1mm;
        }

        .print-controls {
            position: fixed;
            bottom: 20px;
            right: 20px;
            display: flex;
            gap: 10px;
            z-index: 1000;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            font-size: 14px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            font-family: Arial, sans-serif;
        }

        .btn-print {
            background: #28a745;
            color: white;
        }

        .btn-thermal {
            background: #007bff;
            color: white;
        }

        .btn-exit {
            background: #6c757d;
            color: white;
        }

        /* New PDF button */
        .btn-pdf {
            background: #dc3545;
            color: white;
        }

        @media print {
            body {
                width: 72.1mm;
                margin: 0 !important;
                padding: 0 !important;
                font-weight: 600;
            }
            .print-controls, .no-print {
                display: none !important;
            }
            @page {
                size: 72.1mm auto;
                margin: 0 !important;
            }
        }

        @media screen {
            body {
                background: #e0e0e0;
                display: flex;
                justify-content: center;
                padding: 20px;
            }
            .thermal-receipt {
                box-shadow: 0 5px 15px rgba(0,0,0,0.2);
                background: white;
            }
        }

        .small { font-size: 7px; font-weight: 600; }
        .indent { margin-left: 15%; }
        .discount-row { color: #000; font-weight: 600; }
    </style>
</head>
<body>
    <div class="thermal-receipt" id="receipt">
        <!-- Header -->
        <div class="header">
            <div class="shop-name">IBRAHIM TRADERS</div>
            <div class="shop-address">Ahmed Pura St#3 Numaniya Road</div>
            <div class="shop-address">Gujranwala</div>
            <div class="shop-contact">0321-7407080 | 0334-2107080</div>
            <div class="invoice-title">SALE INVOICE</div>
        </div>

        <!-- Order Info -->
        <div class="info-line">
            <span>Order #: <?php echo htmlspecialchars($orderId ?? ''); ?></span>
            <span><?php echo date('d-m-Y h:i A', strtotime($dateTime ?? date('Y-m-d H:i:s'))); ?></span>
        </div>
        <div class="info-line">
            <span>Cust: <?php echo htmlspecialchars(substr($customerName ?? 'Walk-in', 0, 18)); ?></span>
            <span><?php echo htmlspecialchars($customerPhone ?? ''); ?></span>
        </div>
        <div class="info-line">
            <span>Cashier: <?php echo htmlspecialchars(substr($loginUser ?? 'Admin', 0, 15)); ?></span>
            <span>Pay: <?php echo ucfirst(htmlspecialchars($paidBy ?? 'Cash')); ?></span>
        </div>

        <div class="divider"></div>

        <!-- Items Table Header -->
        <div class="items-header">
            <div class="col-qty">Qty</div>
            <div class="col-item">Item</div>
            <div class="col-price">Price</div>
            <div class="col-total">Total</div>
        </div>

        <!-- Items List -->
        <?php foreach ($orderDetails as $order): ?>
        <div class="item-row">
            <div class="col-qty"><?php echo $order['product_quantity']; ?></div>
            <div class="col-item"><?php echo $order['product_name']; ?></div>
            <div class="col-price"><?php echo number_format($order['product_price'], 0); ?></div>
            <div class="col-total"><?php echo number_format($order['net_amount'], 0); ?></div>
        </div>
        <?php if($order['disc_amount'] > 0): ?>
        <div class="item-row small indent discount-row">
            <div class="col-qty"></div>
            <div class="col-item">Discount</div>
            <div class="col-price"></div>
            <div class="col-total">-<?php echo number_format($order['disc_amount'], 0); ?></div>
        </div>
        <?php endif; ?>
        <?php endforeach; ?>

        <!-- QTY Summary Row -->
        <div class="qty-summary-row">
            <div class="col-qty"><?php echo $totalQty; ?></div>
            <div class="col-item" style="font-weight: 900;">Total Items</div>
            <div class="col-price"></div>
            <div class="col-total"></div>
        </div>

        <div class="divider"></div>

        <!-- Summary -->
        <div class="summary-line">
            <span>Bill Amount:</span>
            <span>Rs. <?php echo number_format($totalSub ?? 0, 0); ?></span>
        </div>
        <?php if($discounted > 0): ?>
        <div class="summary-line">
            <span>Discount:</span>
            <span>-Rs. <?php echo number_format($discounted, 0); ?></span>
        </div>
        <?php endif; ?>
        <?php if(@$rent > 0): ?>
        <div class="summary-line">
            <span>Rent:</span>
            <span>Rs. <?php echo number_format(@$rent, 0); ?></span>
        </div>
        <?php endif; ?>
        <div class="summary-line bold">
            <span>Net Amount:</span>
            <span>Rs. <?php echo number_format((float)$discountedAmount + (float)@$rent, 0); ?></span>
        </div>
        <div class="summary-line">
            <span>Prev Balance:</span>
            <span>Rs. <?php echo number_format($preAmount, 0); ?></span>
        </div>

        <!-- Grand Total -->
        <div class="grand-total-container">
            <div class="grand-total-box">
                <div class="grand-total-row">
                    <span>New Balance:</span>
                    <span>Rs. <?php echo number_format($close ?? 0, 0); ?></span>
                </div>
            </div>
        </div>

        <!-- Barcode -->
        <div class="barcode-placeholder">
            <div class="barcode-text">
                *<?php echo str_pad($orderId ?? '0000', 10, '0', STR_PAD_LEFT); ?>*
            </div>
            <div class="small">Order ID: <?php echo $orderId; ?></div>
            <p class="urdu-text">
                خریدی ہوئی اشیاء کے کوئی گارنٹی نہیں
            </p>
        </div>

        <!-- Footer -->
        <div class="footer">
            <div class="divider-double"></div>
            <div class="thank-you">THANK YOU!</div>
            <div class="small">Visit Again</div>
        </div>
    </div>

    <!-- Print Controls -->
    <div class="print-controls no-print">
        <button class="btn btn-thermal" onclick="thermalPrint()">Thermal Print</button>
        <button class="btn btn-print" onclick="standardPrint()">Standard Print</button>
        <button class="btn btn-pdf" onclick="downloadPDF()">Download PDF</button>
        <button class="btn btn-exit" onclick="window.close()">Close</button>
    </div>

    <script>
        function thermalPrint() {
            var style = document.createElement('style');
            style.innerHTML = `
                @page { size: 72.1mm auto; margin: 0 !important; }
                body { width: 72.1mm !important; margin: 0 !important; padding: 0 !important; }
            `;
            document.head.appendChild(style);
            setTimeout(() => window.print(), 100);
        }

        function standardPrint() {
            window.print();
        }

        // ========== PDF DOWNLOAD USING html2canvas + jsPDF ==========
        function downloadPDF() {
            const receipt = document.getElementById('receipt');
            
            // Use html2canvas to capture the receipt div
            html2canvas(receipt, {
                scale: 2,                 // higher resolution
                useCORS: true,
                logging: false,
                backgroundColor: '#ffffff'
            }).then(canvas => {
                // Convert canvas to image data
                const imgData = canvas.toDataURL('image/png');
                
                // Calculate dimensions in mm (72.1mm wide)
                const imgWidth = 72.1;  // mm
                const pageHeight = (imgWidth * canvas.height) / canvas.width;
                
                // Create jsPDF instance (portrait, mm)
                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF({
                    orientation: 'portrait',
                    unit: 'mm',
                    format: [imgWidth, pageHeight]
                });
                
                // Add the image to the PDF (full page)
                pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, pageHeight);
                
                // Auto download
                pdf.save('invoice_<?php echo $orderId; ?>.pdf');
            }).catch(error => {
                alert('PDF generation failed: ' + error);
            });
        }

        // Auto print on page load
        window.onload = function() {
            // comment out if you don't want auto print
            // setTimeout(() => thermalPrint(), 200); 
        };

        // keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') window.close();
            if (e.ctrlKey && (e.key === 'Enter' || e.key === 'p')) {
                e.preventDefault();
                thermalPrint();
            }
        });
    </script>
</body>
</html>
<?php
ob_end_flush();
?>