<?php
include("../db/cn.php");
include("common/tx.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 = null;

// Variable to store total quantity
$totalQty = 0;

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 = $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'];
        $pre = $order['pre_amount'];
        $close = $order['grand_amount'];
    }
}

$content = ob_get_clean();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($customerName) && is_numeric($changeAmount)) {
        $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);

            if ($updateResult) {
                echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Update failed: " . mysqli_error($connection) . "</p>";
            }
        } 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);

            if ($insertResult) {
                echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Insert failed: " . mysqli_error($connection) . "</p>";
            }
        }
    }
}
?>

<!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 htmlspecialchars($orderId); ?></title>
    
    <!-- ====== PDF DOWNLOAD KE LIYE CDN (client‑side) ====== -->
    <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>
        /* SpeedX 72.1mm Thermal Printer Optimized Styles */
        * {
            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 */
        .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 Lines */
        .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 Table */
        .items-header {
            display: flex;
            font-weight: 900;
            border-bottom: 1px solid #000;
            padding-bottom: 1mm;
            margin-bottom: 1mm;
            font-size: 7px;
        }

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

        .col-qty { width: 8%; text-align: center; }
        .col-item { width: 35%; padding-left: 1mm; }
        .col-unit { width: 12%; text-align: center; }
        .col-price { width: 18%; text-align: right; }
        .col-disc { width: 12%; text-align: right; }
        .col-total { width: 15%; text-align: right; padding-right: 1mm; }

        /* Qty Summary Row */
        .qty-summary-row {
            display: flex;
            font-size: 7px;
            margin-top: 0.5mm;
            margin-bottom: 1mm;
            font-weight: 700;
            border-top: 1px dashed #000;
            padding-top: 1mm;
        }

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

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

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

        /* Grand Total - Thermal Optimized */
        .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: 12px;
        }

        /* Exchange Policy */
        .policy-section {
            margin: 2mm 0;
            padding: 1.5mm;
            border: 1px dashed #000;
            font-size: 6px;
            font-weight: 600;
        }

        .policy-title {
            font-weight: 900;
            text-align: center;
            margin-bottom: 1mm;
            font-size: 7px;
        }

        /* Footer */
        .footer {
            text-align: center;
            margin-top: 3mm;
            font-size: 7px;
            font-weight: 600;
        }

        .thank-you {
            font-weight: 900;
            font-size: 10px;
            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: 16px;
            letter-spacing: 2px;
            font-weight: 900;
        }

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

        /* Print Controls */
        .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: #dc3545;
            color: white;
        }

        /* ---- Naya PDF Button ---- */
        .btn-pdf {
            background: #ffc107;
            color: #000;
        }

        /* Thermal Print Specific - Force dark print */
        @media print {
            body {
                width: 72.1mm;
                margin: 0 !important;
                padding: 0 !important;
                font-weight: 600;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
            
            .thermal-receipt {
                padding: 2mm !important;
                margin: 0 !important;
            }
            
            .print-controls, .no-print {
                display: none !important;
            }
            
            @page {
                size: 72.1mm auto;
                margin: 0 !important;
            }
            
            * {
                color: #000 !important;
                text-shadow: none !important;
            }
            
            .grand-total-row, .shop-name, .invoice-title, .thank-you, 
            .items-header, .summary-line.bold, .policy-title, .qty-summary-row .col-item {
                font-weight: 900 !important;
            }
        }

        /* Screen Preview */
        @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;
            }
        }

        /* Utility */
        .text-center { text-align: center; }
        .text-right { text-align: right; }
        .text-left { text-align: left; }
        .bold { font-weight: 900; }
        .small { font-size: 6px; font-weight: 600; }
        .indent { margin-left: 15%; }
    </style>
