<?php
/***
    Author: Farhan Akhtar
    Last Modified on: 17 july 2025
    Description: To Upload Documents for Knowledge Base AI Assistant
*/
?>
<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;
}
.url-row {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
}

.url-row input {
    flex: 1;
}

</style>

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

<form id="UploadForm">
    <table class="tableview tableview-2 mb-4">
        <tbody>
            <!-- Radio buttons to choose input type -->
            <tr>
                <td class="left" colspan="4">
                    <label>
                        <input type="radio" name="uploadType" value="file" checked> Upload File
                    </label>
                    &nbsp;&nbsp;
                    <label>
                        <input type="radio" name="uploadType" value="url"> Provide URL
                    </label>
                </td>
            </tr>

            <!-- File input (toggles visibility) -->
            <tr>
              
                <td class="left" style="width:420px;">
                    <label class="labelUpload" for="uploadDoc">
                        <input type="file" class="uploadDoc" id="uploadDoc" name="uploadDoc[]" multiple
                            accept="application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/csv" />
                        <a title="Only PDF, Excel, Word, and CSV files Allowed">Select Files From Here
                            <i class="far fa-file-pdf text-danger"></i>
                            <i class="far fa-file-excel text-success"></i>
                            <i class="far fa-file-word text-primary"></i>
                            <i class="far fa-file-excel text-secondary"></i>
                        </a>
                    </label>
                    <div style="font-size: 10px; color: #555; margin-top: 6px;">
                      <a 
                        id="downloadLink"
                        href="../../unistorage/2224/Guidelines/Guidelines.pdf" 
                        style="color: #007bff; text-decoration: none;"
                      >
                        Download Document Guidelines
                      </a>
                    </div>

                    <script>
                      document.getElementById('downloadLink').addEventListener('click', function (e) {
                        e.preventDefault();
                        const link = document.createElement('a');
                        link.href = this.href;
                        link.download = 'Guidelines.pdf';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                      });
                    </script>

                    </div>
                    <!-- URL input (hidden unless selected) -->
                    <div id="urlInputRow" style="display: none;">
                        <label>Enter File URLs:</label>

                        <div id="urlWrapper">
                            <div class="url-row" style="display:flex; align-items:center; gap:10px;">
                                <input type="url"
                                      name="fileUrl[]"
                                      placeholder="https://example.com/file.pdf"
                                      required
                                      style="flex:1;" />

                                <button type="button"
                                        id="addUrlBtn"
                                        style="
                                            background-color:#28a745;
                                            color:white;
                                            border:none;
                                            padding:5px 8px;
                                            border-radius:6px;
                                            cursor:pointer;
                                            font-size:12px;
                                            transition:background-color 0.3s;
                                        ">
                                    + Add another URL
                                </button>
                            </div>
                        </div>
                    </div>
                </td>

                <!-- Classification dropdown -->
                 
                <div class="row">
                <td class="left">
                    <label for="kb_classificationDoc">Collection:</label>
                        <select name="kb_classificationDoc" style="width:150px;" id="kb_classificationDoc">
                             <option selected disabled value="">Select Collection</option>
                          
                        </select>
                        <svg id="editCollectionBtn" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" height="15" width="15"><path d="M535.6 85.7C513.7 63.8 478.3 63.8 456.4 85.7L432 110.1L529.9 208L554.3 183.6C576.2 161.7 576.2 126.3 554.3 104.4L535.6 85.7zM236.4 305.7C230.3 311.8 225.6 319.3 222.9 327.6L193.3 416.4C190.4 425 192.7 434.5 199.1 441C205.5 447.5 215 449.7 223.7 446.8L312.5 417.2C320.7 414.5 328.2 409.8 334.4 403.7L496 241.9L398.1 144L236.4 305.7zM160 128C107 128 64 171 64 224L64 480C64 533 107 576 160 576L416 576C469 576 512 533 512 480L512 384C512 366.3 497.7 352 480 352C462.3 352 448 366.3 448 384L448 480C448 497.7 433.7 512 416 512L160 512C142.3 512 128 497.7 128 480L128 224C128 206.3 142.3 192 160 192L256 192C273.7 192 288 177.7 288 160C288 142.3 273.7 128 256 128L160 128z"/></svg>
                        <svg xmlns="http://www.w3.org/2000/svg" id="deleteCollectionBtn" viewBox="0 0 640 640"  height="15" width="15"><path d="M232.7 69.9L224 96L128 96C110.3 96 96 110.3 96 128C96 145.7 110.3 160 128 160L512 160C529.7 160 544 145.7 544 128C544 110.3 529.7 96 512 96L416 96L407.3 69.9C402.9 56.8 390.7 48 376.9 48L263.1 48C249.3 48 237.1 56.8 232.7 69.9zM512 208L128 208L149.1 531.1C150.7 556.4 171.7 576 197 576L443 576C468.3 576 489.3 556.4 490.9 531.1L512 208z"/></svg>
                        <svg id="openModalBtn" xmlns="http://www.w3.org/2000/svg" 
                            viewBox="0 0 640 640" height="15" width="15" >
                        <path d="M352 128C352 110.3 337.7 96 320 96C302.3 96 288 110.3 288 128L288 288L128 288C110.3 288 96 302.3 96 320C96 337.7 110.3 352 128 352L288 352L288 512C288 529.7 302.3 544 320 544C337.7 544 352 529.7 352 512L352 352L512 352C529.7 352 544 337.7 544 320C544 302.3 529.7 288 512 288L352 288L352 128z"/>
                        </svg><button type="button" id="fetchDocsBtn"  style="background-color:#28a745; color:white; border:none; padding:5px 8px; border-radius:6px; cursor:pointer; font-size:12px; margin-left:10px; transition:background-color 0.3s;">Fetch Files</button>

                </td>
                </div>
            </tr>
            <tr>
                <!-- Description -->
                <td>
                    <textarea name="descDoc" id="descDoc" class="descDoc text-area1" placeholder="Enter Description here..." style="resize: none;"></textarea>
                </td>

                <!-- Submit button -->
                <td class="left">
                  <input type="hidden" name="upload_mode" id="upload_mode" value="file">
                  <input type="submit"
                            value="Upload Doc"
                            class="submitUpload btn btn-danger btn-sm"
                            id="uploadBtn"
                            name="submit" />
                </td>
            </tr>
        </tbody>
    </table>

    <!-- Preview or list section (optional) -->
    <div class="files" style="display: none;">
        <ul class="file-list"></ul>
    </div>
