<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload & API Interaction</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: #ffffff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        h2 {
            text-align: center;
            color: #333;
            font-size: 28px;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            font-weight: 500;
            margin-bottom: 8px;
            color: #555;
        }
        input[type="text"],
        input[type="file"],
        button {
            width: 100%;
            padding: 14px;
            border-radius: 8px;
            border: 1px solid #ccc;
            box-sizing: border-box;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        input[type="text"],
        input[type="file"] {
            background-color: #f9f9f9;
        }
        input[type="text"]:focus,
        input[type="file"]:focus {
            border-color: #28a745;
            outline: none;
            background-color: #ffffff;
        }
        button {
            background-color: #28a745;
            color: #ffffff;
            border: none;
            cursor: pointer;
            font-size: 18px;
            margin-top: 10px;
        }
        button:hover {
            background-color: #218838;
        }
        button:active {
            background-color: #1e7e34;
        }
        #loader {
            display: none;
            border: 4px solid #f3f3f3;
            border-radius: 50%;
            border-top: 4px solid #28a745;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        #json-output {
            margin-top: 20px;
            padding: 20px;
            background: #ffffff;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            font-family: monospace;
            white-space: pre-wrap;
            color: #333;
        }
        #line-items-and-image {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-top: 30px;
        }
        .card-container {
            width: 48%;
            max-height: 600px; /* Set a fixed height */
            overflow-y: auto;
            background: #f9f9f9;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        .line-item-card {
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 20px;
            background-color: #ffffff;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .line-item-card h4 {
            margin: 0 0 15px;
            font-size: 18px;
            color: #333;
        }
        .line-item-label {
            font-size: 14px;
            font-weight: bold;
            color: #444;
            margin-bottom: 5px;
        }
        .line-item-value {
            font-size: 16px;
            color: #333;
            padding: 10px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 6px;
            margin-bottom: 10px;
            width: 100%;
            box-sizing: border-box;
        }
        #image-display {
            width: 48%;
            border: 1px solid #ddd;
            border-radius: 8px;
            text-align: center;
            background: #ffffff;
            overflow: hidden;
        }
        #image-display img {
            max-width: 100%;
            max-height: 100%;
        }
        #additionalButtons {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        #additionalButtons button {
            flex: 1;
            margin-right: 10px;
        }
        #additionalButtons button:last-child {
            margin-right: 0;
        }
        #submitOrderContainer {
            margin-top: 20px;
            display: flex;
            justify-content: flex-start;
        }
        #submit_order_canonicalbtn {
            background-color: #dc3545;
            color: #ffffff;
            border: none;
            padding: 14px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 18px;
        }
        #submit_order_canonicalbtn:hover {
            background-color: #c82333;
        }
        #submit_order_canonicalbtn:active {
            background-color: #bd2130;
        }
        #xml-and-image-container {
            display: none;
            margin-top: 30px;
            display: flex;
            justify-content: space-between;
        }
        #xml-container,
        #image-container {
            max-height: 800px;
            width: 48%;
            overflow-x: auto;
            overflow-y: auto;
            border: 1px solid #ddd; /* Border around XML and image containers */
            padding: 10px; /* Padding around XML and image content */
            background: #ffffff; /* White background for XML and image content */
            border-radius: 8px; /* Rounded corners */
        }
        #xml-container {
            max-height: 800px; /* Limit height of XML container */
            overflow-x: auto; /* Enable horizontal scrolling */
            overflow-y: auto; /* Enable vertical scrolling */
            white-space: nowrap; /* Prevent text wrapping */
            border: 1px solid #ddd; /* Border around XML container */
            padding: 10px; /* Padding around XML content */
            background: #ffffff; /* White background for XML content */
            border-radius: 8px; /* Rounded corners */
        }
        #xml-container pre {
            margin: 0; /* Remove margin from preformatted text */
        }
        #image-container img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Upload File and Enter Sender ID</h2>

    <div class="form-group">
        <label for="senderId">Sender ID</label>
        <input type="text" id="senderId" placeholder="Enter Sender ID">
    </div>

    <div class="form-group">
        <label for="fileInput">Upload PDF/Image</label>
        <input type="file" id="fileInput" accept=".pdf, .jpg, .jpeg, .png">
    </div>

    <button id="submitBtn">Submit</button>

    <div id="loader"></div>

    

    <!-- Line items and Image -->
    <div id="line-items-and-image" style="display:none;">
        <div id="result-container" class="card-container"></div>
        <div id="image-display"></div>
    </div>
    
    <button id="generateJsonBtn" style="display:none;">Generate JSON</button>
    <div id="json-output"></div>

    <div id="additionalButtons" style="display:none;">
        <button id="edit_fields">Edit Fields</button>
        <button id="createOrderCanonicalBtn">Create Order Canonical</button>
    </div>
    
    <div id="submitOrderContainer" style="display:none;">
        <button id="submit_order_canonicalbtn">Submit Order Canonical</button>
    </div>
    
    <!-- XML and Image Display -->
    <div id="xml-and-image-container">
        <div id="xml-container"></div>
        <div id="image-container"></div>
    </div>
