Nessun oggetto della modifica
Nessun oggetto della modifica
 
(24 versioni intermedie di uno stesso utente non sono mostrate)
Riga 1: Riga 1:
// ============================================
// ============================================
// 🔧 CommonDashboard.js – versione GPT-4o + Lettura file reale
// 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti
// ============================================
// ============================================


// ============================================
// 📘 INTRODUZIONE
// 📘 INTRODUZIONE
// ============================================
window.toggleDashboardBox = function (id) {
window.toggleDashboardBox = function (id) {
   const box = document.getElementById(id);
   const box = document.getElementById(id);
Riga 14: Riga 12:
};
};


// ============================================
// ⚙️ CONNESSIONE API
// ⚙️ CONNESSIONE API
// ============================================
window.testAPIConnection = async function () {
window.testAPIConnection = async function () {
   const key = document.getElementById('api-key').value.trim();
   const key = document.getElementById('api-key').value.trim();
Riga 49: Riga 44:


     if (data.choices && data.choices.length > 0) {
     if (data.choices && data.choices.length > 0) {
       output.innerText = "✅ Risposta:\n" + data.choices[0].message.content;
       output.innerText = "✅ Risposta:" + data.choices[0].message.content;
       logActivity(`✅ Risposta ricevuta – Modello: <strong>${model}</strong>`);
       logActivity(`✅ Risposta ricevuta – Modello: <strong>${model}</strong>`);
     } else if (data.error) {
     } else if (data.error) {
Riga 63: Riga 58:
};
};


 
// 📊 SEZIONE: STATO PROGETTI
// ============================================
// 📊 STATO PROGETTI
// ============================================


window.addNewProject = function () {
window.addNewProject = function () {
   const title = document.getElementById("newProjectTitle").value.trim();
   const title = document.getElementById("newProjectTitle").value.trim();
   const notes = document.getElementById("newProjectNotes").value.trim();
   const notes = document.getElementById("newProjectNotes").value.trim();
   if (!title) return;
   if (!title) {
    alert("Inserisci un titolo per il progetto!");
    return;
  }


   const table = document.getElementById("projectRows");
   const table = document.getElementById("projectRows");
   const newRow = document.createElement("tr");
   const newRow = document.createElement("tr");
  // 🔹 Genera contenuto HTML per la nuova riga
   newRow.innerHTML = `
   newRow.innerHTML = `
     <td style="padding:0.5rem; border:1px solid #ccc;">${title}</td>
     <td style="padding:0.5rem; border:1px solid #ccc;">${title}</td>
Riga 80: Riga 77:
     <td style="padding:0.5rem; border:1px solid #ccc;">${new Date().toLocaleDateString("it-IT")}</td>
     <td style="padding:0.5rem; border:1px solid #ccc;">${new Date().toLocaleDateString("it-IT")}</td>
     <td style="padding:0.5rem; border:1px solid #ccc;">${notes || '–'}</td>
     <td style="padding:0.5rem; border:1px solid #ccc;">${notes || '–'}</td>
    <td style="padding:0.5rem; border:1px solid #ccc;">
      <button onclick="analyzeProjectWithGPT('${title}', \`${notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
    </td>
   `;
   `;
  // 🔹 Inserisce la nuova riga nella tabella HTML
   table.appendChild(newRow);
   table.appendChild(newRow);
  // 🔹 Chiude il dialog di inserimento
   window.closeProjectDialog();
   window.closeProjectDialog();
  // 🔹 Log attività locale
   logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);
   logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);
  // 💾 SEZIONE: Invio al server per salvataggio JSON
  const payload = {
    title: title,
    notes: notes,
    date: new Date().toLocaleDateString("it-IT")
  };
  fetch("/dashboard/api/write_project.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload)
  })
    .then((res) => res.json())
    .then((data) => {
      if (!data.success) {
        alert("⚠️ Errore salvataggio su server: " + data.error);
        logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
      } else {
        logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`);
      }
    })
    .catch((err) => {
      alert("❌ Errore rete salvataggio progetto.");
      console.error("Errore invio progetto:", err);
      logActivity("❌ Errore rete durante salvataggio progetto.");
    });
};
};


window.openProjectDialog = function () {
window.openProjectDialog = function () {
Riga 94: Riga 128:
};
};


// ============================================
// 📥 Carica prompt.txt
// 📥 Carica prompt.txt
// ============================================
window.loadPrompt = function () {
window.loadPrompt = function () {
   fetch('/mnt/data/masticationpedia-openai/prompt.txt')
   fetch('/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt')
     .then(response => {
     .then(response => {
       if (!response.ok) throw new Error('Errore nel caricamento del file');
       if (!response.ok) throw new Error('Errore nel caricamento del file');
       return response.text();
       return response.json();
     })
     })
     .then(text => {
     .then(data => {
       document.getElementById("promptArea").value = text;
       if (data.status === "ok") {
      logActivity("📥 Caricato prompt.txt nella textarea.");
        document.getElementById("promptArea").value = data.content;
        logActivity("📥 Caricato prompt.txt nella textarea.");
      } else {
        alert("Errore: " + data.error);
        logActivity("❌ Errore nel caricamento: " + data.error);
      }
     })
     })
     .catch(error => {
     .catch(error => {
Riga 114: Riga 150:
};
};


// ============================================
// 💾 Salva prompt.txt
// 💾 Salva prompt.txt
// ============================================
window.savePrompt = function () {
window.savePrompt = function () {
   const content = document.getElementById("promptArea").value;
   const content = document.getElementById("promptArea").value;
   fetch('/mnt/data/masticationpedia-openai/write_prompt.php', {
   fetch('/dashboard/api/write_prompt.php', {
     method: 'POST',
     method: 'POST',
     headers: {
     headers: {
Riga 141: Riga 174:
};
};


// ============================================
// 💾 Salva RISPOSTA GPT IN FILE
// 💾 Salva RISPOSTA GPT IN FILE
// ============================================
window.salvaFileDaTextarea = function () {
window.salvaFileDaTextarea = function () {
   const content = document.getElementById("gpt-response-area").value;
   const content = document.getElementById("gpt-response-area").value;
Riga 170: Riga 200:
     .then(response => response.json())
     .then(response => response.json())
     .then(data => {
     .then(data => {
       console.log("✅ File salvato:", data);
       if (data.status === "ok") {
      logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
        document.getElementById("gpt-response-area").value = data.content;
      alert("File salvato con successo in:\n" + data.path);
        logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
        alert("File salvato con successo in:" + data.path);
      } else {
        alert("Errore: " + data.error);
        logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
      }
     })
     })
     .catch(error => {
     .catch(error => {
Riga 180: Riga 215:
};
};


// ============================================
// 📂 Carica File Salvato in Textarea GPT
// 📂 Carica File Salvato in Textarea GPT  
// ============================================
 
window.caricaFileGPT = function () {
window.caricaFileGPT = function () {
   const filename = document.getElementById("gpt-filename").value.trim();
   const filename = document.getElementById("gpt-filename").value.trim();
Riga 194: Riga 226:
   }
   }


   const url = `/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`;
   fetch(`/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`)
  console.log("📡 Chiamata fetch:", url); // 🐞 LOG DI DEBUG
 
  fetch(url)
     .then(res => res.json())
     .then(res => res.json())
     .then(data => {
     .then(data => {
      console.log("📬 Risposta fetch:", data); // 🐞 LOG DI DEBUG
       if (data.status === "ok") {
       if (data.status === "ok") {
         document.getElementById("gpt-response-area").value = data.content;
         document.getElementById("gpt-response-area").value = data.content;
Riga 206: Riga 234:
       } else {
       } else {
         alert("Errore: " + data.error);
         alert("Errore: " + data.error);
         logActivity(`❌ Errore nel caricamento di ${filename}.`);
         logActivity(`❌ Errore nel caricamento di ${filename}: ${data.error}`);
       }
       }
     })
     })
     .catch(err => {
     .catch(err => {
       console.error("Errore durante il caricamento:", err); // 🐞 LOG DI DEBUG
       console.error("Errore:", err);
       alert("Errore durante il caricamento del file.");
       alert("Errore durante il caricamento del file.");
     });
     });
Riga 216: Riga 244:




// 🚀 ========= Carica automaticamente tutti i progetti salvati ================
window.loadAllProjects = function () {
  fetch('/dashboard/api/read_all_projects.php')
    .then(response => response.json())
    .then(data => {
      if (!Array.isArray(data)) {
        logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
        return;
      }
      const table = document.getElementById("projectRows");
      table.innerHTML = ''; // Pulisce la tabella prima di caricare
      data.forEach(project => {
        const row = document.createElement("tr");
        row.innerHTML = `
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.title}</td>
          <td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.date}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.notes || '–'}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">
            <button onclick="analyzeProjectWithGPT('${project.title}', \`${project.notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
          </td>
        `;
        table.appendChild(row);
        logActivity(`📌 Caricato progetto: <strong>${project.title}</strong>`);
      });
    })
    .catch(err => {
      console.error("Errore nel caricamento progetti:", err);
      alert("Errore nel caricamento dei progetti.");
      logActivity("❌ Errore nel caricamento progetti.");
    });
};


/* window.caricaFileGPT = function () {
  const filename = document.getElementById("gpt-filename").value.trim();
  const subfolder = document.getElementById("gpt-subfolder").value;
  const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";


   if (!filename) {
// ✅ Al caricamento pagina: esegue tutte le funzioni necessarie
     alert("Inserisci il nome del file da caricare.");
window.addEventListener("load", function () {
     return;
  loadAllProjects();
    // ✅ Recupera API Key da localStorage (se esiste)
  const savedKey = localStorage.getItem("openai_api_key");
   if (savedKey) {
     document.getElementById("apiKeyInput").value = savedKey;
     logActivity("🔐 API Key caricata dal browser.");
   }
   }


   fetch(`/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`)
   // ✅ Salva la chiave ogni volta che viene modificata
  document.getElementById("apiKeyInput").addEventListener("input", function () {
    localStorage.setItem("openai_api_key", this.value.trim());
    logActivity("💾 API Key aggiornata nel browser.");
  });
 
});
 
// 🔹 2. ========== AGGIUNGI FUNZIONE GPT =============================
/*window.analyzeProjectWithGPT = function (title, notes) {
  const prompt = `📌 Analizza il progetto seguente:\nTitolo: ${title}\nNote: ${notes}\n\nFornisci una valutazione sintetica e suggerimenti operativi.`;
 
  fetch("/dashboard/api/openai_project_gpt.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ prompt: prompt })
  })
     .then(res => res.json())
     .then(res => res.json())
     .then(data => {
     .then(data => {
       if (data.status === "ok") {
       if (data.status === "ok") {
         document.getElementById("gpt-response-area").value = data.content;
         document.getElementById("gpt-response-area").value = data.result;
         logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`);
         logActivity(`🤖 GPT elaborato per progetto: <strong>${title}</strong>`);
       } else {
       } else {
         alert("Errore: " + data.error);
         alert("Errore GPT: " + data.error);
         logActivity(`❌ Errore nel caricamento di ${filename}.`);
         logActivity(`❌ Errore GPT: ${data.error}`);
       }
       }
     })
     })
     .catch(err => {
     .catch(err => {
       console.error("Errore:", err);
       console.error("Errore GPT:", err);
       alert("Errore durante il caricamento del file.");
       alert("Errore durante la richiesta a GPT.");
     });
     });
};
};
*/
*/