</form>

   <table class="tableview tableview-2 mt-4" id="fileTable">
  <thead>
    <tr class="background">
      <td>SNo.</td>
      <td>File Name & File URL</td>
      <td>Description</td>
      <td>Created By</td>
      <td>Collection name</td>
      <!-- <td>Size</td> -->
      <td>Datetime</td>
      <td>Action</td>
    </tr>
  </thead>
  <tbody></tbody>
</table>


</div>

<div id="createModal" class="modal2">
  <div class="modal2-content">
    <h3>Add Classification <span class="close2" style="float:right;cursor:pointer;font-size:20px;">&times;</span></h3>
    <input type="text" id="categoryInput" placeholder="Enter classification name" />
    <br>
    <button  style="background-color:Green"id="saveBtn">Save</button>
  </div>
</div>

<!-- 🔹 Modal (reuse your existing modal2 styling/structure) -->
<div id="collectionModal" class="modal2" style="display:none;">
  <div class="modal2-content" style="padding:20px;max-width:400px;margin:auto;">
    
    <h3>Edit Classification <span class="close" style="float:right;cursor:pointer;font-size:20px;">&times;</span></h3>

    <label>Selected Classification:</label>
    <input type="text" id="collectionName" readonly style="width:100%;margin-bottom:10px;">

    <label>New Name:</label>
    <input type="text" id="newCollectionName" style="width:100%;margin-bottom:15px;" placeholder="Enter new name">

    <button id="updateCollectionBtn" style="background-color:green;color:white;padding:8px 12px;border:none;border-radius:4px;cursor:pointer;">
      Save Changes
    </button>
  </div>