</div>

<script>
    let generatedJsonData = {};
    const api_url = "https://8c47-35-187-224-10.ngrok-free.app/";

    let edited = false;
    let original_json = {};

    document.getElementById('submitBtn').addEventListener('click', function () {
        const senderId = document.getElementById('senderId').value;
        const fileInput = document.getElementById('fileInput').files[0];
        const loader = document.getElementById('loader');
        const resultContainer = document.getElementById('result-container');

        resultContainer.innerHTML = '';
        document.getElementById('json-output').innerHTML = '';

        if (!senderId || !fileInput) {
            alert('Please enter Sender ID and upload a file.');
            return;
        }
        
        const formData = new FormData();
        formData.append('senderId', senderId);
        formData.append('file', fileInput);
        
        loader.style.display = 'block';

        fetch(api_url + '/po_processing', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            loader.style.display = 'none';
            original_json = data;
            displayResults(data);
            document.getElementById('generateJsonBtn').style.display = 'block';
        })
        .catch(error => {
            loader.style.display = 'none';
            console.error('Error:', error);
        });
    });

    function displayResults(data) {
        const resultContainer = document.getElementById('result-container');
        const imageDisplay = document.getElementById('image-display');

        resultContainer.innerHTML = '';

        for (const [key, value] of Object.entries(data)) {
            if (key !== 'line_items') {
                const div = document.createElement('div');
                div.classList.add('form-group');
                
                const label = document.createElement('label');
                label.classList.add('line-item-label');
                label.innerText = key;

                const input = document.createElement('input');
                input.type = 'text';
                input.value = value;
                input.classList.add('editable-field');
                input.dataset.key = key;
                input.readOnly = true;

                div.appendChild(label);
                div.appendChild(input);
                resultContainer.appendChild(div);
            }
        }

        if (data.line_items && Array.isArray(data.line_items)) {
            data.line_items.sort((a, b) => a.line_number - b.line_number);
            data.line_items.forEach((item, index) => {
                const card = document.createElement('div');
                card.classList.add('line-item-card');
                card.innerHTML = `<h4>Line Item ${index + 1}</h4>`;
                
                Object.entries(item).forEach(([key, value]) => {
                    const div = document.createElement('div');
                    div.classList.add('form-group');
                    
                    const label = document.createElement('label');
                    label.classList.add('line-item-label');
                    label.innerText = key;

                    const input = document.createElement('input');
                    input.type = 'text';
                    input.value = value;
                    input.classList.add('line-item-value');
                    input.dataset.lineItemKey = key;
                    input.readOnly = true;

                    div.appendChild(label);
                    div.appendChild(input);
                    card.appendChild(div);
                });
                
                resultContainer.appendChild(card);
            });
        }

        const imageUrl = URL.createObjectURL(document.getElementById('fileInput').files[0]);
        imageDisplay.innerHTML = `<img src="${imageUrl}" alt="Uploaded Image">`;

        document.getElementById('line-items-and-image').style.display = 'flex';
        document.getElementById('additionalButtons').style.display = 'flex';
        document.getElementById('submitOrderContainer').style.display = 'flex';
    }

    function generateJsonData() {
        const resultContainer = document.getElementById('result-container');
        const finalData = {};

        resultContainer.querySelectorAll('.editable-field').forEach(field => {
            finalData[field.dataset.key] = field.value;
        });

        finalData.line_items = [];
        resultContainer.querySelectorAll('.line-item-card').forEach(card => {
            const lineItem = {};
            card.querySelectorAll('.line-item-value').forEach(field => {
                lineItem[field.dataset.lineItemKey] = field.value;
            });
            finalData.line_items.push(lineItem);
        });

        return finalData;
    }

    document.getElementById('generateJsonBtn').addEventListener('click', function () {
        const jsonOutput = document.getElementById('json-output');
        generatedJsonData = generateJsonData();

        jsonOutput.innerHTML = `<textarea rows="10" style="width: 100%; box-sizing: border-box;">${JSON.stringify(generatedJsonData, null, 2)}</textarea>`;
    });

    document.getElementById('edit_fields').addEventListener('click', function () {
        document.querySelectorAll('.editable-field').forEach(field => {
            field.readOnly = false;
        });

        document.querySelectorAll('.line-item-value').forEach(field => {
            field.readOnly = false;
        });

        alert("Fields are now editable.");
    });

    document.getElementById('createOrderCanonicalBtn').addEventListener('click', function () {
        const loader = document.getElementById('loader');
        const senderId = document.getElementById('senderId').value;

        loader.style.display = 'block';

        const formData = new FormData();
        formData.append('senderId', senderId);
        generatedJsonData = generateJsonData();
        formData.append('purchaseOrderNumber', generatedJsonData.purchase_order_number);
        formData.append('json', JSON.stringify(generatedJsonData));

        fetch(api_url + '/create_order_canonical', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            loader.style.display = 'none';

            const xmlContainer = document.getElementById('xml-container');
            if (!xmlContainer) {
                console.error('xml-container not found');
                return;
            }
            xmlContainer.innerHTML = `<pre>${escapeHTML(data)}</pre>`;

            const imageContainer = document.getElementById('image-container');
            const imageUrl = URL.createObjectURL(document.getElementById('fileInput').files[0]);
            imageContainer.innerHTML = `<img src="${imageUrl}" alt="Uploaded Image">`;

            document.getElementById('xml-and-image-container').style.display = 'flex';
        })
        .catch(error => {
            loader.style.display = 'none';
            console.error('Error creating canonical order:', error);
        });
    });

    document.getElementById("submit_order_canonicalbtn").addEventListener('click', function () {
        const loader = document.getElementById('loader');
        const senderId = document.getElementById('senderId').value;

        loader.style.display = 'block';

        const formData = new FormData();
        formData.append('senderId', senderId);
        generatedJsonData = generateJsonData();
        formData.append('purchaseOrderNumber', generatedJsonData.purchase_order_number);
        formData.append('json', JSON.stringify(generatedJsonData));

        fetch(api_url + '/submit_order_canonical', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            loader.style.display = 'none';
            alert(data.message);
        })
        .catch(error => {
            loader.style.display = 'none';
            console.error('Error submitting canonical order:', error);
        });

        checkIfEdited(original_json, generatedJsonData);
    });

    function checkIfEdited(original, generated) {
        const keys = Object.keys(original);
        edited = false;

        keys.forEach(key => {
            if (key !== "line_items" && original[key] !== generated[key]) {
                edited = true;
            } else if (key === "line_items") {
                edited = JSON.stringify(original.line_items) !== JSON.stringify(generated.line_items);
            }
        });

        if (edited) {
            addToTraining();
        }
    }

    function addToTraining() {
        const jsonOutput = generatedJsonData;
        const fileInput = document.getElementById('fileInput').files[0];

        const formData_add = new FormData();
        formData_add.append('file', fileInput);
        formData_add.append('purchaseOrderNumber', jsonOutput.purchase_order_number);
        formData_add.append('json', JSON.stringify(jsonOutput));

        fetch(api_url + '/add_to_training', {
            method: 'POST',
            body: formData_add
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
        })
        .catch(error => {
            console.error('Error adding to training:', error);
        });
    }

    function escapeHTML(html) {
        return html.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }
</script>
</body>
</html>


Just for the submit button loader can we add a progress bar with the labels Processing PO, Creating image Encodings, Creating text Encodings, Extracting information

can you make it it look realistic and add some good styling to progress bar to look modern, don't remove the other parts loarder only for the submit button (first one)