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

// Handle deletion request
if (isset($_GET['delete_order_id'])) {
    $deleteOrderId = $_GET['delete_order_id'];
    $deleteQuery = "DELETE FROM log_user_sales WHERE order_id = '$deleteOrderId'";
    mysqli_query($connection, $deleteQuery);
    echo "<script type='text/javascript'>window.location.href = 'order_detail_v.php';</script>";
    exit();
}
// Handle deletion request for refund
if (isset($_GET['delete_r_order_id'])) {
    $deleteOrderId = $_GET['delete_r_order_id'];
    $deleteQuery = "DELETE FROM log_user_sales WHERE r_order_id = '$deleteOrderId'";
    mysqli_query($connection, $deleteQuery);
    echo "<script type='text/javascript'>window.location.href = 'order_detail_v.php';</script>";
    exit();
}

if(isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name'])
 && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];

    // Fetch sale history data
    $saleHistoryResult = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE status = '' ORDER BY date_time DESC");

    // Fetch sale hold data
    $saleHoldResult = mysqli_query($connection, "SELECT * FROM pay_hold WHERE outlet_name = '$outlet_name' && login_user = '$userName' && user_role = '$userRole' && outlet_address = '$outlet_address' ORDER BY date_time DESC");

    // Fetch sale refund data
    $saleRefundResult = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE status = 'refund' ORDER BY date_time DESC");

    // Group sale history data by order ID
    $saleHistoryData = array();
    while ($row = mysqli_fetch_assoc($saleHistoryResult)) {
        $saleHistoryData[] = $row;
    }
    $orderGroups = groupDataByOrderId($saleHistoryData);

    // Group sale hold data by order ID
    $saleHoldData = array();
    while ($row = mysqli_fetch_assoc($saleHoldResult)) {
        $saleHoldData[] = $row;
    }
    $saleHoldGroups = groupDataByOrderId($saleHoldData);

    // Group sale refund data by order ID
    $saleRefundData = array();
    while ($row = mysqli_fetch_assoc($saleRefundResult)) {
        $saleRefundData[] = $row;
    }
    $refundGroups = groupDataByOrderId($saleRefundData);
}
// Close database connection
mysqli_close($connection);

// Function to group data by order ID
function groupDataByOrderId($data) {
    $groups = array();
    foreach ($data as $item) {
        $orderId = $item['order_id'];
        if (!isset($groups[$orderId])) {
            $groups[$orderId] = array();
        }
        $groups[$orderId][] = $item;
    }
    return $groups;
}