</div>
<!-- Processing Modal -->
<!-- Processing Modal -->
<div id="processingModal" style="
  display:none;  /* keep hidden initially */
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background:rgba(0,0,0,0.5);
  z-index:8888;
  justify-content:center;
  align-items:center;
  font-family:sans-serif;
">
  <div style="
    background:#fff;
    padding:30px 40px;
    border-radius:12px;
    box-shadow:0 4px 20px rgba(0,0,0,0.3);
    font-size:18px;
    font-weight:600;
    color:#333;
    text-align:center;
    min-width:250px;
  ">
    🔄 Processing... <br><small>Please wait</small>
  </div>
</div>
<script>
document.getElementById('addUrlBtn').addEventListener('click', function () {
    let wrapper = document.getElementById('urlWrapper');

    let div = document.createElement('div');
    div.className = 'url-row';

    div.innerHTML = `
        <input type="url" name="fileUrl[]" placeholder="https://example.com/file.pdf" required />
        <button type="button" class="removeUrlBtn" style="background-color:#28a745; color:white; border:none; padding:5px 8px; border-radius:6px; cursor:pointer; font-size:12px; margin-left:10px; transition:background-color 0.3s;">✖</button>
    `;

    wrapper.appendChild(div);

    // show remove button on all rows
    document.querySelectorAll('.removeUrlBtn').forEach(btn => {
        btn.style.display = 'inline-block';
        btn.onclick = function () {
            this.parentElement.remove();
        };
    });
});

document.getElementById("fetchDocsBtn").addEventListener("click", async () => {
  const tableBody = document.querySelector("#fileTable tbody");
  const classification = document.getElementById("kb_classificationDoc").value;

  if (!classification) {
    alert("⚠️ Please select a classification first");
    return;
  }

  tableBody.innerHTML = "<tr><td colspan='8'>Loading...</td></tr>";

  try {
    const response = await fetch(
      `${BASE_URL}/collections/${classification}/documents`
    );
    if (!response.ok) throw new Error("Fetch failed");

    const data = await response.json();
    let rows = "";
    let serialNo = 1;

    if (!data.documents || data.documents.length === 0) {
      tableBody.innerHTML = "<tr><td colspan='8'>No documents found</td></tr>";
      return;
    }

  data.documents.forEach(doc => {
    const filename = doc.filename || doc.url || "-";
    const description = doc.description || "-";
    const createdBy = doc.created_by || doc.all_metadata?.created_by || "-";
    const date = doc.date_uploaded ? formatDate(doc.date_uploaded) : "-";

    const isUrl = doc.type === "url" || doc.source_type === "url";

    const fileExtension = !isUrl && filename.includes(".")
      ? filename.split(".").pop().toLowerCase()
      : "";

    const viewLink = isUrl
      ? filename
      : `/ThirdPartyApi/new_knowledgebase_faq/Kb_Latest/uploads/${classification}/${encodeURIComponent(filename)}`;

    let downloadAction = "";
    if (!isUrl && ["csv", "xls", "xlsx", "docx","pdf"].includes(fileExtension)) {
      downloadAction = `
        <i class="fas fa-download download-btn"
          data-url="${viewLink}"
          style="color:green; cursor:pointer; margin-right:10px;"></i>
      `;
    }

    rows += `
      <tr>
        <td>${serialNo++}</td>
        <td>${filename}</td>
        <td>${description}</td>
        <td>${createdBy}</td>
        <td>${classification}</td>
        <td>${date}</td>
        <td>
          <i class="fas fa-eye view-btn"
            data-url="${viewLink}"
            style="color:#007bff; cursor:pointer; margin-right:10px;"></i>

          ${downloadAction}

          <i class="fas fa-trash delete-icon"
            data-collection="${classification}"
            data-filename="${filename}"
            style="color:red; cursor:pointer;"></i>
        </td>
      </tr>`;
  });


    tableBody.innerHTML = rows;
    attachActionHandlers();

  } catch (err) {
    console.error(err);
    tableBody.innerHTML =
      "<tr><td colspan='8' style='color:red;'>Error loading documents</td></tr>";
  }
});

