<?php
// Function to sanitize data for basic security
function sanitizeData($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

$dataFolder = 'data/'; // Define the data folder

// Ensure the data folder exists
if (!is_dir($dataFolder)) {
    mkdir($dataFolder, 0755, true);
}

// Handle saving JSON data
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_data'])) {
    $jsonData = json_decode($_POST['save_data'], true);

    // Determine the filename based on the 'bot' parameter
    $botName = isset($_GET['bot']) ? sanitizeData($_GET['bot']) : 'products';
    $filename = $dataFolder . $botName . '.json';

    // Save the data
    if (file_put_contents($filename, json_encode($jsonData, JSON_PRETTY_PRINT))) {
        echo "Data saved successfully!";
    } else {
        http_response_code(500);
        echo "Failed to save data.";
    }
    exit;
}

// Handle loading JSON data
$productsToLoad = [];
if (isset($_GET['bot'])) {
    $botName = sanitizeData($_GET['bot']);
    $filename = $dataFolder . $botName . '.json';

    if (file_exists($filename)) {
        $jsonData = file_get_contents($filename);
        $productsToLoad = json_decode($jsonData, true);
        if (!is_array($productsToLoad)) {
            $productsToLoad = []; // Reset to an empty array if the JSON data is invalid
        }
    }
} 
// No need for this else block as it will load in javascript part of code below
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product JSON Generator</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
    
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f5f7fa;
    padding-bottom: 5rem;/* Adjust based on your header height */
}

/* Header styles */
h1 {
    font-size: 2.5rem;
    color: #1a365d;
    margin-bottom: 1rem;
    font-weight: 700;
}

h2 {
    font-size: 1.8rem;
    color: #2d4a7e;
    margin: 2rem 0 1rem;
    font-weight: 600;
}

h3 {
    font-size: 1.4rem;
    color: #2d4a7e;
    margin-bottom: 1rem;
    font-weight: 500;
}

p {
    color: #4a5568;
    margin-bottom: 2rem;
}

/* Container styles */
.container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 2rem;
    margin-bottom: 2rem;
    border: 1px solid rgba(226, 232, 240, 0.8);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.container:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 8px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Form elements */
label {
    display: block;
    font-weight: 600;
    color: #2d4a7e;
    margin-bottom: 0.5rem;
    font-size: 0.95rem;
}

input[type="text"],
input[type="number"],
textarea,
select {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 1rem;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
    margin-bottom: 1rem;
    background-color: #fff;
}

input:focus,
select:focus,
textarea:focus {
    outline: none;
    border-color: #4299e1;
    box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.15);
}

/* Button styles */
button {
    padding: 1.75rem 2.5rem;
    border-radius: 8px;
    font-weight: 600;
    font-size: 0.95rem;
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    width: 150px;
    height: 50px;
   
}

button:hover {
    transform: translateY(-1px);
}

button:active {
    transform: translateY(0);
}

#add-product-button {
    background-color: #3182ce;
    color: white;
    margin: 1rem 0 2rem;
}

#add-product-button:hover {
    background-color: #2c5282;
}

.add-option {
    background-color: #48bb78;
    color: white;
    margin-right: 1rem;
}

.add-option:hover {
    background-color: #38a169;
}

.remove-step {
    background-color: #f56565;
    color: white;
}

.remove-step:hover {
    background-color: #c53030;
}

#save-button {
    background-color: #4299e1;
    color: white;
    margin-right: 1rem;
}

#save-button:hover {
    background-color: #3182ce;
}

#import-button {
    background-color: #9f7aea;
    color: white;
    margin-right: 1rem;
}

#import-button:hover {
    background-color: #805ad5;
}

#copyJsonButton {
    background-color: #667eea;
    color: white;
}

#copyJsonButton:hover {
    background-color: #5a67d8;
}

/* Options container */
.options-container {
    background-color: #f7fafc;
    border-radius: 8px;
    padding: 1.5rem;
    margin: 1rem 0;
    border: 1px solid #e2e8f0;
}