</head>
<body>
    <!-- id="receipt" add kiya taaki PDF capture kar sake -->
    <div class="thermal-receipt" id="receipt">
        <!-- Header -->
        <div class="header">
            <div class="shop-name"><?php echo htmlspecialchars($tx); ?></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, 16)); ?></span>
            <span><?php echo htmlspecialchars($customerPhone ?? ''); ?></span>
        </div>
        <div class="info-line">
            <span>Cashier: <?php echo htmlspecialchars(substr($loginUser ?? 'Admin', 0, 13)); ?></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">Q</div>
            <div class="col-item">Item</div>
            <!--<div class="col-unit">Unit</div>-->
            <div class="col-price">Price</div>
            <div class="col-disc">Disc</div>
            <div class="col-total">Total</div>
        </div>

        <!-- Items List -->
        <?php 
        $subTotal = 0;
        $totalDiscount = 0;
        $totalQty = 0;
        foreach ($orderDetails as $order): 
            $subTotal += $order['net_amount'];
            $totalQty += intval($order['product_quantity']);
            $itemDiscount = isset($order['discount']) ? ($order['product_price'] * $order['product_quantity'] * $order['discount'] / 100) : 0;
            $totalDiscount += $itemDiscount;
        ?>
        <div class="item-row">
            <div class="col-qty"><?php echo $order['product_quantity']; ?></div>
            <div class="col-item">
                <?php 
                $productName = htmlspecialchars($order['product_name'] ?? '');
                echo strlen($productName) > 13 ? substr($productName, 0, 11) . '.' : $productName;
                ?>
            </div>
            <!--<div class="col-unit"><?php echo htmlspecialchars($order['product_unit'] ?? 'pcs'); ?></div>-->
            <div class="col-price"><?php echo number_format($order['product_price'] ?? 0, 0); ?></div>
            <div class="col-disc"><?php echo isset($order['discount']) && $order['discount'] > 0 ? $order['discount'].'%' : '-'; ?></div>
            <div class="col-total"><?php echo number_format($order['net_amount'] ?? 0, 0); ?></div>
        </div>
        <?php if(isset($order['discount']) && $order['discount'] > 0): ?>
        <div class="item-row small indent">
            <div class="col-qty"></div>
            <div class="col-item">Discount Applied</div>
            <div class="col-unit"></div>
            <div class="col-price"></div>
            <div class="col-disc"></div>
            <div class="col-total">-<?php echo number_format($itemDiscount, 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-unit"></div>
            <div class="col-price"></div>
            <div class="col-disc"></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($subTotal + $totalDiscount, 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($taxAmount > 0): ?>
        <div class="summary-line">
            <span>Tax:</span>
            <span>Rs. <?php echo number_format($taxAmount, 0); ?></span>
        </div>
        <?php endif; ?>
        
        <div class="summary-line bold">
            <span>Net Amount:</span>
            <span>Rs. <?php echo number_format($discountedAmount ?? 0, 0); ?></span>
        </div>
        
        <div class="summary-line">
            <span>Prev Balance:</span>
            <span>Rs. <?php echo number_format(@(int)$pre, 0); ?></span>
        </div>

        <!-- Grand Total - Thermal Optimized -->
        <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>

        <!-- Exchange Policy -->
        <div class="policy-section">
            <div class="policy-title">EXCHANGE POLICY</div>
            <div>Exchange within 7 days</div>
            <div>Original condition with tags</div>
            <div>Valid receipt required</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</button>
        <!-- Naya Download PDF button -->
        <button class="btn btn-pdf" onclick="downloadPDF()">Download PDF</button>
        <button class="btn btn-exit" onclick="window.location.href='mainpos.php'">Exit</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;
                    font-weight: 600 !important;
                    -webkit-print-color-adjust: exact !important;
                    print-color-adjust: exact !important;
                    color-adjust: exact !important;
                }
                * {
                    color: #000 !important;
                    font-weight: 600 !important;
                }
                .grand-total-row, .shop-name, .invoice-title, .thank-you, 
                .items-header, .summary-line.bold, .policy-title, .qty-summary-row .col-item {
                    font-weight: 900 !important;
                }
            `;
            document.head.appendChild(style);
            
            setTimeout(function() {
                window.print();
            }, 100);
        }

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

        // ========== PDF DOWNLOAD (Client‑Side) ==========
        function downloadPDF() {
            const receipt = document.getElementById('receipt');
            html2canvas(receipt, {
                scale: 2,               // high resolution
                useCORS: true,
                logging: false,
                backgroundColor: '#ffffff'
            }).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = 72.1;  // thermal receipt width in mm
                const pageHeight = (imgWidth * canvas.height) / canvas.width;
                
                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF({
                    orientation: 'portrait',
                    unit: 'mm',
                    format: [imgWidth, pageHeight]
                });
                
                pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, pageHeight);
                pdf.save('invoice_<?php echo $orderId; ?>.pdf');
            }).catch(error => {
                alert('PDF generation failed: ' + error);
            });
        }

        // ESC key to close
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                window.location.href = 'mainpos.php';
            }
            if (e.key === 'Enter' && e.ctrlKey) {
                e.preventDefault();
                thermalPrint();
            }
            if (e.key === 'p' && e.ctrlKey) {
                e.preventDefault();
                thermalPrint();
            }
        });

        // Auto print on load
        window.onload = function() {
            setTimeout(function() { thermalPrint(); }, 200);
        };
    </script>
</body>
</html>