// 🎯 Analizza progetto con GPT
window.analyzeProjectWithGPT = async function (title, notes) {
  console.log("🚀 Analisi GPT avviata per:", title, "con note:", notes);
  try {
    const model = "gpt-4o-2024-05-13";
    const apiKey = document.getElementById("api-key").value.trim();
    console.log("🔑 Chiave API letta:", apiKey ? "(presente)" : "(vuota)");
    if (!apiKey) {
      alert("❌ Inserisci prima una API key valida!");
      return;
    }
   
    const prompt = `Titolo: ${title}\nNote: ${notes}`;
    console.log("📌 Prompt costruito:", prompt);
    const response = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`
      },
      body: JSON.stringify({ model, messages: [{ role: "user", content: prompt }] })
    });
    console.log("📡 Chiamata fetch completata. HTTP status:", response.status);


// ============================================
    const result = await response.json();
// 📝 LOG ATTIVITÀ?
    console.log("📥 Risposta JSON da OpenAI:", result);
// ============================================


window.logActivity = function (message) {
    if (result.error) {
  const log = document.getElementById("activityLog");
      throw new Error(result.error.message);
  const time = new Date().toLocaleTimeString("it-IT");
    }
  const entry = document.createElement("div");
  entry.innerHTML = `<span style="color:gray;">[${time}]</span> ${message}`;
  log.prepend(entry);
};


    const reply = result.choices?.[0]?.message?.content;
    console.log("✅ Contenuto risposta GPT:", reply);
    document.getElementById("response").value = reply;


  } catch (err) {
    console.error("❌ Errore completo GPT:", err);
    alert("Errore durante la richiesta a GPT:\n" + err.message);
  }
};
// 🧠 Toggle per mostrare/nascondere istruzioni sysadmin
window.toggleSysNote = function () {
  const noteBox = document.getElementById("sysNote");
  if (noteBox) {
    noteBox.style.display = (noteBox.style.display === "none") ? "block" : "none";
  }
};






// ============================================
// 🧪 STRUMENTI DI TEST
// ============================================
// (Da completare nel prossimo step)




// ============================================
// 🧾 REGISTRO ATTIVITÀ
// 🧾 REGISTRO ATTIVITÀ
// ============================================
window.logActivity = function (messaggio) {
window.logActivity = function (messaggio) {
   const contenitore = document.getElementById("activityLogContent");
   const contenitore = document.getElementById("activityLogContent") || document.getElementById("activityLog");
   if (!contenitore) return;
   if (!contenitore) return;


   const ora = new Date().toLocaleTimeString("it-IT");
   const ora = new Date().toLocaleTimeString("it-IT");
   const paragrafo = document.createElement("p");
   const entry = document.createElement("div");
   paragrafo.innerHTML = `<strong>[${ora}]</strong> ${messaggio}`;
   entry.innerHTML = `<span style="color:gray;">[${ora}]</span> ${messaggio}`;
   contenitore.appendChild(paragrafo);
   contenitore.prepend(entry);
  contenitore.scrollTop = contenitore.scrollHeight;
};
};


window.clearActivityLog = function () {
window.clearActivityLog = function () {
   const contenitore = document.getElementById("activityLogContent");
   const contenitore = document.getElementById("activityLogContent");
   contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
   if (contenitore) {
  logActivity("🧹 Log svuotato manualmente.");
    contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
    logActivity("🧹 Log svuotato manualmente.");
  }
};
};
// ============================================
// 🧠 CARICA IN OPENAI
// ============================================
// (Da completare nel prossimo step)

Versione attuale delle 17:29, 3 ago 2025

// ============================================
// 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti
// ============================================

// 📘 INTRODUZIONE
window.toggleDashboardBox = function (id) {
  const box = document.getElementById(id);
  if (box) {
    box.style.display = box.style.display === "block" ? "none" : "block";
  }
};

// ⚙️ CONNESSIONE API
window.testAPIConnection = async function () {
  const key = document.getElementById('api-key').value.trim();
  const prompt = document.getElementById('test-prompt').value;
  const output = document.getElementById('api-result');
  const model = "gpt-4o-2024-05-13";

  if (!key || !prompt) {
    output.innerText = '⚠️ Inserisci una chiave valida e un prompt.';
    return;
  }

  output.innerText = '⏳ Attendere risposta da OpenAI...';
  logActivity(`🚀 Test API avviato – Modello: <strong>${model}</strong>`);

  try {
    const response = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + key
      },
      body: JSON.stringify({
        model: model,
        messages: [{ role: "user", content: prompt }],
        temperature: 0.7
      })
    });

    const data = await response.json();

    if (data.choices && data.choices.length > 0) {
      output.innerText = "✅ Risposta:" + data.choices[0].message.content;
      logActivity(`✅ Risposta ricevuta – Modello: <strong>${model}</strong>`);
    } else if (data.error) {
      output.innerText = "❌ Errore: " + data.error.message;
      logActivity(`❌ Errore API: ${data.error.message}`);
    } else {
      output.innerText = "❌ Nessuna risposta ricevuta.";
    }
  } catch (e) {
    output.innerText = "🚫 Errore di rete o sintassi: " + e.message;
    logActivity(`❌ Errore di connessione: ${e.message}`);
  }
};

// 📊 SEZIONE: STATO PROGETTI – 

window.addNewProject = function () {
  const title = document.getElementById("newProjectTitle").value.trim();
  const notes = document.getElementById("newProjectNotes").value.trim();
  if (!title) {
    alert("Inserisci un titolo per il progetto!");
    return;
  }

  const table = document.getElementById("projectRows");
  const newRow = document.createElement("tr");

  // 🔹 Genera contenuto HTML per la nuova riga
  newRow.innerHTML = `
    <td style="padding:0.5rem; border:1px solid #ccc;">${title}</td>
    <td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td>
    <td style="padding:0.5rem; border:1px solid #ccc;">${new Date().toLocaleDateString("it-IT")}</td>
    <td style="padding:0.5rem; border:1px solid #ccc;">${notes || '–'}</td>
    <td style="padding:0.5rem; border:1px solid #ccc;">
      <button onclick="analyzeProjectWithGPT('${title}', \`${notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
    </td>
  `;

  // 🔹 Inserisce la nuova riga nella tabella HTML
  table.appendChild(newRow);

  // 🔹 Chiude il dialog di inserimento
  window.closeProjectDialog();

  // 🔹 Log attività locale
  logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);

  // 💾 SEZIONE: Invio al server per salvataggio JSON
  const payload = {
    title: title,
    notes: notes,
    date: new Date().toLocaleDateString("it-IT")
  };

  fetch("/dashboard/api/write_project.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload)
  })
    .then((res) => res.json())
    .then((data) => {
      if (!data.success) {
        alert("⚠️ Errore salvataggio su server: " + data.error);
        logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
      } else {
        logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`);
      }
    })
    .catch((err) => {
      alert("❌ Errore rete salvataggio progetto.");
      console.error("Errore invio progetto:", err);
      logActivity("❌ Errore rete durante salvataggio progetto.");
    });
};