.option-row {
    display: grid;
    grid-template-columns: 2fr 1fr 1.5fr 0.5fr;
    gap: 1rem;
    align-items: center;
    margin-bottom: 1rem;
    background: white;
    padding: 1rem;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.option-row:last-child {
    margin-bottom: 0;
}

.remove-option {
    background-color: #fc8181;
    color: white;
    padding: 0.5rem 1rem;
}

.remove-option:hover {
    background-color: #f56565;
}

/* JSON output */
.json-output {
    background-color: #2d3748;
    color: #e2e8f0;
    padding: 2rem;
    border-radius: 12px;
    font-family: 'Monaco', 'Consolas', monospace;
    white-space: pre-wrap;
    font-size: 0.95rem;
    line-height: 1.5;
    overflow-x: auto;
    margin-top: 1rem;
    border: 1px solid #4a5568;
}

/* Quill editor customization */
.ql-container {
    border-radius: 0 0 8px 8px;
    min-height: 120px;
    background: white;
    margin-bottom: 1.5rem;
}

.ql-toolbar {
    border-radius: 8px 8px 0 0;
    border-color: #e2e8f0 !important;
    background: #f7fafc;
}

.ql-editor {
    font-size: 1rem;
    color: #2d3748;
}

/* Loading state for buttons */
button:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

/* Animations */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.container {
    animation: fadeIn 0.3s ease-out;
}

/* Custom scrollbar */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f7fafc;
}

::-webkit-scrollbar-thumb {
    background: #cbd5e0;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #a0aec0;
}

/* Fixed Header Styles */
.header-container {
    position: fixed;
    bottom: 0;
    left: 0; /* Adjust when sidebar is present */
    width: 100%;
    background-color: #f5f7fa;
    z-index: 10;
    
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    padding-left: 18rem;
}

/* Sidebar Styles */
.sidebar {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 250px;
    background-color: #e2e8f0;
    padding: 4rem 1rem 2rem; /* Adjust top padding to be below header */
    overflow-y: auto;
    z-index: 5; /* Below the header */
    transition: left 0.3s ease; /* Smooth transition for mobile */
    z-index: 20;
}

.sidebar-title {
    font-weight: 600;
    margin-bottom: 1rem;
    color: #2d4a7e;
}

.sidebar-step {
    padding: 0.5rem 1rem;
    margin-bottom: 0.5rem;
    background-color: #f7fafc;
    border-radius: 8px;
    border: 1px solid #cbd5e0;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.sidebar-step:hover {
    background-color: #edf2f7;
}

/* Main Content Adjustments */
.main-content {
    margin-left: 250px; /* Same as sidebar width */
    padding: 4rem 2rem 2rem; /* Adjust top padding to be below header */
    transition: margin-left 0.3s ease; /* Smooth transition for mobile */
}

/* Hamburger Menu Button */
.hamburger-menu {
    display: none;
    position: fixed;
    top: 1rem;
    left: 1rem;
    z-index: 20; /* Above the header */
    background-color: #4299e1;
    color: white;
    border: none;
    padding: 0.5rem 0.75rem;
    border-radius: 5px;
    cursor: pointer;
}

.hamburger-menu:hover {
    background-color: #3182ce;
}

/* Media Query for Mobile Devices */
@media (max-width: 768px) {
    /* General Mobile Styles */
    body {
        padding: 4rem 1rem 1rem 1rem;
        padding-bottom: 5rem; /* Adjust body padding for smaller screens */
    }

    .option-row {
        grid-template-columns: 1fr;
        gap: 0.5rem;
    }

    .container {
        padding: 1.5rem;
    }

    h1 {
        font-size: 2rem;
    }

    button {
        width: 100%;
        margin-bottom: 0.5rem;
    }
    
    /* Header on Mobile */
    .header-container {
        left: 0; /* Reset left position */
        width: 100%; /* Take up full width */
    }

    /* Sidebar on Mobile */
    .sidebar {
        left: -250px; /* Off-screen by default */
        z-index: 20;
    }

    .sidebar.show {
        left: 0; /* Slide in when toggled */
    }

    /* Main Content on Mobile */
    .main-content {
        margin-left: 0; /* No margin when sidebar is hidden */
        padding: 4rem 1rem 2rem; /* Adjust padding */
    }

    /* Hamburger Menu */
    .hamburger-menu {
        display: block;
        width: 50px;
        z-index: 21;
    }
    .header-container {
        padding-left: 5rem;
    }
    #save-button , #add-product-button
    {
        width: 130px;
        padding: 1rem 0.8rem;
    }
}
        /* Modal Styles */