// 🔹 Load All Documents (Fixed Version)
/* ================= LOAD DOCUMENTS (UNCHANGED FETCH) ================= */
async function loadAllDocuments() {
  const tableBody = document.querySelector("#fileTable tbody");
  tableBody.innerHTML = "<tr><td colspan='8'>Loading...</td></tr>";

  try {
    const response = await fetch(`${BASE_URL}/collections/all/documents`);
    if (!response.ok) throw new Error("Failed to fetch document data");

    const data = await response.json();
    let rows = "";
    let serialNo = 1;

    data.collections.forEach(collection => {
      const collectionName = collection.collection_name;
      if (!collection.documents || collection.documents.length === 0) return;

      collection.documents.forEach(doc => {
        const status = (doc.status || "").toLowerCase();
        if (status.includes("missing") || status.includes("deleted")) return;

        const filename = doc.filename || doc.url || "-";
        const description = doc.description || "-";
        const createdBy = doc.created_by || doc.all_metadata?.created_by || "-";

        const size =
          typeof doc.file_size_mb === "number"
            ? `${doc.file_size_mb.toFixed(2)} MB`
            : "-";

        const date = doc.date_uploaded ? formatDate(doc.date_uploaded) : "-";

        const isUrl = doc.type === "url" || doc.source_type === "url";
        const fileExtension = !isUrl ? filename.split(".").pop().toLowerCase() : "";

        const viewLink = isUrl
          ? filename
          : `/ThirdPartyApi/new_knowledgebase_faq/Kb_Latest/uploads/${collectionName}/${encodeURIComponent(filename)}`;

        let downloadAction = "";

        if (!isUrl && ["csv", "xls", "xlsx", "docx"].includes(fileExtension)) {
          downloadAction = `
            <i class="fas fa-download download-btn"
               data-url="${viewLink}"
               style="color:green; cursor:pointer; margin-right:10px;"></i>`;
        }

        if (!isUrl && fileExtension === "pdf") {
          downloadAction = `
            <a href="${viewLink}" download="${filename}">
              <i class="fas fa-download"
                 style="color:green; cursor:pointer; margin-right:10px;"></i>
            </a>`;
        }

        rows += `
          <tr>
            <td>${serialNo++}</td>
            <td>${filename}</td>
            <td>${description}</td>
            <td>${createdBy}</td>
            <td>${collectionName}</td>
            <td>${date}</td>
            <td>
              <i class="fas fa-eye view-btn"
                 data-url="${viewLink}"
                 style="color:#007bff; cursor:pointer; margin-right:10px;"></i>
              ${downloadAction}
              <i class="fas fa-trash delete-icon"
                 data-collection="${collectionName}"
                 data-filename="${filename}"
                 style="color:red; cursor:pointer;"></i>
            </td>
          </tr>`;
      });
    });

    tableBody.innerHTML =
      rows || `<tr><td colspan="8">No documents found</td></tr>`;

    attachActionHandlers();

  } catch (err) {
    console.error(err);
    tableBody.innerHTML =
      `<tr><td colspan="8" style="color:red;">Error loading documents</td></tr>`;
  }
}