window.openProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "block";
};

window.closeProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "none";
};

// 📥 Carica prompt.txt
window.loadPrompt = function () {
  fetch('/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt')
    .then(response => {
      if (!response.ok) throw new Error('Errore nel caricamento del file');
      return response.json();
    })
    .then(data => {
      if (data.status === "ok") {
        document.getElementById("promptArea").value = data.content;
        logActivity("📥 Caricato prompt.txt nella textarea.");
      } else {
        alert("Errore: " + data.error);
        logActivity("❌ Errore nel caricamento: " + data.error);
      }
    })
    .catch(error => {
      alert("Errore nel caricamento: " + error);
      logActivity("❌ Errore nel caricamento di prompt.txt.");
    });
};

// 💾 Salva prompt.txt
window.savePrompt = function () {
  const content = document.getElementById("promptArea").value;
  fetch('/dashboard/api/write_prompt.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: 'text=' + encodeURIComponent(content)
  })
    .then(response => {
      if (!response.ok) throw new Error('Errore nel salvataggio');
      return response.text();
    })
    .then(msg => {
      logActivity("💾 Salvato prompt.txt dal form.");
      alert("Prompt salvato con successo.");
    })
    .catch(error => {
      alert("Errore nel salvataggio: " + error);
      logActivity("❌ Errore nel salvataggio di prompt.txt.");
    });
};

