<?php
/***
    Author: Vastvikta Nishad
    Last Modified on: 20 jan 2025
    Description: To Upload URL 
*/
?>
<style>
  @keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
/* Modal background */
.modal2 {
  display: none;
  position: fixed;
  z-index: 9999;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

/* Modal content */
.modal2-content {
  background: #fff;
  width: 300px;
  margin: 15% auto;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.2);
}

.modal2-content input {
  width: 90%;
  padding: 8px;
  margin: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.modal2-content button {
  background: Green;
  color: #fff;
  padding: 8px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
#collectionModal .modal2-content {
  position: relative;
  top: 160px; /* 🔹 Move modal2 80px down from its default position */
}
.modal2-content button:hover {
  background: Green;
}
</style>

<div class="style2-table">
    <div class="style-title">
        <h3>Upload URL</h3>    
    </div>

<form id="UploadURLForm">
    <table class="tableview tableview-2 mb-4">
        <tbody>
            <!-- Radio buttons to choose input type -->
 <tr>
                <!-- Description -->
                <td>
    <div id="urlWrapper">
        <input type="url"
               name="descDoc[]"
               class="descDoc text-area1 url-input"
               placeholder="Enter URL"
               style="margin-bottom:6px;" />
    </div>

    <button type="button" id="addUrlBtn" class="button-orange1">
        + Add another URL
    </button>
</td>

                <!-- Submit button -->
                <td class="left">
                    <input type="submit" value="Upload" class="submitUpload btn btn-danger btn-sm" id ="uploadBtn" name="submit" />
                </td>
            </tr>
        </tbody>
    </table>
</form>
</div>
<script>
       const CREATED_BY = "<?php echo $_SESSION['logged']; ?>";
 
document.getElementById('addUrlBtn').addEventListener('click', function () {
    const wrapper = document.getElementById('urlWrapper');

    const div = document.createElement('div');
    div.style.marginBottom = '6px';

    div.innerHTML = `
        <input type="url"
               name="descDoc[]"
               class="descDoc text-area1 url-input"
               placeholder="Enter URL"
               style="width:90%;" />
        <button type="button" class="removeUrlBtn">✖</button>
    `;

    wrapper.appendChild(div);
});

document.addEventListener('click', function (e) {
    if (e.target.classList.contains('removeUrlBtn')) {
        e.target.parentElement.remove();
    }
});
document.getElementById('UploadURLForm').addEventListener('submit', function (e) {
    e.preventDefault();

    // collect all URL inputs
    const urlInputs = document.querySelectorAll('input[name="descDoc[]"]');
    const urls = [];

    urlInputs.forEach(input => {
        if (input.value.trim() !== '') {
            urls.push(input.value.trim());
        }
    });

    if (urls.length === 0) {
        alert('Please enter at least one URL');
        return;
    }

    // build payload based on count
    let payload = {
        description: "Uploaded from UI",
        created_by: CREATED_BY
    };

    if (urls.length === 1) {
        payload.url = urls[0];          // ✅ single URL
    } else {
        payload.urls = urls;            // ✅ multiple URLs
    }

    fetch(BASE_URL + '/collections/test_category/documents', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Upload failed');
        }
        return response.json();
    })
    .then(data => {
        console.log('Success:', data);
        alert('URL(s) uploaded successfully');
        document.getElementById('UploadURLForm').reset();
        document.getElementById('urlWrapper').innerHTML = `
            <input type="url"
                   name="descDoc[]"
                   class="descDoc text-area1 url-input"
                   placeholder="Enter URL"
                   style="margin-bottom:6px;" />
        `;
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Something went wrong while uploading');
    });
});
</script>