/* ================= DELETE (FILE + URL – API CORRECT) ================= */
function attachActionHandlers() {
  document.querySelectorAll(".view-btn").forEach(btn => {
    btn.onclick = () => window.open(btn.dataset.url, "_blank");
  });

  document.querySelectorAll(".delete-icon").forEach(icon => {
    icon.onclick = async () => {
      const collection = icon.dataset.collection;
      const filename = icon.dataset.filename;

      console.log("DELETE payload:", { filename });

      if (!filename) {
        alert("❌ Filename missing");
        return;
      }

      try {
        const res = await fetch(
          `${BASE_URL}/collections/${collection}/documents`,
          {
            method: "DELETE",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              filename: filename
            })
          }
        );

        if (!res.ok) {
          const err = await res.json();
          throw new Error(err.error || "Delete failed");
        }

        alert("✅ Deleted successfully");
        loadAllDocuments();
      } catch (err) {
        console.error("❌ Delete failed:", err.message);
        alert(err.message);
      }
    };
  });
}

/* ================= DOWNLOAD ================= */
$(document).on("click", ".download-btn", async function () {
  const fileUrl = $(this).data("url");
  const fileName = decodeURIComponent(fileUrl.split("/").pop());

  try {
    const res = await fetch(fileUrl);
    if (!res.ok) throw new Error();

    const blob = await res.blob();
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(a.href);
  } catch {
    alert("Download failed");
  }
});

/* ================= UTIL ================= */
function formatDate(dateString) {
  return new Date(dateString).toLocaleString();
}

document.addEventListener("DOMContentLoaded", loadAllDocuments);


// 📅 Format readable date
function formatDate(dateString) {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString();
}

// ⚙️ Add click events to buttons
function attachActionHandlers() {
  // VIEW document
  document.querySelectorAll(".view-btn").forEach(btn => {
    btn.addEventListener("click", () => {
      const url = btn.getAttribute("data-url");
      window.open(url, "_blank"); // Opens in new tab
    });
  });

  // DELETE document
  document.querySelectorAll(".delete-icon").forEach(icon => {
  icon.addEventListener("click", async () => {
    const collection = icon.getAttribute("data-collection");
    const filename = icon.getAttribute("data-filename");

    console.log("DELETE payload:", { collection, filename });

    if (!filename) {
      alert("❌ Filename missing");
      return;
    }

    if (!confirm(`🗑️ Are you sure you want to delete "${filename}" from "${collection}"?`)) {
      return;
    }

    try {
      const res = await fetch(
        `${BASE_URL}/collections/${collection}/documents`,
        {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            filename: filename   // RAW value
          })
        }
      );

      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Delete request failed");
      }

      alert(`✅ Document "${filename}" deleted successfully!`);
      loadAllDocuments();
    } catch (err) {
      console.error("❌ Delete failed:", err);
      alert("❌ " + err.message);
    }
  });
});
}


// Run on page load
document.addEventListener("DOMContentLoaded", loadAllDocuments);


// ============================
// ✅ FILE INPUT HANDLING (KEPT FROM OLD CODE)
// ============================

$(".uploadDoc").change(function (e) {
    let files = e.target.files;

    // Allowed file types
    const allowedTypes = [
        "application/pdf",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
        "application/vnd.ms-excel", // .xls
        "application/msword", // .doc
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
        "text/csv"
    ];

    // Filter valid files only
    let validFiles = Array.from(files).filter(file => allowedTypes.includes(file.type));

    if (validFiles.length !== files.length) {
        alert("Only PDF, Excel, Word, and CSV files are allowed. Other files will be ignored.");
    }

    updateState({ filesArr: validFiles });
    renderFileList();
    toggleFileList();
});

// Remove a file from list
$(".files").on("click", ".file-list-item > i", function () {
    let key = $(this).parent().data("key");
    let curArr = [...state.filesArr];
    curArr.splice(key, 1);
    updateState({ filesArr: curArr });
    renderFileList();
    toggleFileList();
});

// Toggle file list display
function toggleFileList() {
    if (state.filesArr.length > 0) {
        $(".files").show();
    } else {
        $(".files").hide();
    }
}