// 💾 Salva RISPOSTA GPT IN FILE
window.salvaFileDaTextarea = function () {
  const content = document.getElementById("gpt-response-area").value;
  const filename = document.getElementById("gpt-filename").value.trim();
  const subfolder = document.getElementById("gpt-subfolder").value;
  const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";

  if (!filename || !content) {
    alert("Inserisci un nome file e assicurati che il contenuto non sia vuoto.");
    return;
  }

  fetch('/dashboard/api/write_file.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      projectName: project,
      subfolder: subfolder,
      filename: filename,
      content: content
    })
  })
    .then(response => response.json())
    .then(data => {
      if (data.status === "ok") {
        document.getElementById("gpt-response-area").value = data.content;
        logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
        alert("File salvato con successo in:" + data.path);
      } else {
        alert("Errore: " + data.error);
        logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
      }
    })
    .catch(error => {
      console.error("❌ Errore:", error);
      alert("Errore durante il salvataggio.");
    });
};

// 📂 Carica File Salvato in Textarea GPT
window.caricaFileGPT = function () {
  const filename = document.getElementById("gpt-filename").value.trim();
  const subfolder = document.getElementById("gpt-subfolder").value;
  const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";

  if (!filename) {
    alert("Inserisci il nome del file da caricare.");
    return;
  }

  fetch(`/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`)
    .then(res => res.json())
    .then(data => {
      if (data.status === "ok") {
        document.getElementById("gpt-response-area").value = data.content;
        logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`);
      } else {
        alert("Errore: " + data.error);
        logActivity(`❌ Errore nel caricamento di ${filename}: ${data.error}`);
      }
    })
    .catch(err => {
      console.error("Errore:", err);
      alert("Errore durante il caricamento del file.");
    });
};


// 🚀 ========= Carica automaticamente tutti i progetti salvati ================
window.loadAllProjects = function () {
  fetch('/dashboard/api/read_all_projects.php')
    .then(response => response.json())
    .then(data => {
      if (!Array.isArray(data)) {
        logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
        return;
      }

      const table = document.getElementById("projectRows");
      table.innerHTML = ''; // Pulisce la tabella prima di caricare

      data.forEach(project => {
        const row = document.createElement("tr");
        row.innerHTML = `
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.title}</td>
          <td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.date}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.notes || '–'}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">
            <button onclick="analyzeProjectWithGPT('${project.title}', \`${project.notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
          </td>
        `;
        table.appendChild(row);
        logActivity(`📌 Caricato progetto: <strong>${project.title}</strong>`);
      });
    })
    .catch(err => {
      console.error("Errore nel caricamento progetti:", err);
      alert("Errore nel caricamento dei progetti.");
      logActivity("❌ Errore nel caricamento progetti.");
    });
};


// ✅ Al caricamento pagina: esegue tutte le funzioni necessarie
window.addEventListener("load", function () {
  loadAllProjects();
    // ✅ Recupera API Key da localStorage (se esiste)
  const savedKey = localStorage.getItem("openai_api_key");
  if (savedKey) {
    document.getElementById("apiKeyInput").value = savedKey;
    logActivity("🔐 API Key caricata dal browser.");
  }

  // ✅ Salva la chiave ogni volta che viene modificata
  document.getElementById("apiKeyInput").addEventListener("input", function () {
    localStorage.setItem("openai_api_key", this.value.trim());
    logActivity("💾 API Key aggiornata nel browser.");
  });

});

// 🔹 2. ========== AGGIUNGI FUNZIONE GPT =============================
/*window.analyzeProjectWithGPT = function (title, notes) {
  const prompt = `📌 Analizza il progetto seguente:\nTitolo: ${title}\nNote: ${notes}\n\nFornisci una valutazione sintetica e suggerimenti operativi.`;

  fetch("/dashboard/api/openai_project_gpt.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ prompt: prompt })
  })
    .then(res => res.json())
    .then(data => {
      if (data.status === "ok") {
        document.getElementById("gpt-response-area").value = data.result;
        logActivity(`🤖 GPT elaborato per progetto: <strong>${title}</strong>`);
      } else {
        alert("Errore GPT: " + data.error);
        logActivity(`❌ Errore GPT: ${data.error}`);
      }
    })
    .catch(err => {
      console.error("Errore GPT:", err);
      alert("Errore durante la richiesta a GPT.");
    });
};
*/

// 🎯 Analizza progetto con GPT
window.analyzeProjectWithGPT = async function (title, notes) {
  console.log("🚀 Analisi GPT avviata per:", title, "con note:", notes);

  try {
    const model = "gpt-4o-2024-05-13";
    const apiKey = document.getElementById("api-key").value.trim();
    console.log("🔑 Chiave API letta:", apiKey ? "(presente)" : "(vuota)");

    if (!apiKey) {
      alert("❌ Inserisci prima una API key valida!");
      return;
    }
    
    const prompt = `Titolo: ${title}\nNote: ${notes}`;
    console.log("📌 Prompt costruito:", prompt);

    const response = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`
      },
      body: JSON.stringify({ model, messages: [{ role: "user", content: prompt }] })
    });
    console.log("📡 Chiamata fetch completata. HTTP status:", response.status);

    const result = await response.json();
    console.log("📥 Risposta JSON da OpenAI:", result);

    if (result.error) {
      throw new Error(result.error.message);
    }

    const reply = result.choices?.[0]?.message?.content;
    console.log("✅ Contenuto risposta GPT:", reply);
    document.getElementById("response").value = reply;

  } catch (err) {
    console.error("❌ Errore completo GPT:", err);
    alert("Errore durante la richiesta a GPT:\n" + err.message);
  }
};
// 🧠 Toggle per mostrare/nascondere istruzioni sysadmin
window.toggleSysNote = function () {
  const noteBox = document.getElementById("sysNote");
  if (noteBox) {
    noteBox.style.display = (noteBox.style.display === "none") ? "block" : "none";
  }
};





// 🧾 REGISTRO ATTIVITÀ
window.logActivity = function (messaggio) {
  const contenitore = document.getElementById("activityLogContent") || document.getElementById("activityLog");
  if (!contenitore) return;

  const ora = new Date().toLocaleTimeString("it-IT");
  const entry = document.createElement("div");
  entry.innerHTML = `<span style="color:gray;">[${ora}]</span> ${messaggio}`;
  contenitore.prepend(entry);
};

window.clearActivityLog = function () {
  const contenitore = document.getElementById("activityLogContent");
  if (contenitore) {
    contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
    logActivity("🧹 Log svuotato manualmente.");
  }
};