<?php
// file: purchase_detail_v.php
// Enhanced purchase order details with batch number support

include("../db/cn.php");
include("common/tx.php");
ob_start();

// Handle deletion request
if (isset($_GET['delete_order_id'])) {
    $deleteOrderId = mysqli_real_escape_string($connection, $_GET['delete_order_id']);
    $deleteQuery = "DELETE FROM purchase WHERE inv_id = '$deleteOrderId'";
    mysqli_query($connection, $deleteQuery);
    echo "<script>window.location.href = 'purchase_detail_v.php';</script>";
    exit();
}
// Handle deletion request
if (isset($_GET['delete_r_inv_id'])) {
    $deleteOrderId = $_GET['delete_r_order_id'];
    $deleteQuery = "DELETE FROM purchase WHERE r_inv_id = '$deleteOrderId'";
    mysqli_query($connection, $deleteQuery);
    // Optional: redirect after delete to avoid resubmission
   echo "<script type='text/javascript'>window.location.href = 'purchase_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 purchase history data (status = '')
    $saleHistoryResult = mysqli_query($connection, "SELECT * FROM purchase WHERE status = '' ORDER BY date_time DESC");

    // Fetch purchase 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 purchase return/refund data
    $saleRefundResult = mysqli_query($connection, "SELECT * FROM purchase WHERE status = 'return' ORDER BY date_time DESC");

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

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

    // Group purchase 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 invoice ID
function groupDataByOrderId($data) {
    $groups = array();
    foreach ($data as $item) {
        $orderId = $item['inv_id'];
        if (!isset($groups[$orderId])) {
            $groups[$orderId] = array();
        }
        $groups[$orderId][] = $item;
    }
    return $groups;
}
ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase Order Detail - <?php echo htmlspecialchars($tx ?? 'Stock Manager'); ?></title>
    <!-- Bootstrap 5 CSS -->
    <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">
    <link rel="stylesheet" href="css/custom_css.css" />
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', sans-serif;
            background: #f0f2f5;
            overflow-x: hidden;
        }
        
        /* Modern Header */
        .modern-header {
            background: linear-gradient(135deg, #1a2a3a 0%, #0e1a24 100%);
            padding: 0.75rem 1.5rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1030;
        }
        
        .logo-brand {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .logo-brand img {
            border-radius: 50%;
            background: white;
            padding: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        
        .store-title {
            font-weight: 800;
            letter-spacing: 1px;
            font-size: 1.5rem;
            background: linear-gradient(120deg, #FFE6A3, #FFD666);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }
        
        .btn-back-modern {
            background: rgba(255,255,255,0.12);
            backdrop-filter: blur(4px);
            border: 1px solid rgba(255,214,102,0.5);
            color: #FFD666;
            border-radius: 40px;
            padding: 8px 24px;
            font-weight: 600;
            transition: all 0.2s;
            text-decoration: none;
        }
        
        .btn-back-modern:hover {
            background: #FFD666;
            color: #1a2a3a;
            border-color: #FFD666;
            transform: translateY(-2px);
        }
        
        /* Card Styles */
        .card-glass {
            background: white;
            border-radius: 24px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.05);
            border: none;
            overflow: hidden;
        }
        
        .custom-tabs {
            border: none;
            background: #ffffff;
            border-radius: 20px;
            padding: 6px;
            margin-bottom: 1.2rem;
        }
        
        .custom-tabs .nav-link {
            border: none;
            border-radius: 40px;
            font-weight: 600;
            padding: 0.6rem 1.6rem;
            color: #4a627a;
            transition: all 0.2s;
            background: transparent;
        }
        
        .custom-tabs .nav-link.active {
            background: #0f2b3b;
            color: white;
            box-shadow: 0 4px 12px rgba(15,43,59,0.2);
        }
        
        .custom-tabs .nav-link:hover:not(.active) {
            background: #eef2f7;
            color: #1e4663;
        }
        
        /* Table Styles */
        .table-scroll-area {
            max-height: 550px;
            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;
        }
        
        .purchase-table {
            margin-bottom: 0;
            font-size: 0.85rem;
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .purchase-table thead th {
            background: #1e2f3c;
            color: white;
            font-weight: 600;
            font-size: 0.8rem;
            padding: 14px 8px;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .purchase-table tbody tr {
            transition: background 0.15s;
            cursor: pointer;
            border-bottom: 1px solid #edf2f7;
        }
        
        .purchase-table tbody tr:hover {
            background: #f8fafd;
        }
        
        .purchase-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 10px;
            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-edit { background: #e9f4f8; color: #0f6b8c; border: none; }
        .btn-edit:hover { background: #0f6b8c; color: white; }
        .btn-delete { background: #ffe9e9; color: #c23d3d; border: none; }
        .btn-delete:hover { background: #c23d3d; color: white; }
        .btn-add-item { background: #e6f7ec; color: #2a7f49; border: none; }
        .btn-add-item:hover { background: #2a7f49; 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;
        }
        
        .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;
        }
        
        .info-row {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 14px;
            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;
        }
        
        .batch-badge {
            background: #e9ecef;
            color: #495057;
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 10px;
            font-family: monospace;
            font-weight: 500;
        }
        
        .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;
        }
        
        @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; }
        }
    </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 htmlspecialchars($tx ?? 'Stock Manager'); ?></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;">Purchase Orders</h3>
            </div>
            <div class="col-md-3 col-6 text-end">
                <a href="addproduct.php" class="btn-back-modern"><i class="fas fa-arrow-left me-1"></i> Back</a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid py-4">
    <div class="row g-4">
        <!-- LEFT COLUMN: Purchase History Table -->
        <div class="col-lg-6">
            <div class="card-glass">
                <div class="p-3 border-0">
                    <ul class="nav nav-tabs custom-tabs" id="purchaseTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="purchaseHistory-tab" data-bs-toggle="tab" data-bs-target="#purchaseHistory" type="button" role="tab">
                                <i class="fas fa-truck me-1"></i> Purchase 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> Returns
                            </button>
                        </li>
                    </ul>
                </div>

                <div class="tab-content px-3 pb-3">
                    <!-- PURCHASE HISTORY TAB -->
                    <div class="tab-pane fade show active" id="purchaseHistory" role="tabpanel">
                        <div class="mb-3">
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0"><i class="fas fa-search text-muted"></i></span>
                                <input type="text" class="form-control border-start-0 ps-0 search-modern" id="purchaseOrderID" placeholder="Search by Invoice ID, Supplier, Amount...">
                            </div>
                        </div>
                        <div class="table-scroll-area">
                            <table class="purchase-table table align-middle">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Supplier</th>
                                        <th>Invoice ID</th>
                                        <th>Amount (Rs)</th>
                                        <th>Status</th>
                                        <th>Print</th>
                                        <!--<th>Edit</th>-->
                                        <th>Delete</th>
                                        <!--<th>Add Item</th>-->
                                    </tr>
                                </thead>
                                <tbody id="purchaseTableBody">
                                <?php foreach (array_reverse($orderGroups) as $orderId => $group): ?>
                                <?php 
                                    $subtotal = 0;
                                    foreach ($group as $orderRow) {
                                        $gross = $orderRow['product_quantity'] * $orderRow['product_price'];
                                        $discountAmount = ($gross * $orderRow['discount']) / 100;
                                        $productTotal = $gross - $discountAmount;
                                        $subtotal += $productTotal;
                                    }
                                ?>
                                    <tr class="purchase-row" data-order-id="<?php echo htmlspecialchars($orderId); ?>">
                                        <td class="fw-semibold"><?php echo htmlspecialchars($group[0]['date_time']); ?></td>
                                        <td><?php echo htmlspecialchars($group[0]['customer_name']); ?></td>
                                        <td><span class="badge-order-id"><?php echo htmlspecialchars($orderId); ?></span></td>
                                        <td class="fw-bold text-success"><?php echo number_format($subtotal, 2); ?></td>
                                        <td><span class="badge bg-info bg-opacity-10 text-info px-3 py-1 rounded-pill"><?php echo htmlspecialchars($group[0]['paid_by']); ?></span></td>
                                        <td>
                                            <a href="print_invoice_pp.php?inv_id=<?php echo urlencode($orderId); ?>" target="_blank" class="btn btn-icon-sm btn-print">
                                                <i class="fas fa-print"></i>
                                            </a>
                                        </td>
                                        <!--<td>-->
                                        <!--    <a href="edit_inv_2.php?inv_id=<?php echo urlencode($orderId); ?>" class="btn btn-icon-sm btn-edit">-->
                                        <!--        <i class="fas fa-edit"></i>-->
                                        <!--    </a>-->
                                        <!--</td>-->
                                        <td>
                                            <a href="purchase_detail_v.php?delete_order_id=<?php echo urlencode($orderId); ?>" class="btn btn-icon-sm btn-delete" onclick="return confirm('Are you sure you want to delete this purchase order?');">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </td>
                                        <!--<td>-->
                                        <!--    <a href="add_item_p.php?inv_id=<?php echo urlencode($orderId); ?>" class="btn btn-icon-sm btn-add-item">-->
                                        <!--        <i class="fas fa-plus"></i>-->
                                        <!--    </a>-->
                                        <!--</td>-->
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($orderGroups)): ?>
                                    <tr><td colspan="9" class="text-center text-muted py-4">No purchase records found</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- RETURNS TAB -->
                    <div class="tab-pane fade" id="refund" role="tabpanel">
                        <div class="mb-3">
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0"><i class="fas fa-search text-muted"></i></span>
                                <input type="text" class="form-control border-start-0 ps-0 search-modern" id="refundOrderID" placeholder="Search return records...">
                            </div>
                        </div>
                        <div class="table-scroll-area">
                            <table class="purchase-table table align-middle">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Supplier</th>
                                        <th>Invoice ID</th>
                                        <th>Amount(Rs)</th>
                                        <th>Status</th>
                                        <th>Print</th>
                                        <th>Delete</th>
                                    </tr>
                                </thead>
                                <tbody id="refundTableBody">
                                    <?php foreach (array_reverse($refundGroups) as $orderId => $group): ?>
                                        <tr class="refund-row" data-order-id="<?php echo htmlspecialchars($orderId); ?>">
                                            <td><?php echo htmlspecialchars($group[0]['date_time']); ?></td>
                                            <td><?php echo htmlspecialchars($group[0]['customer_name']); ?></td>
                                            <td><span class="badge-order-id"><?php echo htmlspecialchars($group[0]['r_order_id']); ?></span></td>
                                            <td class="fw-bold"><?php echo htmlspecialchars($group[0]['discount_amount']); ?></td>
                                            <td><span class="badge bg-warning bg-opacity-10 text-dark px-3 py-1 rounded-pill"><?php echo htmlspecialchars($group[0]['paid_by']); ?></span></td>
                                            <td><a href="print_invoice_r.php?inv_id=<?php echo urlencode($group[0]['r_inv_id']); ?>" target="_blank" class="btn btn-icon-sm btn-print"><i class="fas fa-print"></i></a></td>
                                              <td><a href="purchase_detail_v.php?delete_r_inv_id=<?php echo $group[0]['r_inv_id']; ?>" onclick="return confirm('Are you sure you want to delete this  Refund Invoice?');" class="btn btn-icon-sm btn-delete"><i class="fas fa-trash-alt"></i></a></td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($refundGroups)): ?>
                                        <tr><td colspan="7" class="text-center text-muted py-4">No return records found</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- RIGHT COLUMN: SINGLE VIEW DETAILS -->
        <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 purchase order to see full details</p>
                    <small class="text-muted">Includes batch numbers and product information</small>
                </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 ?? [], JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT); ?>;
const refundGroups = <?php echo json_encode($refundGroups ?? [], JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT); ?>;

// Helper Functions
function formatMoney(value) {
    return parseFloat(value).toFixed(2);
}

function escapeHtml(str) {
    if (!str) return '';
    return String(str).replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

function parseDate(text) {
    const d = new Date(text);
    if (!isNaN(d)) return d;
    const cleaned = text.replace(/-/g,'/').replace(/(\.\d+)?$/,'');
    const d2 = new Date(cleaned);
    return isNaN(d2) ? null : d2;
}

// Sort purchase history rows by date descending
(function sortPurchaseHistory() {
    const tbody = document.getElementById('purchaseTableBody');
    if (!tbody) return;
    const rows = Array.from(tbody.rows);
    rows.sort((a,b) => {
        const aText = a.cells && a.cells[0] ? a.cells[0].innerText.trim() : '';
        const bText = b.cells && b.cells[0] ? b.cells[0].innerText.trim() : '';
        const da = parseDate(aText), db = parseDate(bText);
        if (da && db) return db - da;
        if (da) return -1;
        if (db) return 1;
        return 0;
    });
    tbody.innerHTML = '';
    rows.forEach(r => tbody.appendChild(r));
})();

// Filter tables
function filterTable(selector, text) {
    $(selector + ' tr').each(function() {
        const content = $(this).text().toLowerCase();
        $(this).toggle(!text || content.indexOf(text.toLowerCase()) !== -1);
    });
}

$('#purchaseOrderID').on('input', function() {
    filterTable('#purchaseTableBody', $(this).val());
});
$('#refundOrderID').on('input', function() {
    filterTable('#refundTableBody', $(this).val());
});

// Render Single View with Batch Numbers
function renderSingleView(orderId, products, sales) {
    if (!products || products.length === 0) {
        $('#singleViewContainer').html('<div class="text-center text-muted py-5"><i class="fas fa-exclamation-circle fa-2x mb-2"></i><p>Order details not found.</p></div>');
        return;
    }

    let subtotal = 0;
    let rowsHtml = '';

    products.forEach(prod => {
        const qty = parseFloat(prod.product_quantity) || 0;
        const inches = parseFloat(prod.inches) || 0;
        const price = parseFloat(prod.product_price) || 0;
        const saleCost = parseFloat(prod.sale_cost) || 0;
        const discount = parseFloat(prod.discount) || 0;
        const batchNo = prod.batch_no || '-';
        
        const gross = qty * price * inches;
        const discountAmount = (gross * discount) / 100;
        const productTotal = gross - discountAmount;
        subtotal += productTotal;
        
        const perUnitSaleCost = (qty > 0 && saleCost > 0) ? (saleCost / qty) : 0;
        const updatedSaleCost = perUnitSaleCost * qty;

        rowsHtml += `<tr style="border-bottom: 1px solid #eee;">
            <td style="padding: 10px 5px; font-weight: 600;">${escapeHtml(prod.product_name)}</td>
            <td style="padding: 10px 5px;"><span class="batch-badge">${escapeHtml(batchNo)}</span></td>
            <td style="padding: 10px 5px;">${qty}</td>
            <td style="padding: 10px 5px;">${formatMoney(price)}</td>
            <td style="padding: 10px 5px;">${formatMoney(updatedSaleCost)}</td>
            <td style="padding: 10px 5px;">${formatMoney(gross)}</td>
            <td style="padding: 10px 5px;">${discount}%</td>
            <td style="padding: 10px 5px; font-weight: 700; color: #0A4657;">${formatMoney(productTotal)}</td>
        </tr>`;
    });

    const sale = sales[0];
    const discountTotal = parseFloat(sale.discounted) || 0;
    const totalAfterDisc = subtotal - discountTotal;

    const html = `
        <div>
            <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> ${escapeHtml(orderId)}</div>
                <small class="text-muted"><i class="far fa-calendar-alt me-1"></i> ${escapeHtml(sale.date_time || '')}</small>
            </div>
            <div class="info-row"><div class="info-icon"><i class="fas fa-building"></i></div><div><strong>Supplier:</strong> ${escapeHtml(sale.customer_name || '-')}</div></div>
            <div class="info-row"><div class="info-icon"><i class="fas fa-phone-alt"></i></div><div><strong>Phone:</strong> ${escapeHtml(sale.customer_phone || '-')}</div></div>
            <div class="info-row"><div class="info-icon"><i class="fas fa-money-bill"></i></div><div><strong>Payment:</strong> ${escapeHtml(sale.paid_by || '-')}</div></div>
            <hr class="my-3">
            <div style="max-height: 350px; overflow-y: auto;">
                <table class="table table-sm">
                    <thead style="background: #f0f4f8; position: sticky; top: 0;">
                        <tr style="font-size: 12px;">
                            <th>Product</th><th>Batch No</th><th>Qty</th><th>Unit Price</th><th>Sale Cost</th><th>Gross</th><th>Disc%</th><th>Total</th>
                        </tr>
                    </thead>
                    <tbody>${rowsHtml}</tbody>
                </table>
            </div>
            <div class="summary-card mt-3">
                <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 class="fw-bold">Rs ${formatMoney(totalAfterDisc)}</span></div>
                <div class="summary-grand d-flex justify-content-between">
                    <strong>Grand Total</strong>
                    <strong class="text-success">Rs ${formatMoney(totalAfterDisc)}</strong>
                </div>
            </div>
            <div class="mt-4 d-flex justify-content-end">
                <button class="btn btn-outline-secondary btn-sm rounded-pill" id="printSingleViewBtn">
                    <i class="fas fa-print me-1"></i> Print Order
                </button>
            </div>
        </div>
    `;

    $('#singleViewContainer').html(html);
    
    $('#printSingleViewBtn').off('click').on('click', function(e) {
        e.preventDefault();
        const content = $('#singleViewContainer').clone();
        content.find('#printSingleViewBtn').remove();
        const w = window.open('', '_blank', 'width=900,height=900');
        if (!w) { alert('Pop-up blocked. Please allow pop-ups for this site.'); return; }
        const style = `<style>body{font-family:Arial,sans-serif;padding:20px}table{width:100%;border-collapse:collapse}th,td{border:1px solid #ddd;padding:8px;text-align:center}th{background:#f2f2f2}.summary-card{margin-top:15px}.summary-line{display:flex;justify-content:space-between;padding:8px 0}</style>`;
        w.document.write(`<html><head><title>Purchase Order - ${escapeHtml(orderId)}</title>${style}</head><body>${content.html()}</body></html>`);
        w.document.close();
        w.focus();
        setTimeout(() => w.print(), 300);
    });
}

// Click handlers
$(document).on('click', '.purchase-row', function(e) {
    if ($(e.target).closest('a, button').length) return;
    const orderId = $(this).data('order-id');
    const products = orderGroups[orderId];
    if (products) renderSingleView(orderId, products, products);
});

$(document).on('click', '.refund-row', function(e) {
    if ($(e.target).closest('a, button').length) return;
    const orderId = $(this).data('order-id');
    const products = refundGroups[orderId];
    if (products) renderSingleView(orderId, products, products);
});

// Auto-select first row on load
const firstRow = $('.purchase-row').first();
if (firstRow.length && firstRow.data('order-id')) {
    renderSingleView(firstRow.data('order-id'), orderGroups[firstRow.data('order-id')], orderGroups[firstRow.data('order-id')]);
}
</script>
</body>
</html>