// Render selected file list
function renderFileList() {
    let fileMap = state.filesArr.map((file, index) => {
        let suffix = "bytes";
        let size = file.size;
        if (size >= 1024 && size < 1024000) {
            suffix = "KB";
            size = Math.round((size / 1024) * 100) / 100;
        } else if (size >= 1024000) {
            suffix = "MB";
            size = Math.round((size / 1024000) * 100) / 100;
        }

        return `<li class="file-list-item" data-key="${index}">
                    ${file.name} <span class="file-size">${size} ${suffix}</span> 
                    <i class="fa fa-trash"></i>
                </li>`;
    });
    $(".file-list").html(fileMap);
}

// ============================
// ✅ TOGGLE URL / FILE INPUT (KEPT FROM OLD CODE)
// ============================
document.addEventListener("DOMContentLoaded", function () {
    const uploadTypeRadios = document.querySelectorAll('input[name="uploadType"]');
    const fileInputSection = document.querySelector(".labelUpload");
    const urlInputRow = document.getElementById("urlInputRow");

    const uploadBtn = document.getElementById("uploadBtn");
    const uploadModeInput = document.getElementById("upload_mode");

    uploadTypeRadios.forEach(radio => {
        radio.addEventListener("change", function () {

            if (this.value === "url") {
                // UI switch
                fileInputSection.style.display = "none";
                urlInputRow.style.display = "block";

                // button + backend switch
                uploadBtn.value = "Upload URL";
                uploadModeInput.value = "url";

            } else {
                // UI switch
                fileInputSection.style.display = "block";
                urlInputRow.style.display = "none";

                // button + backend switch
                uploadBtn.value = "Upload Doc";
                uploadModeInput.value = "file";
            }
        });
    });
});


// ============================
// ✅ API-BASED LOGIC (NEW UPLOAD SCRIPT)
// ============================


// Load classification dropdown from collections API
async function loadCollections() {
    try {
        const res = await fetch(`${BASE_URL}/collections`);
        const data = await res.json();
        console.log('RAW RESPONSE:', data);

        const oldSelect = document.getElementById("kb_classificationDoc");

        // 🔥 DESTROY select2 / choices if attached
        if (window.jQuery && $(oldSelect).hasClass("select2-hidden-accessible")) {
            $(oldSelect).select2('destroy');
            console.log('SELECT2 DESTROYED');
        }

        // 🔁 CLONE & REPLACE (removes any injected/cached options)
        const select = oldSelect.cloneNode(false);
        oldSelect.parentNode.replaceChild(select, oldSelect);

        select.id = "kb_classificationDoc";
        select.name = "kb_classificationDoc";

        select.innerHTML = `<option selected disabled value="">Select Collection</option>`;

        data.collection_names
            .filter(name => name.toLowerCase() !== 'email_content')
            .forEach(name => {
                console.log('ADDING:', name);
                const opt = document.createElement("option");
                opt.value = name;
                opt.textContent = name;
                select.appendChild(opt);
            });

        // 🧹 FINAL HARD CHECK
        [...select.options].forEach(opt => {
            if (
                opt.value.toLowerCase() === 'email_content' ||
                opt.textContent.toLowerCase() === 'email_content'
            ) {
                console.log('FORCE REMOVED:', opt.value);
                opt.remove();
            }
        });

        console.log(
            'FINAL OPTIONS:',
            [...select.options].map(o => o.value)
        );

    } catch (err) {
        console.error("Error loading collections:", err);
        alert("Error loading collections!");
    }
}
loadCollections();
// ============================
// ✅ UPLOAD HANDLER USING API
// ============================
const CREATED_BY = "<?php echo $_SESSION['logged']; ?>";
document.querySelector(".submitUpload").addEventListener("click", async function (e) {
    e.preventDefault();

    const button = e.currentTarget;
    const classification = document.getElementById("kb_classificationDoc").value;
    const description = document.getElementById("descDoc").value.trim();
    const uploadMode = document.getElementById("upload_mode").value;
    const modal = document.getElementById("processingModal");

    if (!classification) {
        alert("⚠️ Please select a classification before uploading!");
        return;
    }

    if (!description) {
        alert("⚠️ Please enter a description for the document!");
        return;
    }

    const endpoint = `${BASE_URL}/collections/${classification}/documents`;

    button.disabled = true;
    modal.style.display = "flex";

    try {
        /* ================= FILE MODE ================= */
        if (uploadMode === "file") {
            const files = state.filesArr;

            if (!files || files.length === 0) {
                alert("⚠️ Please select at least one document to upload!");
                throw new Error("No files selected");
            }

            for (const file of files) {
                const formData = new FormData();
                formData.append("file", file);
                formData.append("description", description);
                formData.append("created_by", CREATED_BY);

                const response = await fetch(endpoint, {
                    method: "POST",
                    body: formData
                });

                if (!response.ok) throw new Error(`File upload failed: ${file.name}`);
            }

            alert("✅ All files uploaded successfully!");
        }

        /* ================= URL MODE (SERVER-SAFE) ================= */
        if (uploadMode === "url") {
            const urlInputs = document.querySelectorAll('input[name="fileUrl[]"]');
            const urls = Array.from(urlInputs)
                .map(i => i.value.trim())
                .filter(Boolean);

            if (urls.length === 0) {
                alert("⚠️ Please add at least one URL before uploading!");
                throw new Error("No URLs provided");
            }

            // 🔒 Always send ONE URL per request (backend-safe)
            for (const singleUrl of urls) {
                const payload = {
                    url: singleUrl,
                    description: description,
                    created_by: CREATED_BY
                };

                const response = await fetch(endpoint, {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(payload)
                });

                if (!response.ok) {
                    throw new Error(`URL upload failed: ${singleUrl}`);
                }
            }

            alert("✅ URL(s) uploaded successfully!");
        }

        location.reload();

    } catch (error) {
        console.error("❌ Upload error:", error);
        alert("❌ Upload failed. Please check console for details.");
        button.disabled = false;
        modal.style.display = "none";
    }
});