// Function to calculate order total
function calculateOrderTotal($products) {
    $total = 0;
    foreach ($products as $product) {
        $inches = floatval($product['inches']);
        $price = floatval($product['product_price']);
        $quantity = floatval($product['product_quantity']);
        $discount = floatval($product['discount']);
        $discAmount = floatval($product['disc_amount']);
        
        $gross = $inches * $price * $quantity;
        
        if ($discount > 0) {
            $discountAmount = ($gross * $discount) / 100;
        } else {
            $discountAmount = $discAmount;
        }
        
        $productTotal = $gross - $discountAmount;
        $total += $productTotal;
    }
    return $total;
}

ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title><?php echo $tx; ?> | Order Management</title>
    <!-- Bootstrap 5 CSS + Icons + Fonts -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f4f7fc;
            overflow-x: hidden;
        }

        /* modern header gradient */
        .modern-header {
            background: linear-gradient(135deg, #1e2a3a 0%, #0f1a24 100%);
            padding: 0.75rem 1.5rem;
            box-shadow: 0 8px 20px rgba(0,0,0,0.08);
            position: sticky;
            top: 0;
            z-index: 1030;
        }

        .logo-brand {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo-brand img {
            border-radius: 14px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
            transition: transform 0.2s ease;
        }

        .logo-brand img:hover {
            transform: scale(1.02);
        }

        .store-title {
            font-weight: 800;
            letter-spacing: 1px;
            font-size: 1.6rem;
            background: linear-gradient(120deg, #F9E0A0, #FFD966);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            text-shadow: none;
        }

        .btn-back-modern {
            background: rgba(255,255,255,0.12);
            backdrop-filter: blur(4px);
            border: 1px solid rgba(255,217,102,0.5);
            color: #FFD966;
            border-radius: 40px;
            padding: 8px 24px;
            font-weight: 600;
            transition: all 0.2s;
        }

        .btn-back-modern:hover {
            background: #FFD966;
            color: #1e2a3a;
            border-color: #FFD966;
            transform: translateY(-2px);
        }

        /* card tabs modern */
        .custom-tabs {
            border: none;
            background: #ffffff;
            border-radius: 20px;
            padding: 6px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.03);
            margin-bottom: 1.2rem;
        }

        .custom-tabs .nav-link {
            border: none;
            border-radius: 40px;
            font-weight: 600;
            padding: 0.6rem 1.6rem;
            color: #3a546d;
            transition: all 0.2s;
            background: transparent;
        }

        .custom-tabs .nav-link.active {
            background: #0f2b3b;
            color: white;
            box-shadow: 0 6px 12px rgba(15,43,59,0.2);
        }

        .custom-tabs .nav-link:hover:not(.active) {
            background: #eef2f7;
            color: #1e4663;
        }

        /* table card style */
        .table-wrapper {
            background: white;
            border-radius: 24px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.05);
            overflow: hidden;
            transition: all 0.2s;
        }

        .table-scroll-area {
            max-height: 580px;
            overflow-y: auto;
            scrollbar-width: thin;
        }

        .table-scroll-area::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        .table-scroll-area::-webkit-scrollbar-track {
            background: #e9ecef;
            border-radius: 10px;
        }

        .table-scroll-area::-webkit-scrollbar-thumb {
            background: #b9cadb;
            border-radius: 10px;
        }

        .order-table {
            margin-bottom: 0;
            font-size: 0.85rem;
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }

        .order-table thead th {
            background: #1e2f3c;
            color: white;
            font-weight: 600;
            font-size: 0.8rem;
            padding: 14px 8px;
            border-bottom: none;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .order-table tbody tr {
            transition: background 0.15s;
            cursor: pointer;
            border-bottom: 1px solid #edf2f7;
        }

        .order-table tbody tr:hover {
            background: #f8fafd;
            transform: scale(1.001);
        }

        .order-table td {
            padding: 12px 8px;
            vertical-align: middle;
            font-weight: 500;
            color: #1f2f3e;
        }

        .badge-order-id {
            background: #eef2ff;
            color: #1e4a76;
            font-family: monospace;
            font-weight: 700;
            font-size: 0.75rem;
            padding: 4px 8px;
            border-radius: 40px;
            display: inline-block;
        }

        .btn-icon-sm {
            width: 32px;
            height: 32px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 12px;
            transition: all 0.2s;
        }

        .btn-print {
            background: #eef2fa;
            color: #2c5f8a;
            border: none;
        }

        .btn-print:hover {
            background: #2c5f8a;
            color: white;
            transform: translateY(-2px);
        }

        .btn-delete {
            background: #ffe9e9;
            color: #c23d3d;
        }

        .btn-delete:hover {
            background: #c23d3d;
            color: white;
        }

        /* single view card */
        .single-view-card {
            background: white;
            border-radius: 28px;
            box-shadow: 0 20px 35px -12px rgba(0,0,0,0.1);
            padding: 1.5rem;
            position: sticky;
            top: 100px;
            transition: all 0.2s;
            border: 1px solid rgba(0,0,0,0.03);
        }

        .order-id-badge-large {
            background: linear-gradient(135deg, #103c4e, #0a2c3a);
            color: #FFE3A4;
            padding: 10px 18px;
            border-radius: 60px;
            font-weight: 700;
            font-size: 1rem;
            display: inline-block;
            letter-spacing: 0.5px;
        }

        .info-row {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 14px;
            font-size: 0.9rem;
            border-bottom: 1px dashed #e9edf2;
            padding-bottom: 10px;
        }

        .info-icon {
            width: 34px;
            height: 34px;
            background: #eef3fc;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: #2b6a9f;
        }

        .summary-line {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            font-weight: 600;
            border-bottom: 1px solid #ecf3f9;
        }

        .summary-grand {
            background: #f0f5fa;
            padding: 12px 16px;
            border-radius: 20px;
            margin-top: 12px;
            font-weight: 800;
        }

        .search-modern {
            border-radius: 60px;
            border: 1px solid #dce5ec;
            padding: 10px 18px;
            font-size: 0.85rem;
            background: #ffffff;
            transition: all 0.2s;
        }

        .search-modern:focus {
            border-color: #8eb3cf;
            box-shadow: 0 0 0 3px rgba(46, 109, 164, 0.1);
            outline: none;
        }

        .filter-label {
            font-weight: 600;
            color: #2c4b6e;
        }

        @media (max-width: 768px) {
            .single-view-card {
                margin-top: 25px;
                position: relative;
                top: 0;
            }
            .store-title {
                font-size: 1.2rem;
            }
            .custom-tabs .nav-link {
                padding: 0.4rem 1rem;
                font-size: 0.8rem;
            }
            .btn-icon-sm {
                width: 28px;
                height: 28px;
            }
        }
    </style>
</head>
<body>

<!-- MODERN HEADER -->
<div class="modern-header">
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-6 col-md-3">
                <div class="logo-brand">
                    <img src="../img/logo231.png" width="52" height="52" alt="Logo">
                    <span class="store-title d-none d-md-block"><?php echo $tx; ?></span>
                </div>
            </div>
            <div class="col-6 col-md-6 text-center">
                <h3 class="store-title mb-0 d-md-none" style="font-size:1.3rem;"><?php echo $tx; ?></h3>
            </div>
            <div class="col-md-3 col-6 text-end">
                <a href="addproduct.php">
                    <button class="btn btn-back-modern"><i class="fas fa-arrow-left me-1"></i> Back</button>
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid py-4">
    <div class="row g-4">
        <!-- LEFT COLUMN: TABS + TABLES -->
        <div class="col-lg-6">
            <!-- Tabs with modern design -->
            <ul class="nav nav-tabs custom-tabs" id="orderTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="saleHistory-tab" data-bs-toggle="tab" data-bs-target="#saleHistory" type="button" role="tab"><i class="fas fa-chart-line me-1"></i> Sale History</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="refund-tab" data-bs-toggle="tab" data-bs-target="#refund" type="button" role="tab"><i class="fas fa-undo-alt me-1"></i> Refund</button>
                </li>
            </ul>

            <div class="tab-content mt-3">
                <!-- SALE HISTORY TAB -->
                <div class="tab-pane fade show active" id="saleHistory" role="tabpanel">
                    <div class="table-wrapper">
                        <div class="p-3 pb-0">
                            <div class="row g-2 align-items-center">
                                <div class="col-auto"><i class="fas fa-search filter-label"></i></div>
                                <div class="col"><input type="text" id="saleOrderID" class="form-control search-modern" placeholder="Search by Order ID, Customer, Product..."></div>
                            </div>
                        </div>
                        <div class="table-scroll-area">
                            <table class="order-table table align-middle">
                                <thead>
                                    <tr>
                                        <th>Date</th><th>Customer</th><th>Order ID</th><th>Amount (Rs)</th><th>Status</th><th>Print</th>
                                        <th>Delete</th>
                                    </tr>
                                </thead>
                                <tbody id="saleHistoryTableBody">
                                    <?php foreach ($orderGroups as $orderId => $group): 
                                        $grandTotal = 0;
                                        foreach ($group as $orderRow) {
                                            $inches = floatval($orderRow['inches']);
                                            $price = floatval($orderRow['product_price']);
                                            $quantity = floatval($orderRow['product_quantity']);
                                            $discount = floatval($orderRow['discount']);
                                            $discAmount = floatval($orderRow['disc_amount']);
                                            
                                            $gross = $inches * $price * $quantity;
                                            
                                            if ($discount > 0) {
                                                $discountAmount = ($gross * $discount) / 100;
                                            } else {
                                                $discountAmount = $discAmount;
                                            }
                                            
                                            $productTotal = $gross - $discountAmount;
                                            $grandTotal += $productTotal;
                                        }
                                        // Add pre_amount and rent if they exist
                                        $preAmount = floatval($group[0]['pre_amount']);
                                        $rentAmount = floatval($group[0]['rent']);
                                        $finalTotal = $grandTotal + $preAmount + $rentAmount;
                                    ?>
                                    <tr class="sale-history-row" data-order-id="<?php echo $orderId; ?>">
                                        <td class="fw-semibold"><?php echo date('Y-m-d', strtotime($group[0]['date_time'])); ?></td>
                                        <td><?php echo htmlspecialchars($group[0]['customer_name']); ?></td>
                                        <td><span class="badge-order-id"><?php echo $orderId; ?></span></td>
                                        <td class="fw-bold"><?php echo number_format($finalTotal, 2); ?></td>
                                        <td><span class="badge bg-success bg-opacity-10 text-success px-3 py-1 rounded-pill"><?php echo $group[0]['paid_by']; ?></span></td>
                                        <td><a href="print_invoice_o.php?order_id=<?php echo $orderId; ?>" target="_blank" class="btn btn-icon-sm btn-print"><i class="fas fa-print"></i></a></td>
                                        <td><a href="order_detail_v.php?delete_order_id=<?php echo $orderId; ?>" onclick="return confirm('Are you sure you want to delete this order?');" class="btn btn-icon-sm btn-delete"><i class="fas fa-trash-alt"></i></a></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- REFUND TAB -->
                <div class="tab-pane fade" id="refund" role="tabpanel">
                    <div class="table-wrapper">
                        <div class="p-3 pb-0">
                            <div class="row g-2 align-items-center">
                                <div class="col-auto"><i class="fas fa-search filter-label"></i></div>
                                <div class="col"><input type="text" id="refundOrderID" class="form-control search-modern" placeholder="Search refund orders..."></div>
                            </div>
                        </div>
                        <div class="table-scroll-area">
                            <table class="order-table table align-middle">
                                <thead>
                                    <tr><th>Date</th><th>Customer</th><th>Order ID</th><th>Amount(Rs)</th><th>Status</th><th>Print</th><th>Delete</th></tr>
                                </thead>
                                <tbody id="refundTableBody">
                                    <?php foreach ($refundGroups as $orderId => $group): 
                                        $refundTotal = 0;
                                        foreach ($group as $orderRow) {
                                            $inches = floatval($orderRow['inches']);
                                            $price = floatval($orderRow['product_price']);
                                            $quantity = floatval($orderRow['product_quantity']);
                                            $discount = floatval($orderRow['discount']);
                                            $discAmount = floatval($orderRow['disc_amount']);
                                            
                                            $gross = $inches * $price * $quantity;
                                            
                                            if ($discount > 0) {
                                                $discountAmount = ($gross * $discount) / 100;
                                            } else {
                                                $discountAmount = $discAmount;
                                            }
                                            
                                            $productTotal = $gross - $discountAmount;
                                            $refundTotal += $productTotal;
                                        }
                                    ?>
                                    <tr class="refund-row" data-order-id="<?php echo $group[0]['r_order_id']; ?>">
                                        <td><?php echo date('Y-m-d', strtotime($group[0]['date_time'])); ?></td>
                                        <td><?php echo htmlspecialchars($group[0]['customer_name']); ?></td>
                                        <td><span class="badge-order-id"><?php echo $group[0]['r_order_id']; ?></span></td>
                                        <td class="fw-bold"><?php echo number_format($refundTotal, 2); ?></td>
                                        <td><span class="badge bg-warning bg-opacity-10 text-dark px-3 py-1 rounded-pill"><?php echo $group[0]['paid_by']; ?></span></td>
                                        <td><a href="print_invoice_r.php?order_id=<?php echo $group[0]['r_order_id']; ?>" target="_blank" class="btn btn-icon-sm btn-print"><i class="fas fa-print"></i></a></td>
                                        <td><a href="order_detail_v.php?delete_r_order_id=<?php echo $group[0]['r_order_id']; ?>" onclick="return confirm('Are you sure you want to delete this Refund order?');" class="btn btn-icon-sm btn-delete"><i class="fas fa-trash-alt"></i></a></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- RIGHT COLUMN: SINGLE VIEW (DETAILS CARD) -->
        <div class="col-lg-6">
            <div class="single-view-card" id="singleViewContainer">
                <div class="text-center text-muted py-5">
                    <i class="fas fa-receipt fa-3x mb-3 opacity-25"></i>
                    <p class="mb-0">Click on any order row to see full details</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>

<script>
// PHP DATA INJECTION
const orderGroups = <?php echo json_encode($orderGroups); ?>;
const refundGroups = <?php echo json_encode($refundGroups); ?>;

// Format currency
function formatMoney(value) {
    return parseFloat(value).toFixed(2);
}

// Calculate order total from products
function calculateOrderTotalFromProducts(products) {
    let total = 0;
    products.forEach(prod => {
        let inches = parseFloat(prod.inches) || 0;
        let price = parseFloat(prod.product_price) || 0;
        let quantity = parseFloat(prod.product_quantity) || 0;
        let discount = parseFloat(prod.discount) || 0;
        let discAmount = parseFloat(prod.disc_amount) || 0;
        
        let gross = inches * price * quantity;
        let discountAmount = discount > 0 ? (gross * discount) / 100 : discAmount;
        let productTotal = gross - discountAmount;
        total += productTotal;
    });
    return total;
}

// Populate Single View
function populateSingleView(orderId, products, sales, type = 'history') {
    if (!products || products.length === 0) {
        document.getElementById('singleViewContainer').innerHTML = `<div class="text-center text-danger p-4">No details found for order ${orderId}</div>`;
        return;
    }

    let subtotal = calculateOrderTotalFromProducts(products);
    let rowsHtml = '';

    products.forEach(prod => {
        let qty = parseFloat(prod.product_quantity) || 0;
        let inches = parseFloat(prod.inches) || 0;
        let price = parseFloat(prod.product_price) || 0;
        let saleCost = parseFloat(prod.sale_cost) || 0;
        let discount = parseFloat(prod.discount) || 0;
        let discAmount = parseFloat(prod.disc_amount) || 0;
        
        let gross = inches * price * qty;
        let discountAmount = discount > 0 ? (gross * discount) / 100 : discAmount;
        let productTotal = gross - discountAmount;
        
        let perUnitSaleCost = (qty > 0 && saleCost > 0) ? (saleCost / qty) : 0;
        let updatedSaleCost = perUnitSaleCost * qty;

        rowsHtml += `<tr>
            <td class="fw-semibold">${prod.product_name}</td>
            <td>${prod.category || '-'}</td>
            <td><span class="badge bg-dark bg-opacity-10 px-2 py-1 rounded">${qty}</span></td>
            <td>${inches}</td>
            <td>${formatMoney(price)}</td>
            <td>${formatMoney(updatedSaleCost)}</td>
            <td>${formatMoney(gross)}</td>
            <td>${formatMoney(discountAmount)}</td>
            <td class="fw-bold">${formatMoney(productTotal)}</td>
            <td class="fw-bold">${prod.p_type}</td>
        </tr>`;
    });

    let discountTotal = parseFloat(sales[0]?.discounted) || 0;
    let preAmount = parseFloat(sales[0]?.pre_amount) || 0;
    let rentAmount = parseFloat(sales[0]?.rent) || 0;
    let totalAfterDisc = subtotal - discountTotal;
    let grandTotal = totalAfterDisc + preAmount + rentAmount;
    let paidBy = sales[0]?.paid_by || 'N/A';
    let cashAmount = parseFloat(sales[0]?.cash_amount) || 0;
    let changeAmount = parseFloat(sales[0]?.change_amount) || 0;

    let html = `
        <div class="d-flex justify-content-between align-items-center flex-wrap mb-4">
            <div class="order-id-badge-large"><i class="fas fa-hashtag me-1"></i> ${orderId}</div>
            <small class="text-muted"><i class="far fa-calendar-alt me-1"></i> ${sales[0]?.date_time || ''}</small>
        </div>
        <div class="info-row"><div class="info-icon"><i class="fas fa-user"></i></div><div><strong>Customer:</strong> ${sales[0]?.customer_name || '—'}</div></div>
        <div class="info-row"><div class="info-icon"><i class="fas fa-phone-alt"></i></div><div><strong>Phone:</strong> ${sales[0]?.customer_phone || '—'}</div></div>
        <div class="info-row"><div class="info-icon"><i class="fas fa-credit-card"></i></div><div><strong>Payment:</strong> ${paidBy}</div></div>
        <hr class="my-3">
        <div style="max-height: 340px; overflow-y: auto;" class="mb-3">
            <table class="table table-sm table-borderless">
                <thead class="bg-light rounded"><tr><th>Product</th><th>Cat</th><th>Qty</th><th>Inch</th><th>Price</th><th>Sale Cost</th><th>Gross</th><th>Disc</th><th>Total</th><th>Type</th></tr></thead>
                <tbody>${rowsHtml}</tbody>
            </table>
        </div>
        <div class="bg-light p-3 rounded-4 mt-2">
            <div class="summary-line"><span>Subtotal</span><span>Rs ${formatMoney(subtotal)}</span></div>
            <div class="summary-line"><span>Discount (-)</span><span class="text-danger">Rs ${formatMoney(discountTotal)}</span></div>
            <div class="summary-line"><span>Total after discount</span><span>Rs ${formatMoney(totalAfterDisc)}</span></div>
            <div class="summary-line"><span>Pre Amount</span><span>Rs ${formatMoney(preAmount)}</span></div>
            <div class="summary-line"><span>Rent</span><span>Rs ${formatMoney(rentAmount)}</span></div>
            <div class="summary-grand d-flex justify-content-between"><strong>Grand Total</strong><strong class="text-success">Rs ${formatMoney(grandTotal)}</strong></div>
            ${cashAmount > 0 ? `<div class="summary-line mt-2"><span>Amount Received</span><span>Rs ${formatMoney(cashAmount)}</span></div>` : ''}
            ${changeAmount > 0 ? `<div class="summary-line"><span>Change Returned</span><span>Rs ${formatMoney(changeAmount)}</span></div>` : ''}
        </div>
        <div class="mt-4 d-flex gap-2 justify-content-end">
            <button class="btn btn-outline-secondary btn-sm rounded-pill" id="printSingleViewBtn"><i class="fas fa-print me-1"></i> Print Summary</button>
        </div>
    `;

    const container = document.getElementById('singleViewContainer');
    container.innerHTML = html;

    const printBtn = document.getElementById('printSingleViewBtn');
    if (printBtn) {
        printBtn.onclick = () => {
            const printContent = container.cloneNode(true);
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html><head><title>Invoice ${orderId}</title>
                <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
                <style>body { padding: 2rem; font-family: Inter, sans-serif; } .btn, #printSingleViewBtn { display: none; }</style>
                </head><body>${printContent.innerHTML}</body></html>
            `);
            printWindow.document.close();
            printWindow.print();
        };
    }
}

$(document).ready(function() {
    // Filter functions
    $('#saleOrderID').on('keyup', function() {
        let val = $(this).val().toLowerCase();
        $('#saleHistoryTableBody tr').each(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(val) !== -1);
        });
    });
    
    $('#refundOrderID').on('keyup', function() {
        let val = $(this).val().toLowerCase();
        $('#refundTableBody tr').each(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(val) !== -1);
        });
    });

    // Click handler for sale history rows
    $(document).on('click', '.sale-history-row', function() {
        let orderId = $(this).data('order-id');
        let products = orderGroups[orderId];
        if (products && products.length) {
            populateSingleView(orderId, products, products, 'history');
        } else {
            $('#singleViewContainer').html('<div class="text-center p-4 text-muted">No data for this order</div>');
        }
    });

    // Click handler for refund rows
    $(document).on('click', '.refund-row', function() {
        let orderId = $(this).data('order-id');
        let products = refundGroups[orderId];
        if (products && products.length) {
            populateSingleView(orderId, products, products, 'refund');
        } else {
            $('#singleViewContainer').html('<div class="text-center p-4 text-muted">Refund details not available</div>');
        }
    });
});
</script>
</body>
</html>