<?php
include("../db/cn.php");
include("common/tx.php");
session_start();

$order_id = isset($_GET['order_id']) ? mysqli_real_escape_string($connection, $_GET['order_id']) : '';

if (empty($order_id)) {
    header("Location: order_detail_v.php");
    exit();
}

// Fetch order details
$query = "SELECT * FROM log_user_sales WHERE order_id = '$order_id' AND (status != 'refund' OR status IS NULL)";
$result = mysqli_query($connection, $query);
$products = [];
$order_info = null;

while ($row = mysqli_fetch_assoc($result)) {
    $products[] = $row;
    if ($order_info == null) {
        $order_info = $row;
    }
}

if (empty($products)) {
    echo "Order not found!";
    exit();
}

// Handle refund submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['refund_submit'])) {
    $order_id = mysqli_real_escape_string($connection, $_POST['order_id']);
    $paid_by = mysqli_real_escape_string($connection, $_POST['paid_by']);
    $customer_name = mysqli_real_escape_string($connection, $_POST['customer_name']);
    $refund_reason = mysqli_real_escape_string($connection, $_POST['refund_reason']);
    $refund_items = $_POST['refund_qty'];
    
    mysqli_begin_transaction($connection);
    
    try {
        $total_refund_amount = 0;
        $order_has_remaining = false;
        
        foreach ($refund_items as $index => $refund_qty) {
            $refund_qty = intval($refund_qty);
            if ($refund_qty > 0) {
                $product_id = mysqli_real_escape_string($connection, $_POST['product_id'][$index]);
                $product_name = mysqli_real_escape_string($connection, $_POST['product_name'][$index]);
                $original_qty = intval($_POST['original_qty'][$index]);
                $product_price = floatval($_POST['product_price'][$index]);
                $trade_price = floatval($_POST['trade_price'][$index]);
                $category = mysqli_real_escape_string($connection, $_POST['category'][$index]);
                $company = mysqli_real_escape_string($connection, $_POST['company'][$index]);
                $supplier_name = mysqli_real_escape_string($connection, $_POST['supplier_name'][$index]);
                $sale_cost = floatval($_POST['sale_cost'][$index]);
                $net_amount = floatval($_POST['net_amount'][$index]);
                $disc_amount = floatval($_POST['disc_amount'][$index]);
                
                // Calculate refund amount
                $refund_amount = $refund_qty * $product_price;
                $total_refund_amount += $refund_amount;
                
                // 1. Update stock in products table
                $update_product = "UPDATE products SET quantity = quantity + $refund_qty 
                                   WHERE product_id = '$product_id'";
                if (!mysqli_query($connection, $update_product)) {
                    throw new Exception("Failed to update products table: " . mysqli_error($connection));
                }
                
                // 2. Update stock in opening_products table
                $update_opening = "UPDATE opening_products SET quantity = quantity + $refund_qty 
                                   WHERE product_id = '$product_id'";
                if (!mysqli_query($connection, $update_opening)) {
                    throw new Exception("Failed to update opening_products table: " . mysqli_error($connection));
                }
                
                // 3. Update or delete from log_user_sales
                $new_qty = $original_qty - $refund_qty;
                if ($new_qty <= 0) {
                    // Delete this product row if quantity becomes 0
                    $delete_row = "DELETE FROM log_user_sales WHERE order_id = '$order_id' AND product_id = '$product_id'";
                    if (!mysqli_query($connection, $delete_row)) {
                        throw new Exception("Failed to delete product row: " . mysqli_error($connection));
                    }
                } else {
                    $order_has_remaining = true;
                    // Calculate new product total and net amount
                    $new_product_total = $new_qty * $product_price;
                    $new_net_amount = $new_product_total - $disc_amount;
                    
                    $update_sale = "UPDATE log_user_sales SET 
                                   product_quantity = $new_qty, 
                                   product_total = $new_product_total,
                                   net_amount = $new_net_amount
                                   WHERE order_id = '$order_id' AND product_id = '$product_id'";
                    if (!mysqli_query($connection, $update_sale)) {
                        throw new Exception("Failed to update sale record: " . mysqli_error($connection));
                    }
                }
                
                // 4. Create refund record
                $refund_order_id = "REF-" . time() . "-" . rand(100, 999);
                $date_time = date('Y-m-d H:i:s');
                
                // Calculate per-unit net amount for refund
                $per_unit_net = $net_amount / $original_qty;
                $refund_net_amount = $refund_qty * $per_unit_net;
                
                $insert_refund = "INSERT INTO log_user_sales (
                    product_id, supplier_name, company, category, product_name, 
                    product_price, trade_price, product_quantity, product_total, 
                    bonus, discount, disc_amount, tax, net_amount, tax_amount, 
                    total_amount, BillAmount, paid_by, pre_amount, grand_amount, 
                    sale_cost, customer_id, customer_type, customer_name, customer_phone,
                    discount_amount, discounted, discount_per, cash_amount, change_amount, 
                    order_id, r_order_id, status, outlet_name, login_user, user_role, 
                    outlet_address, date_time, desc_note
                ) VALUES (
                    '$product_id', '$supplier_name', '$company', '$category', '$product_name (REFUND)',
                    '$product_price', '$trade_price', '$refund_qty', '$refund_amount',
                    '0', '0', '0', '0', '$refund_net_amount', '0',
                    '$refund_amount', '$refund_amount', '$paid_by', '0', '$refund_amount',
                    '$sale_cost', '', 'refund', '$customer_name', '',
                    '$refund_amount', '0', '0', '0', '$refund_amount',
                    '$refund_order_id', '$order_id', 'refund', '{$_SESSION['outlet_name']}', 
                    '{$_SESSION['user_name']}', '{$_SESSION['user_role']}', '{$_SESSION['outlet_address']}', 
                    '$date_time', 'Refund for $refund_qty units - $refund_reason'
                )";
                
                if (!mysqli_query($connection, $insert_refund)) {
                    throw new Exception("Failed to insert refund record: " . mysqli_error($connection));
                }
            }
        }
        
        // 5. Update the main order's total amount if there are remaining items
        if ($order_has_remaining) {
            // Recalculate order totals
            $recalc_query = "SELECT SUM(product_total) as total_products, SUM(net_amount) as total_net 
                            FROM log_user_sales WHERE order_id = '$order_id'";
            $recalc_result = mysqli_query($connection, $recalc_query);
            $recalc_row = mysqli_fetch_assoc($recalc_result);
            
            $new_total_amount = $recalc_row['total_products'];
            $new_net_amount = $recalc_row['total_net'];
            $new_grand_amount = $new_net_amount + floatval($_POST['pre_amount']);
            
            // Update all rows with new totals
            $update_order_total = "UPDATE log_user_sales SET 
                                  total_amount = '$new_total_amount',
                                  net_amount = '$new_net_amount',
                                  discount_amount = '$new_net_amount',
                                  grand_amount = '$new_grand_amount'
                                  WHERE order_id = '$order_id'";
            mysqli_query($connection, $update_order_total);
        } else {
            // If no items remain, mark the order as fully refunded
            $update_order = "UPDATE log_user_sales SET status = 'fully_refunded' WHERE order_id = '$order_id'";
            mysqli_query($connection, $update_order);
        }
        
        // 6. Update customer ledger for credit sales
        if ($paid_by != 'cash') {
            // Get current balance
            $balance_query = "SELECT remain_balance FROM creditor_closing WHERE creditor_name = '$customer_name' ORDER BY id DESC LIMIT 1";
            $balance_result = mysqli_query($connection, $balance_query);
            $current_balance = 0;
            if ($balance_result && mysqli_num_rows($balance_result) > 0) {
                $balance_row = mysqli_fetch_assoc($balance_result);
                $current_balance = floatval($balance_row['remain_balance']);
            }
            
            // Update balance (reduce by refund amount)
            $new_balance = $current_balance - $total_refund_amount;
            $update_creditor = "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 (
                '$customer_name', '0', '0', '$total_refund_amount', 
                '$new_balance', NOW(), '{$_SESSION['user_name']}', '{$_SESSION['user_role']}', 
                '{$_SESSION['outlet_name']}', '{$_SESSION['outlet_address']}'
            )";
            
            if (!mysqli_query($connection, $update_creditor)) {
                throw new Exception("Failed to update creditor ledger: " . mysqli_error($connection));
            }
            
            // Add to credit_paid record
            $credit_refund = "INSERT INTO credit_paid (
                cr_name, amount, paid_by, description, date_time, user_name, 
                user_role, outlet_name, outlet_address
            ) VALUES (
                '$customer_name', '-$total_refund_amount', 'refund', 
                'Refund for order $order_id - $refund_reason', 
                '$date_time', '{$_SESSION['user_name']}', '{$_SESSION['user_role']}', 
                '{$_SESSION['outlet_name']}', '{$_SESSION['outlet_address']}'
            )";
            
            if (!mysqli_query($connection, $credit_refund)) {
                throw new Exception("Failed to add credit paid record: " . mysqli_error($connection));
            }
        } else {
            // For cash sales, add to cash refund record
            $date_time = date('Y-m-d H:i:s');
            $refund_record = "INSERT INTO incash (
                name_detail, amount, cr_id, paid_by, login_user, user_role, 
                outlet_name, outlet_address, date_time, desc_name
            ) VALUES (
                'REFUND - $customer_name', '-$total_refund_amount', '', 'cash', 
                '{$_SESSION['user_name']}', '{$_SESSION['user_role']}', 
                '{$_SESSION['outlet_name']}', '{$_SESSION['outlet_address']}', 
                '$date_time', 'Refund for order $order_id - $refund_reason'
            )";
            
            if (!mysqli_query($connection, $refund_record)) {
                throw new Exception("Failed to add cash refund record: " . mysqli_error($connection));
            }
        }
        
        mysqli_commit($connection);
        
        echo "<script>
                alert('Refund processed successfully!\\nTotal refund amount: Rs " . number_format($total_refund_amount, 2) . "');
                window.location.href = 'order_detail_v.php';
              </script>";
        exit();
        
    } catch (Exception $e) {
        mysqli_rollback($connection);
        echo "<script>alert('Error processing refund: " . addslashes($e->getMessage()) . "');</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Refund Order - <?php echo $tx; ?></title>
    <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/5.15.4/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Quicksand', sans-serif; background: #f5f5f5; }
        .refund-header { background: linear-gradient(270deg, #060606, #0A4657); color: #fff; padding: 15px; margin-bottom: 20px; }
        .refund-table th { background: #212529; color: #fff; text-align: center; vertical-align: middle; }
        .refund-table td { text-align: center; vertical-align: middle; }
        .refund-qty-input { width: 100px; text-align: center; font-weight: bold; }
        .refund-amount { font-weight: bold; color: #dc3545; font-size: 16px; }
        .btn-refund-submit { background: #dc3545; color: #fff; font-weight: bold; padding: 10px 30px; border-radius: 5px; }
        .btn-refund-submit:hover { background: #c82333; color: #fff; }
        .summary-box { background: #fff; border-radius: 10px; padding: 20px; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-top: 20px; }
        .bg-gradient { background: linear-gradient(270deg, #060606, #0A4657); }
        .current-qty { font-weight: bold; font-size: 18px; color: #28a745; }
        .product-card { background: #fff; border-radius: 10px; margin-bottom: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .quantity-control { display: flex; align-items: center; justify-content: center; gap: 10px; }
        .quantity-control button { width: 30px; height: 30px; border-radius: 50%; border: none; background: #007bff; color: white; font-weight: bold; }
        .quantity-control button:hover { background: #0056b3; }
        .refund-qty-input { width: 80px; text-align: center; }
    </style>
</head>
<body>

<div class="container-fluid">
    <div class="row bg-gradient">
        <div class="col-sm-3">
            <img src="../img/logo231.png" style="margin-top:5px;" width="70" height="70" alt="Logo">
        </div>
        <div class="col-sm-6">
            <h3 class="mb-4 text-center" style="color:#fff; font-weight:700; text-transform:uppercase; line-height:60px; font-size:33px;">
                <?php echo $tx; ?> - Refund Order
            </h3>
        </div>
        <div class="col-sm-3">
            <a href="order_detail_v.php">
                <button type="button" style="margin-top:20px;float:right;" class="btn btn-light">Back to Orders</button>
            </a>
        </div>
    </div>
</div>

<div class="container mt-4">
    <div class="card mb-4">
        <div class="card-header bg-info text-white">
            <h5 class="mb-0"><i class="fas fa-shopping-cart"></i> Order Information</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3"><strong>Order ID:</strong> <span class="badge bg-dark"><?php echo $order_id; ?></span></div>
                <div class="col-md-3"><strong>Customer:</strong> <?php echo htmlspecialchars($order_info['customer_name']); ?></div>
                <div class="col-md-3"><strong>Phone:</strong> <?php echo htmlspecialchars($order_info['customer_phone'] ?: 'N/A'); ?></div>
                <div class="col-md-3"><strong>Payment Type:</strong> 
                    <span class="badge <?php echo ($order_info['paid_by'] == 'cash') ? 'bg-success' : 'bg-warning'; ?>">
                        <?php echo strtoupper(htmlspecialchars($order_info['paid_by'])); ?>
                    </span>
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-md-3"><strong>Order Date:</strong> <?php echo $order_info['date_time']; ?></div>
                <div class="col-md-3"><strong>Total Amount:</strong> Rs <?php echo number_format($order_info['total_amount'], 2); ?></div>
                <div class="col-md-3"><strong>Previous Balance:</strong> Rs <?php echo number_format($order_info['pre_amount'], 2); ?></div>
                <div class="col-md-3"><strong>Grand Total:</strong> Rs <?php echo number_format($order_info['grand_amount'], 2); ?></div>
            </div>
        </div>
    </div>
    
    <form method="POST" action="" id="refundForm" onsubmit="return validateRefund()">
        <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
        <input type="hidden" name="paid_by" value="<?php echo $order_info['paid_by']; ?>">
        <input type="hidden" name="customer_name" value="<?php echo htmlspecialchars($order_info['customer_name']); ?>">
        <input type="hidden" name="pre_amount" value="<?php echo $order_info['pre_amount']; ?>">
        
        <div class="card">
            <div class="card-header bg-danger text-white">
                <h5 class="mb-0"><i class="fas fa-undo-alt"></i> Select Items to Refund</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-warning">
                    <i class="fas fa-info-circle"></i> <strong>Instructions:</strong> Enter the quantity you want to refund for each product. The system will automatically update stock, invoice, and customer ledger.
                </div>
                
                <div class="table-responsive">
                    <table class="table table-bordered refund-table" id="refundTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Product Name</th>
                                <th>Category</th>
                                <th>Company</th>
                                <th>Original Qty</th>
                                <th>Unit Price (Rs)</th>
                                <th>Total (Rs)</th>
                                <th>Refund Quantity</th>
                                <th>Refund Amount (Rs)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $counter = 1;
                            foreach ($products as $index => $product): 
                                $qty = intval($product['product_quantity']);
                                $price = floatval($product['product_price']);
                                $total = $qty * $price;
                            ?>
                             <tr>
                                <td><?php echo $counter++; ?>
                                    <input type="hidden" name="product_id[]" value="<?php echo htmlspecialchars($product['product_id']); ?>">
                                    <input type="hidden" name="product_name[]" value="<?php echo htmlspecialchars($product['product_name']); ?>">
                                    <input type="hidden" name="category[]" value="<?php echo htmlspecialchars($product['category']); ?>">
                                    <input type="hidden" name="company[]" value="<?php echo htmlspecialchars($product['company']); ?>">
                                    <input type="hidden" name="original_qty[]" value="<?php echo $qty; ?>">
                                    <input type="hidden" name="supplier_name[]" value="<?php echo htmlspecialchars($product['supplier_name']); ?>">
                                    <input type="hidden" name="trade_price[]" value="<?php echo $product['trade_price']; ?>">
                                    <input type="hidden" name="product_price[]" value="<?php echo $price; ?>">
                                    <input type="hidden" name="sale_cost[]" value="<?php echo $product['sale_cost']; ?>">
                                    <input type="hidden" name="net_amount[]" value="<?php echo $product['net_amount']; ?>">
                                    <input type="hidden" name="disc_amount[]" value="<?php echo $product['disc_amount']; ?>">
                                    </td>
                                <td><?php echo htmlspecialchars($product['product_name']); ?></td>
                                <td><?php echo htmlspecialchars($product['category']); ?></td>
                                <td><?php echo htmlspecialchars($product['company']); ?></td>
                                <td><span class="current-qty" id="current-qty-<?php echo $index; ?>"><?php echo $qty; ?></span></td>
                                <td>Rs <?php echo number_format($price, 2); ?></td>
                                <td>Rs <?php echo number_format($total, 2); ?></td>
                                <td>
                                    <div class="quantity-control">
                                        <button type="button" onclick="changeQuantity(<?php echo $index; ?>, -1, <?php echo $qty; ?>)">-</button>
                                        <input type="number" name="refund_qty[]" id="refund-qty-<?php echo $index; ?>" 
                                               class="form-control refund-qty-input refund-qty text-center" 
                                               min="0" max="<?php echo $qty; ?>" value="0" step="1" 
                                               data-price="<?php echo $price; ?>" data-index="<?php echo $index; ?>"
                                               data-max="<?php echo $qty; ?>" onchange="updateRefundAmount(<?php echo $index; ?>)">
                                        <button type="button" onclick="changeQuantity(<?php echo $index; ?>, 1, <?php echo $qty; ?>)">+</button>
                                    </div>
                                </td>
                                <td class="refund-amount" id="refund-amount-<?php echo $index; ?>">Rs 0.00</td>
                             </tr>
                            <?php endforeach; ?>
                        </tbody>
                     </table>
                </div>
                
                <div class="row mt-4">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label><strong><i class="fas fa-comment"></i> Refund Reason:</strong></label>
                            <textarea name="refund_reason" id="refund_reason" class="form-control" rows="3" 
                                      placeholder="Enter reason for refund (e.g., Damaged product, Wrong item, Customer request)..." required></textarea>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="summary-box">
                            <h5><i class="fas fa-receipt"></i> Refund Summary</h5>
                            <hr>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td><strong>Total Refund Amount:</strong></td>
                                    <td class="text-end"><span id="summary-refund-amount" class="text-danger fs-4 fw-bold">Rs 0.00</span></td>
                                </tr>
                                <tr>
                                    <td><strong>Payment Type:</strong></td>
                                    <td class="text-end">
                                        <?php if($order_info['paid_by'] == 'cash'): ?>
                                            <span class="badge bg-success"><i class="fas fa-money-bill"></i> Cash Refund</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning"><i class="fas fa-book"></i> Credit Adjustment</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>Current Balance:</strong></td>
                                    <td class="text-end">
                                        <?php 
                                        $bal_query = "SELECT remain_balance FROM creditor_closing WHERE creditor_name = '{$order_info['customer_name']}' ORDER BY id DESC LIMIT 1";
                                        $bal_result = mysqli_query($connection, $bal_query);
                                        $current_creditor_balance = 0;
                                        if ($bal_result && mysqli_num_rows($bal_result) > 0) {
                                            $bal_row = mysqli_fetch_assoc($bal_result);
                                            $current_creditor_balance = floatval($bal_row['remain_balance']);
                                        }
                                        ?>
                                        Rs <?php echo number_format($current_creditor_balance, 2); ?>
                                    </td>
                                </tr>
                            </table>
                            <?php if($order_info['paid_by'] != 'cash'): ?>
                                <div class="alert alert-info mt-2 mb-0">
                                    <i class="fas fa-info-circle"></i> After refund: <strong>Rs <?php echo number_format($current_creditor_balance, 2); ?></strong> → <strong class="text-danger" id="new-balance">Rs <?php echo number_format($current_creditor_balance, 2); ?></strong>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-4">
                    <button type="submit" name="refund_submit" class="btn btn-refund-submit btn-lg" 
                            onclick="return confirmRefund()">
                        <i class="fas fa-undo-alt"></i> Process Refund
                    </button>
                    <a href="order_detail_v.php" class="btn btn-secondary btn-lg ms-3">Cancel</a>
                </div>
            </div>
        </div>
    </form>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
let currentCreditorBalance = <?php echo $current_creditor_balance; ?>;
let paymentType = '<?php echo $order_info['paid_by']; ?>';

function updateRefundAmount(index) {
    var qty = parseInt($('#refund-qty-' + index).val()) || 0;
    var price = parseFloat($('#refund-qty-' + index).data('price'));
    var maxQty = parseInt($('#refund-qty-' + index).data('max'));
    
    if (qty > maxQty) {
        $('#refund-qty-' + index).val(maxQty);
        qty = maxQty;
    }
    if (qty < 0) {
        $('#refund-qty-' + index).val(0);
        qty = 0;
    }
    
    var refundAmount = qty * price;
    $('#refund-amount-' + index).text('Rs ' + refundAmount.toFixed(2));
    
    // Calculate total refund
    var totalRefund = 0;
    $('.refund-qty').each(function() {
        var qtyVal = parseInt($(this).val()) || 0;
        var priceVal = parseFloat($(this).data('price'));
        totalRefund += qtyVal * priceVal;
    });
    
    $('#summary-refund-amount').text('Rs ' + totalRefund.toFixed(2));
    
    // Update new balance for credit customers
    if (paymentType !== 'cash') {
        var newBalance = currentCreditorBalance - totalRefund;
        $('#new-balance').text('Rs ' + newBalance.toFixed(2));
        if (newBalance < 0) {
            $('#new-balance').addClass('text-danger');
        } else {
            $('#new-balance').removeClass('text-danger');
        }
    }
}

function changeQuantity(index, change, maxQty) {
    var currentQty = parseInt($('#refund-qty-' + index).val()) || 0;
    var newQty = currentQty + change;
    if (newQty >= 0 && newQty <= maxQty) {
        $('#refund-qty-' + index).val(newQty);
        updateRefundAmount(index);
    }
}

function validateRefund() {
    var hasRefund = false;
    $('.refund-qty').each(function() {
        if (parseInt($(this).val()) > 0) {
            hasRefund = true;
        }
    });
    
    if (!hasRefund) {
        alert('Please select at least one item to refund!');
        return false;
    }
    
    var reason = $('#refund_reason').val().trim();
    if (reason === '') {
        alert('Please enter a reason for the refund!');
        $('#refund_reason').focus();
        return false;
    }
    
    return true;
}

function confirmRefund() {
    if (!validateRefund()) {
        return false;
    }
    
    var totalRefund = $('#summary-refund-amount').text();
    return confirm('Are you sure you want to process this refund?\n\nTotal Refund Amount: ' + totalRefund + '\n\n⚠️ This action cannot be undone!\n\n✅ Stock will be updated\n✅ Invoice will be updated\n✅ Customer ledger will be updated');
}

// Initialize on page load
$(document).ready(function() {
    // Set initial values
    $('.refund-qty').each(function(index) {
        updateRefundAmount($(this).data('index'));
    });
    
    // Auto-calculate on input change
    $('.refund-qty').on('keyup change', function() {
        updateRefundAmount($(this).data('index'));
    });
});
</script>
</body>
</html>