document.getElementById("deleteCollectionBtn").addEventListener("click", async () => {
  const dropdown = document.getElementById("kb_classificationDoc");
  const selected = dropdown.value;

  if (!selected) {
    alert("Please select a classification to delete!");
    return;
  }

  // Confirmation dialog
  const confirmDelete = confirm(`Are you sure you want to delete the classification: "${selected}" ?`);
  if (!confirmDelete) return;

  try {
    const res = await fetch(`http://209.38.165.2:8093/collections/${selected}`, {
      method: "DELETE",
    });

    if (!res.ok) throw new Error(`HTTP ${res.status}`);

    alert(`✅ Classification "${selected}" deleted successfully!`);
    location.reload();
 

  } catch (err) {
    console.error("❌ Error deleting classification:", err);
    alert("Error deleting classification. Please try again.");
  }
});

      const createModal = document.getElementById("createModal");
  const closeBtn2 = document.querySelector(".close2");

  // Close when clicking the × button
  closeBtn2.addEventListener("click", () => {
    createModal.style.display = "none";
  });

  // Optional: also close when clicking outside the modal2 content
  window.addEventListener("click", (event) => {
    if (event.target === createModal) {
      createModal.style.display = "none";
    }
  });

// 🔹 Fetch all collections and populate dropdown
document.addEventListener("DOMContentLoaded", async () => {
  const dropdown = document.getElementById("kb_classificationDoc");
  dropdown.innerHTML = `<option>Loading...</option>`;

  try {
    const res = await fetch("http://209.38.165.2:8093/collections");
    const data = await res.json();
    const collections = data.collections || [];
    dropdown.innerHTML = "";

    if (collections.length === 0) {
      dropdown.innerHTML = `<option>No classification found</option>`;
      return;
    }

    collections.forEach(c => {
      const opt = document.createElement("option");
      opt.value = c.name;
      opt.textContent = c.name;
      dropdown.appendChild(opt);
    });

  } catch (err) {
    console.error("❌ Error loading collections:", err);
    dropdown.innerHTML = `<option>Error loading collections</option>`;
  }
});

