#!/bin/bash
# Create a temporary file with the fixed function
cat > temp_function.txt << "FUNC_END"
// ===== PRODUCT GALLERY =====

function openProductGallery(productId) {
    if (typeof ImageGallery !== 'undefined') {
        // Find product in bulkEditorData to get name and code
        const product = bulkEditorData.find(p => p.id === productId);
        if (product) {
            ImageGallery.open(productId, product.name || 'Unknown Product', product.cod_produs || '');
        } else {
            // Fallback - just use the productId
            ImageGallery.open(productId, 'Product #' + productId, '');
        }
    } else {
        alert('Image gallery module not loaded');
    }
}
FUNC_END

# Get line numbers
START_LINE=$(grep -n "^function openProductGallery" public/js/admin.js | cut -d: -f1)
END_LINE=$(awk "/^function openProductGallery/,/^}$/ {print NR; found=1} found && /^}$/ {exit}" public/js/admin.js | tail -1)

echo "Replacing lines $START_LINE to $END_LINE"

# Create new file
head -n $((START_LINE - 2)) public/js/admin.js > public/js/admin_new.js
cat temp_function.txt >> public/js/admin_new.js
tail -n +$((END_LINE + 1)) public/js/admin.js >> public/js/admin_new.js

# Replace original
mv public/js/admin_new.js public/js/admin.js
rm temp_function.txt

echo "Function replaced successfully"