.modal {
    display: none;
    position: fixed;
    z-index: 100; /* Ensure modal is above other fixed elements */
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
    position: relative; /* For positioning the close button */
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 600px;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.close-modal {
    color: #aaa;
    position: absolute;
    top: 10px;
    right: 15px;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.close-modal:hover,
.close-modal:focus {
    color: black;
}
.image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    grid-gap: 10px;
}

.image-grid img {
    width: 100%;
    height: auto;
    cursor: pointer;
    border: 2px solid transparent;
    border-radius: 4px; /* Added for a slight rounded corner */
}

.image-grid img.selected {
    border-color: blue;
    box-shadow: 0 0 5px rgba(0, 0, 255, 0.7); /* Added for a 'selected' visual effect */
}

.attached-images {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
}

.attached-image {
    position: relative;
    margin-right: 5px;
    margin-bottom: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden; /* Ensures the image respects the border radius */
}

.attached-image img {
    width: 50px;
    height: 50px;
    object-fit: cover;
}

.remove-image {
    position: absolute;
    top: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    padding: 2px 5px;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.2s ease-in-out;
    border-bottom-left-radius: 4px; /* Rounds the bottom-left corner */
}

.attached-image:hover .remove-image {
    opacity: 1;
}

    </style>
</head>
<body>
    <button class="hamburger-menu">☰</button>

    <div class="sidebar">
        <h3 class="sidebar-title">Products</h3>
        <div id="sidebar-products"></div>
    </div>

    <div class="header-container">
        <button id="add-product-button">Add New Product</button>
        <button id="save-button">Save Work</button>
        <button id="import-button">Import JSON</button>
        <input type="file" id="import-input" style="display: none;" accept=".json">
    </div>

    <div class="main-content">
        <div class="container">
            <h1 class="text-3xl font-bold mb-4">Product JSON Generator</h1>
            <p>Manage your product data with ease. Add, edit, or delete products, save your work, or import from a JSON file.</p>
            
            <h2 class="text-xl font-semibold mb-2">Products</h2>
            <div id="products-container">
                <!-- Product templates will be added here -->
            </div>
        </div>

        <!-- Image Selection Modal -->
        <div id="image-modal" class="modal">
            <div class="modal-content">
                <span class="close-modal" id="close-modal">×</span>
                <h3 class="text-lg font-semibold mb-2">Select Images</h3>
                <div class="image-grid" id="image-grid">
                    <!-- Images from the 'uploads' folder will be loaded here -->
                    <?php
                        $uploadsDir = 'uploads/';
                        $images = scandir($uploadsDir);

                        foreach ($images as $image) {
                            if ($image !== '.' && $image !== '..') {
                                $imagePath = $uploadsDir . $image;
                                echo "<img src='$imagePath' data-path='$imagePath' alt='Image'>";
                            }
                        }
                    ?>
                </div>
                <button id="insert-images" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded mt-4">Insert Images</button>
            </div>
        </div>

        <!-- Display the generated JSON -->
        <div class="container">
            <h2 class="text-xl font-semibold mt-4 mb-2">Generated JSON</h2>
            <textarea id="json-output" rows="10" readonly class="w-full json-output"></textarea>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const addProductButton = document.getElementById('add-product-button');
            const saveButton = document.getElementById('save-button');
            const importButton = document.getElementById('import-button');
            const importInput = document.getElementById('import-input');
            const productsContainer = document.getElementById('products-container');
            const jsonOutput = document.getElementById('json-output');
            const imageModal = document.getElementById('image-modal');
            const closeModal = document.getElementById('close-modal');
            const imageGrid = document.getElementById('image-grid');
            const insertImagesButton = document.getElementById('insert-images');
            let selectedImagePaths = [];
            let productCount = 0;

            // Load existing data from server on page load
            function loadExistingData() {
                const botName = getBotNameFromQueryString();
                if (botName) {
                    // Load data based on bot parameter
                    fetch(`data/${botName}.json`) // Assuming .json extension for data files
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP error! Status: ${response.status}`);
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data && Array.isArray(data)) {
                               // console.log('Loaded data:', data);
                                importData(data);
                            } else {
                                console.log('No data found or invalid data format.');
                                createProductTemplate(); // Create initial template if no data is found
                            }
                        })
                        .catch(error => {
                            console.error('Error loading data:', error);
                            createProductTemplate(); // Create initial template on error
                        });
                } else {
                    createProductTemplate(); // Create initial template if no bot name is provided
                }
            }

            // Function to get bot name from URL query string
            function getBotNameFromQueryString() {
                const queryParams = new URLSearchParams(window.location.search);
                return queryParams.get('bot');
            }

                // Function to create a new product template
            function createProductTemplate(productData = null) {
                productCount++;
                const productId = productData ? productData.id : `product${productCount}`;

                const productTemplate = document.createElement('div');
                productTemplate.classList.add('container', 'product-item');
                productTemplate.setAttribute('data-product-id', productId);

                productTemplate.innerHTML = `
                    <h3 class="text-lg font-semibold mb-2">Product ${productCount}</h3>
                    <form class="product-form">
                        <input type="hidden" name="product-id" value="${productId}">
                        <label for="${productId}-name">Name:</label>
                        <input type="text" id="${productId}-name" name="product-name" placeholder="Enter product name" value="${productData ? productData.name : ''}">

                        <label for="${productId}-description">Description:</label>
                        <textarea id="${productId}-description" name="product-description" placeholder="Enter product description">${productData ? productData.description : ''}</textarea>

                        <label for="${productId}-price">Price:</label>
                        <input type="number" id="${productId}-price" name="product-price" step="0.01" placeholder="Enter price" value="${productData && productData.price !== undefined ? productData.price : ''}">

                        <label for="${productId}-rating">Rating:</label>
                        <input type="number" id="${productId}-rating" name="product-rating" min="0" max="5" placeholder="Enter rating" value="${productData && productData.rating !== undefined  ? productData.rating : ''}">

                        <div class="image-input-container">
                            <label>Images:</label>
                            <button type="button" class="add-image-button bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 rounded mt-1">
                                <i class="fas fa-plus-circle"></i> Select Images
                            </button>
                            <div class="attached-images"></div>
                        </div>

                        <label for="${productId}-category">Category:</label>
                        <select id="${productId}-category" name="product-category">
                            <option value="">Select Category</option>
                            <option value="Electronics" ${productData && productData.category === 'Electronics' ? 'selected' : ''}>Electronics</option>
                            <option value="Wearables" ${productData && productData.category === 'Wearables' ? 'selected' : ''}>Wearables</option>
                            <option value="Furniture" ${productData && productData.category === 'Furniture' ? 'selected' : ''}>Furniture</option>
                            <option value="Clothing" ${productData && productData.category === 'Clothing' ? 'selected' : ''}>Clothing</option>
                             <option value="Footwear" ${productData && productData.category === 'Footwear' ? 'selected' : ''}>Footwear</option>
                             <option value="Footwearrrrr" ${productData && productData.category === 'Footwearrrrr' ? 'selected' : ''}>Footwearrrrr</option>
                        </select>

                        <label for="${productId}-tags">Tags (comma-separated):</label>
                        <input type="text" id="${productId}-tags" name="product-tags" placeholder="Enter tags separated by commas"  value="${productData && productData.tags ? productData.tags.join(', ') : ''}">

                        <button type="button" class="remove-product bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded mt-2">Remove Product</button>
                    </form>
                `;

                productsContainer.appendChild(productTemplate);

               // Add event listeners for the new product's form elements
                const productForm = productTemplate.querySelector('.product-form');
                productForm.addEventListener('input', updateJSONOutput);

                const addImageButton = productTemplate.querySelector('.add-image-button');
                addImageButton.addEventListener('click', () => {
                    openImageModal(productTemplate);
                });

                const removeProductButton = productTemplate.querySelector('.remove-product');
                removeProductButton.addEventListener('click', () => {
                    if (confirm('Are you sure you want to remove this product?')) {
                        productsContainer.removeChild(productTemplate);
                        updateJSONOutput();
                        removeProductFromSidebar(productId);
                    }
                });

                   // Add product to sidebar
                addProductToSidebar(productId);

                if(productData && productData.images)
                {
                      const attachedImagesContainer = productTemplate.querySelector('.attached-images');
                      productData.images.forEach(imagePath => {
                                const imageElement = document.createElement('img');
                                imageElement.src = imagePath;
                                imageElement.style.width = '50px';
                                imageElement.style.height = '50px';
                                imageElement.style.marginRight = '5px';

                                const hiddenInput = document.createElement('input');
                                hiddenInput.type = 'hidden';
                                hiddenInput.name = 'product-images[]';
                                hiddenInput.value = imagePath;

                                const imageContainer = document.createElement('div');
                                imageContainer.classList.add('attached-image');
                                imageContainer.appendChild(imageElement);
                                imageContainer.appendChild(hiddenInput);

                                const removeButton = document.createElement('button');
                                removeButton.type = 'button';
                                removeButton.innerHTML = '×';
                                removeButton.classList.add('remove-image');
                                removeButton.addEventListener('click', () => {
                                    attachedImagesContainer.removeChild(imageContainer);
                                    updateJSONOutput();
                                });

                                imageContainer.appendChild(removeButton);
                                attachedImagesContainer.appendChild(imageContainer);
                            });
                }
                updateJSONOutput();
                return productId;
            }

            // Function to update the JSON output
            function updateJSONOutput() {
                const productData = [];
                const productItems = productsContainer.querySelectorAll('.product-item');

                productItems.forEach(productItem => {
                    const productId = productItem.dataset.productId;
                    const productName = productItem.querySelector(`#${productId}-name`).value;
                    const productDescription = productItem.querySelector(`#${productId}-description`).value;
                    const productPrice = productItem.querySelector(`#${productId}-price`).value;
                    const productRating = productItem.querySelector(`#${productId}-rating`).value;
                    const productCategory = productItem.querySelector(`#${productId}-category`).value;
                    const productTags = productItem.querySelector(`#${productId}-tags`).value;

                    const imageInputs = productItem.querySelectorAll('.attached-images input[type="hidden"]');
                    const imagePaths = Array.from(imageInputs).map(input => input.value);

                    const productTagsArray = productTags ? productTags.split(',').map(tag => tag.trim()) : [];

                    const productObj = {
                        id: productId,
                        name: productName,
                        description: productDescription,
                        category: productCategory,
                        tags: productTagsArray,
                        images: imagePaths
                    };

                    // Only add price and rating if they have values
                    if (productPrice) {
                        productObj.price = parseFloat(productPrice);
                    }
                    if (productRating) {
                        productObj.rating = parseFloat(productRating);
                    }

                    productData.push(productObj);
                });

                jsonOutput.value = JSON.stringify(productData, null, 2);
            }

            // Function to open the image modal
            function openImageModal(productTemplate) {
                // Reset selected images
                selectedImagePaths = [];
                imageGrid.querySelectorAll('.selected').forEach(img => img.classList.remove('selected'));

                // Store the current product template
                currentProductTemplate = productTemplate;

                imageModal.style.display = 'block';
            }

            // Close the image modal
            closeModal.addEventListener('click', () => {
                imageModal.style.display = 'none';
            });

            // Handle image selection in the modal
            imageGrid.addEventListener('click', (event) => {
                if (event.target.tagName === 'IMG') {
                    event.target.classList.toggle('selected');
                    const imagePath = event.target.dataset.path;

                    if (event.target.classList.contains('selected')) {
                        selectedImagePaths.push(imagePath);
                    } else {
                        const index = selectedImagePaths.indexOf(imagePath);
                        if (index > -1) {
                            selectedImagePaths.splice(index, 1);
                        }
                    }
                }
            });

            // Insert selected images into the current product template
            insertImagesButton.addEventListener('click', () => {
                if (currentProductTemplate) {
                    const attachedImagesContainer = currentProductTemplate.querySelector('.attached-images');
                    selectedImagePaths.forEach(imagePath => {
                        const imageElement = document.createElement('img');
                        imageElement.src = imagePath;
                        imageElement.style.width = '50px';
                        imageElement.style.height = '50px';
                        imageElement.style.marginRight = '5px';

                        const hiddenInput = document.createElement('input');
                        hiddenInput.type = 'hidden';
                        hiddenInput.name = 'product-images[]';
                        hiddenInput.value = imagePath;

                        const imageContainer = document.createElement('div');
                        imageContainer.classList.add('attached-image');
                        imageContainer.appendChild(imageElement);
                        imageContainer.appendChild(hiddenInput);

                        const removeButton = document.createElement('button');
                        removeButton.type = 'button';
                        removeButton.innerHTML = '×';
                        removeButton.classList.add('remove-image');
                        removeButton.addEventListener('click', () => {
                            attachedImagesContainer.removeChild(imageContainer);
                            updateJSONOutput();
                        });

                        imageContainer.appendChild(removeButton);
                        attachedImagesContainer.appendChild(imageContainer);
                    });

                    selectedImagePaths = [];
                    imageModal.style.display = 'none';
                    updateJSONOutput();
                }
            });

            // Save data to server
            function saveData() {
                const botName = getBotNameFromQueryString();
                if (!botName) {
                    alert("Bot name is missing in the URL. Please use ?bot=name.");
                    return;
                }

                const jsonData = jsonOutput.value;

                fetch(`-7.3.php?bot=${botName}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `save_data=${encodeURIComponent(jsonData)}`
                })
                .then(response => response.text())
                .then(data => {
                    alert(data);
                })
                .catch(error => {
                    console.error('Error saving data:', error);
                    alert('Error saving data. See console for details.');
                });
            }

         // Import data from file
            function importData(importedData) {
                productsContainer.innerHTML = ''; // Clear existing products
                productCount = 0;

                importedData.forEach(productData => {
                     createProductTemplate(productData);
                   
                });
                 updateJSONOutput();
            }

            // --- Sidebar Functions ---

            function addProductToSidebar(productId) {
                const sidebarProducts = document.getElementById('sidebar-products');
                const productButton = document.createElement('div');
                productButton.classList.add('sidebar-step');
                productButton.textContent = `Product ${productId.replace('product', '')}`;
                productButton.setAttribute('data-product-id', productId);

                productButton.addEventListener('click', () => {
                    const productElement = document.querySelector(`.product-item[data-product-id="${productId}"]`);
                    if (productElement) {
                        productElement.scrollIntoView({ behavior: 'smooth' });
                    }
                });

                sidebarProducts.appendChild(productButton);
            }

            function removeProductFromSidebar(productId) {
                const productButton = document.querySelector(`.sidebar-step[data-product-id="${productId}"]`);
                if (productButton) {
                    productButton.remove();
                }
            }

            // --- Hamburger Menu Toggle ---

            document.querySelector('.hamburger-menu').addEventListener('click', () => {
                const sidebar = document.querySelector('.sidebar');
                sidebar.classList.toggle('show');
            });

            // Event listeners for buttons
            saveButton.addEventListener('click', saveData);
            addProductButton.addEventListener('click', ()=>{
                createProductTemplate()
            });
            importButton.addEventListener('click', () => importInput.click());

            importInput.addEventListener('change', (event) => {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        try {
                            const importedData = JSON.parse(e.target.result);
                            importData(importedData);
                            alert('Import successful!');
                        } catch (error) {
                            console.error('Error importing file:', error);
                            alert('Error importing file. Please make sure it\'s a valid JSON file.');
                        }
                    };
                    reader.readAsText(file);
                }
            });

            // Load existing data on page load
            loadExistingData();
        });
    </script>
</body>
</html>