// 🔹 Handle SVG click → open modal2 + load collection details
document.getElementById("editCollectionBtn").addEventListener("click", async () => {
  const selected = document.getElementById("kb_classificationDoc").value;
  if (!selected) {
    alert("Please select a collection first!");
    return;
  }

  const modal2 = document.getElementById("collectionModal");
  const collectionNameInput = document.getElementById("collectionName");
  const newCollectionNameInput = document.getElementById("newCollectionName");

  // Set current selected name in modal2
  collectionNameInput.value = selected;
  newCollectionNameInput.value = "";

  // Show modal2
  modal2.style.display = "block";

  // Fetch collection details
  try {
    const res = await fetch(`http://209.38.165.2:8093/collections/${selected}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const details = await res.json();
    console.log("✅ Collection details:", details);
  } catch (err) {
    console.error("❌ Failed to fetch collection details:", err);
  }
});

// 🔹 Handle Save (PUT request)
document.getElementById("updateCollectionBtn").addEventListener("click", async () => {
  const oldName = document.getElementById("collectionName").value;
  const newName = document.getElementById("newCollectionName").value.trim();
  if (!newName) return alert("Please enter a new name.");

  try {
    const res = await fetch(`http://209.38.165.2:8093/collections/${oldName}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ new_category: newName })
    });

    if (!res.ok) throw new Error(`HTTP ${res.status}`);

    alert("✅ Collection updated successfully!");
    document.getElementById("collectionModal").style.display = "none";

    // Reload dropdown after update
    location.reload();

  } catch (err) {
    console.error("❌ Failed to update collection:", err);
    alert("Error updating collection.");
  }
});

// 🔹 Close modal2
document.querySelector("#collectionModal .close").addEventListener("click", () => {
  document.getElementById("collectionModal").style.display = "none";
});

const modal2 = document.getElementById('createModal');
const openModalBtn = document.getElementById('openModalBtn');
const saveBtn = document.getElementById('saveBtn');

// Open modal2 on SVG click
openModalBtn.addEventListener('click', () => {
  modal2.style.display = 'block';
});

// Close modal2 when clicking outside
window.addEventListener('click', (e) => {
  if (e.target === modal2) modal2.style.display = 'none';
});

// Handle Save button click
saveBtn.addEventListener('click', async () => {
  const category = document.getElementById('categoryInput').value.trim();
  if (!category) {
    alert('Please enter a category name.');
    return;
  }

  const apiUrl = "http://209.38.165.2:8093/collections";  // Must be HTTPS if site is HTTPS
  const data = { category };

  try {
    const response = await fetch(apiUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data)
    });

    if (response.ok) {
      const result = await response.json();
      alert("✅ Collection created successfully!");
      console.log("Response:", result);
      location.reload();
      modal2.style.display = 'none';
      document.getElementById('categoryInput').value = '';
      location.reload();
    } else {
      alert("❌ Failed to create collection. Status: " + response.status);
    }
  } catch (error) {
    console.error("🚨 Request failed:", error);
    alert("Error connecting to the API. Check console for details.");
  }
});
document.addEventListener("DOMContentLoaded", async () => {
    const dropdown = document.getElementById("kb_classificationDoc");
    dropdown.innerHTML = `<option>Loading...</option>`;

    try {
        const response = await fetch("http://209.38.165.2:8093/collections", {
            method: "GET",
            headers: {
                "Content-Type": "application/json"
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }

        const data = await response.json();
        const collections = data.collections || [];

        dropdown.innerHTML = "";

        if (collections.length === 0) {
            dropdown.innerHTML = `<option value="">No classification found</option>`;
            return;
        }

        collections.forEach((collection) => {
            // 🚫 Skip the "question_log" collection
            if (collection.name === "question_log") return;

            const option = document.createElement("option");
            option.value = collection.name;
            option.textContent = collection.name;
            dropdown.appendChild(option);
        });

    } catch (err) {
        console.error("❌ Failed to fetch collections:", err);
        dropdown.innerHTML = `<option value="">Error loading collections</option>`;
    }
});


    </script>