Nessun oggetto della modifica
Nessun oggetto della modifica
Riga 1: Riga 1:
// ============================================
// ============================================
// 🔧 CommonDashboard.js – SOLO proxy server-side (no API key nel browser)
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// Ultimo aggiornamento: 2025-08-18
// ============================================
// ============================================


// ─────────────────────────────────────────────────────────────────────────────
// 📘 INTRODUZIONE
// UTILITÀ UI
// ─────────────────────────────────────────────────────────────────────────────
window.toggleDashboardBox = function (id) {
window.toggleDashboardBox = function (id) {
   const box = document.getElementById(id);
   const box = document.getElementById(id);
Riga 12: Riga 9:
};
};


window.logActivity = function (msg) {
// ⚙️ CONNESSIONE API (via proxy server)
  const box = document.getElementById("activityLogContent") || document.getElementById("activityLog");
  if (!box) return;
  const now = new Date().toLocaleTimeString("it-IT");
  const line = document.createElement("div");
  line.innerHTML = `<span style="color:gray;">[${now}]</span> ${msg}`;
  box.prepend(line);
};
 
window.clearActivityLog = function () {
  const box = document.getElementById("activityLogContent");
  if (box) {
    box.innerHTML = "<em>Registro svuotato.</em><br>";
    logActivity("✔ Log svuotato manualmente.");
  }
};
 
// ─────────────────────────────────────────────────────────────────────────────
// ⚙️ CONNESSIONE API (via proxy PHP server-side)
// ─────────────────────────────────────────────────────────────────────────────
// Campi previsti nella pagina:
//  - #test-prompt  (textarea / input con il prompt di test)
//  - #api-result  (div / textarea output)
//  - #model-select (opzionale: select con id; se assente usa il default lato server)
//  - #api-key      (eventuale campo legacy: viene nascosto)
window.testAPIConnection = async function () {
window.testAPIConnection = async function () {
   const promptEl = document.getElementById('test-prompt');
   const prompt = (document.getElementById("test-prompt")?.value || "").trim();
   const outputEl = document.getElementById('api-result');
   const output = document.getElementById("api-result");
   const modelEl  = document.getElementById('model-select');
   const model =
 
    document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
  const prompt = (promptEl?.value || '').trim();
  const model  = (modelEl?.value || ''); // opzionale: se vuoto userà il default del proxy


   if (!prompt) {
   if (!prompt) {
     outputEl && (outputEl.innerText = '⚠️ Inserisci un prompt.');
     output.innerText = "⚠️ Inserisci un prompt di test.";
     return;
     return;
   }
   }


   outputEl && (outputEl.innerText = 'Invio al server...');
   output.innerText = "Contatto il proxy sul server...";
   logActivity(`🚀 Test API via proxy – Modello: <strong>${model || '(default server)'}</strong>`);
   logActivity(`🚀 Test API via proxy – Modello: <strong>${model}</strong>`);


   try {
   try {
     const res = await fetch('/dashboard/api/openai_project_gpt.php', {
     const res = await fetch("/dashboard/api/openai_project_gpt.php", {
       method: 'POST',
       method: "POST",
       headers: { 'Content-Type': 'application/json' },
       headers: { "Content-Type": "application/json" },
      credentials: "include",
       body: JSON.stringify({ prompt, model })
       body: JSON.stringify({ prompt, model })
     });
     });
     const data = await res.json();
     const data = await res.json();


     if (data.status === 'ok') {
     if (data.status === "ok" && data.result) {
      const text = data.result || '(risposta vuota)';
       output.innerText = "Risposta: " + data.result;
       outputEl && (outputEl.innerText = '' + text);
       logActivity(`Proxy OK – Modello: <strong>${model}</strong>`);
       logActivity('Risposta ricevuta dal proxy.');
     } else {
     } else {
       outputEl && (outputEl.innerText = '❌ Errore: ' + (data.error || 'sconosciuto'));
       output.innerText = "❌ Errore: " + (data.error || "Risposta vuota");
       logActivity(`❌ Errore proxy: ${data.error || 'sconosciuto'}`);
       logActivity(`❌ Errore proxy: ${data.error || "risposta vuota"}`);
     }
     }
   } catch (e) {
   } catch (e) {
     outputEl && (outputEl.innerText = '🚫 Errore di rete: ' + e.message);
     output.innerText = "🚫 Errore di rete: " + e.message;
     logActivity(`❌ Errore rete: ${e.message}`);
     logActivity(`❌ Errore rete: ${e.message}`);
   }
   }
};
};


// ─────────────────────────────────────────────────────────────────────────────
// 🎯 Analizza progetto con GPT (sempre via proxy)
// 📊 STATO PROGETTI aggiungi / elimina / carica elenco
window.analyzeProjectWithGPT = async function (title, notes) {
// ─────────────────────────────────────────────────────────────────────────────
  try {
    const model =
      document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
    const prompt = `📌 Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}\n\nFornisci valutazione sintetica e suggerimenti operativi.`;
    logActivity(`🤖 Analisi GPT via proxy – <strong>${title}</strong>`);
 
    const res = await fetch("/dashboard/api/openai_project_gpt.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ prompt, model })
    });
 
    const data = await res.json();
    if (data.status === "ok" && data.result) {
      document.getElementById("response").value = data.result;
      logActivity(`✅ Analisi completata <strong>${title}</strong>`);
    } else {
      alert("Errore GPT: " + (data.error || "Risposta vuota"));
      logActivity(`❌ Errore GPT: ${data.error || "risposta vuota"}`);
    }
  } catch (err) {
    console.error("❌ Errore completo GPT:", err);
    alert("Errore durante la richiesta a GPT:\n" + err.message);
    logActivity(`❌ Errore richiesta GPT: ${err.message}`);
  }
};
 
// 📊 SEZIONE: 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) {
   if (!title) {
     alert("Inserisci un titolo per il progetto!");
     alert("Inserisci un titolo per il progetto!");
Riga 92: Riga 92:
     <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; 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;">${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;">
     <td style="padding:0.5rem; border:1px solid #ccc;">
       <button onclick="analyzeProjectWithGPT('${title}', \`${notes || ''}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
       <button onclick="analyzeProjectWithGPT('${title}', \`${notes || ""}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
      <button onclick="deleteProject('${title}')" style="padding: 0.3rem 0.6rem; margin-left:5px; color:red;">🗑️</button>
     </td>
     </td>
   `;
   `;
   table?.appendChild(newRow);
   table.appendChild(newRow);
   window.closeProjectDialog();
   window.closeProjectDialog();
   logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes || '–'}`);
   logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);


  // Crea cartella
  fetch("/dashboard/api/create_project_dir.php", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: "projectName=" + encodeURIComponent(title)
  })
  .then(res => res.json())
  .then(data => {
    if (data.success) logActivity(`📂 Cartella progetto creata: <strong>${title}</strong>`);
    else logActivity(`⚠️ Errore creazione cartella: ${data.error}`);
  })
  .catch(() => logActivity("❌ Errore rete creazione cartella progetto."));
  // Salva metadati progetto
   const payload = { title, notes, date: new Date().toLocaleDateString("it-IT") };
   const payload = { title, notes, date: new Date().toLocaleDateString("it-IT") };
   fetch("/dashboard/api/write_project.php", {
   fetch("/dashboard/api/write_project.php", {
     method: "POST",
     method: "POST",
     headers: { "Content-Type": "application/json" },
     headers: { "Content-Type": "application/json" },
     body: JSON.stringify(payload)
     body: JSON.stringify(payload),
    credentials: "include"
   })
   })
  .then(res => res.json())
    .then((r) => r.json())
  .then(data => {
    .then((data) => {
    if (!data.success) logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
      if (!data.success) {
    else logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`);
        alert("⚠️ Errore salvataggio su server: " + data.error);
  })
        logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
  .catch(() => logActivity("❌ Errore rete durante salvataggio progetto."));
      } else {
};
         logActivity(`Progetto salvato su server: <strong>${title}</strong>`);
 
window.deleteProject = function (title) {
  logActivity(`🧪 deleteProject() invocata per: <strong>${title}</strong>`);
  if (!confirm(`⚠️ Sei sicuro di voler eliminare il progetto "${title}"?\nQuesta azione è irreversibile.`)) return;
 
  fetch('/dashboard/api/delete_project_dir.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'projectName=' + encodeURIComponent(title)
  })
    .then(res => res.text())
    .then(text => {
      try {
        const data = JSON.parse(text);
         if (data.success) {
          logActivity(`🗑️ Progetto eliminato: <strong>${title}</strong>`);
          alert(data.message);
          loadAllProjects();
        } else {
          alert("Errore: " + data.error);
          logActivity(`❌ Errore eliminazione progetto: ${data.error}`);
        }
      } catch {
        alert("⚠️ Risposta non JSON.");
        logActivity("❌ Risposta non JSON durante eliminazione.");
       }
       }
     })
     })
     .catch(() => {
     .catch((err) => {
       alert("Errore rete durante eliminazione.");
       alert("❌ Errore rete salvataggio progetto.");
      logActivity("❌ Errore rete durante eliminazione progetto.");
       console.error("Errore invio progetto:", err);
    });
       logActivity("❌ Errore rete durante salvataggio progetto.");
};
 
window.loadAllProjects = function () {
  fetch('/dashboard/api/read_all_projects.php')
    .then(r => r.json())
    .then(data => {
       if (!Array.isArray(data)) {
        logActivity("Errore: formato dati inatteso dalla lista progetti.");
        return;
      }
      const table = document.getElementById("projectRows");
      if (!table) return;
      table.innerHTML = '';
 
      data.forEach(p => {
        const tr = document.createElement("tr");
        tr.innerHTML = `
          <td style="padding:0.5rem; border:1px solid #ccc;">${p.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;">${p.date}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">${p.notes || '–'}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">
            <button onclick="analyzeProjectWithGPT('${p.title}', \`${p.notes || '–'}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
            <button onclick="deleteProject('${p.title}')" style="padding: 0.3rem 0.6rem; margin-left:5px; color:red;">🗑️</button>
          </td>
        `;
        table.appendChild(tr);
        logActivity(`📌 Caricato progetto: <strong>${p.title}</strong>`);
      });
    })
    .catch(() => {
      alert("Errore nel caricamento dei progetti.");
       logActivity("❌ Errore nel caricamento progetti.");
    });
};
 
// ─────────────────────────────────────────────────────────────────────────────
// 🤖 ANALISI GPT (via proxy PHP) – riusa lo stesso endpoint del test
// ─────────────────────────────────────────────────────────────────────────────
window.analyzeProjectWithGPT = async function (title, notes) {
  logActivity(`🧠 Analisi GPT avviata per: <strong>${title}</strong>`);
  const modelEl = document.getElementById('model-select');
  const model  = (modelEl?.value || '');
 
  const prompt = `Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}`;
  const outputArea = document.getElementById("response") || document.getElementById("api-result");
  const promptBox  = document.getElementById("test-prompt");
 
  if (promptBox) promptBox.value = prompt;
  if (outputArea) outputArea.value = '';
  logActivity(`✍️ Prompt pronto (model: ${model || 'default server'})`);
 
  try {
    const res = await fetch('/dashboard/api/openai_project_gpt.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt, model })
     });
     });
    const data = await res.json();
    if (data.status === 'ok') {
      const text = data.result || '(risposta vuota)';
      if (outputArea) outputArea.value = text;
      logActivity('✅ Analisi completata.');
    } else {
      const err = data.error || 'sconosciuto';
      if (outputArea) outputArea.value = '❌ ' + err;
      logActivity(`❌ Errore proxy: ${err}`);
    }
  } catch (e) {
    if (outputArea) outputArea.value = '🚫 Errore rete: ' + e.message;
    logActivity(`❌ Errore rete: ${e.message}`);
  }
  // opzionale: apri/mostra box API test
  window.toggleDashboardBox("api-test-box");
};
};


// ─────────────────────────────────────────────────────────────────────────────
window.openProjectDialog = function () {
// DIALOG nuovo progetto
   document.getElementById("newProjectDialog").style.display = "block";
// ─────────────────────────────────────────────────────────────────────────────
window.toggleNewProjectDialog = function () {
   const dialog = document.getElementById("newProjectDialog");
  if (!dialog) return;
  dialog.style.display = dialog.style.display === "block" ? "none" : "block";
};
};
window.closeProjectDialog = function () {
window.closeProjectDialog = function () {
   const dialog = document.getElementById("newProjectDialog");
   document.getElementById("newProjectDialog").style.display = "none";
  if (dialog) dialog.style.display = "none";
};
};


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


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


// ─────────────────────────────────────────────────────────────────────────────
// 💾 Salva risposta GPT in file
// SCRITTURA/LETTURA FILE GPT (salva/carica in progetto)
// ─────────────────────────────────────────────────────────────────────────────
window.salvaFileDaTextarea = function () {
window.salvaFileDaTextarea = function () {
   const content = document.getElementById("gpt-response-area")?.value || '';
   const content = document.getElementById("gpt-response-area").value;
   const filename = document.getElementById("gpt-filename")?.value.trim();
   const filename = document.getElementById("gpt-filename").value.trim();
   const subfolder = document.getElementById("gpt-subfolder")?.value || '';
   const subfolder = document.getElementById("gpt-subfolder").value;
   const project = document.getElementById("newProjectTitle")?.value.trim() || "SSO_LinkedIn";
   const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";


   if (!filename || !content) {
   if (!filename || !content) {
Riga 296: Riga 186:
   }
   }


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


// 📂 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();
   const subfolder = document.getElementById("gpt-subfolder")?.value || '';
   const subfolder = document.getElementById("gpt-subfolder").value;
   const project = document.getElementById("newProjectTitle")?.value.trim() || "SSO_LinkedIn";
   const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";


   if (!filename) {
   if (!filename) {
Riga 326: Riga 220:
   }
   }


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


// ─────────────────────────────────────────────────────────────────────────────
// 🚀 Carica automaticamente i progetti
// IMPORTA FILE (interfaccia semplificata esistente)
window.loadAllProjects = function () {
// ─────────────────────────────────────────────────────────────────────────────
  fetch("/dashboard/api/read_all_projects.php", { credentials: "include" })
function setupImportaFileSemplificato() {
    .then((r) => r.json())
  const container = document.getElementById("serverFileSimpleImportContainer");
    .then((data) => {
  if (!container) return;
      if (!Array.isArray(data)) {
  container.innerHTML = `
        logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
    <div style="border:1px solid #ccc; padding:1rem; border-radius:8px; background:#fff;">
        return;
      <h4>📁 Importa file dal server (semplificata)</h4>
      }
      <input type="text" id="sourceFilePath" placeholder="📂 Percorso assoluto file (es: /var/www/html/miofile.php)" style="width:100%; margin-bottom:0.5rem;">
      const table = document.getElementById("projectRows");
      <input type="text" id="destRelativePath" placeholder="📁 Percorso progetto (es: SSO_LinkedIn/php/)" style="width:100%; margin-bottom:0.5rem;">
      table.innerHTML = "";
      <button onclick="eseguiCopiaFileServer()">📤 Copia nel progetto</button>
      data.forEach((project) => {
     </div>
        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((e) => {
      console.error("Errore nel caricamento progetti:", e);
      alert("Errore nel caricamento dei progetti.");
      logActivity("❌ Errore nel caricamento progetti.");
    });
};


function eseguiCopiaFileServer() {
// 📂 Importa file dal server (preset directory)
   const source = document.getElementById("sourceFilePath")?.value;
window.importServerFileFromPresetDir = function () {
   const dest   = document.getElementById("destRelativePath")?.value;
   const baseDir = document.getElementById("baseDirSelect").value;
   const fileName = document.getElementById("fileNameInput").value.trim();
   const destFolder = document.getElementById("destinationPath").value.trim();


   if (!source || !dest) {
   if (!fileName || !destFolder) {
     alert("⚠️ Inserisci sia il percorso sorgente che quello di destinazione.");
     alert("Inserisci sia il nome file che la destinazione.");
     return;
     return;
   }
   }


   // NB: qui ho mantenuto il tuo endpoint; se il path era sbagliato, rimettilo a /dashboard/api/copy_file_from_path.php
   const fullSourcePath = baseDir + fileName;
   fetch("/mnt/data/masticationpedia-openai/copy_file_from_path.php", {
 
   fetch("/dashboard/api/copy_file_from_path.php", {
     method: "POST",
     method: "POST",
     headers: { "Content-Type": "application/json" },
     headers: { "Content-Type": "application/json" },
     body: JSON.stringify({ sourcePath: source, destinationPath: dest }),
    credentials: "include",
     body: JSON.stringify({ source: fullSourcePath, destination: destFolder })
   })
   })
  .then(r => r.text())
    .then((r) => r.json())
  .then(txt => { alert("✅ File copiato: " + txt); logActivity("📁 Copiato da " + source + " a " + dest); })
    .then((data) => {
  .catch(err => { alert("Errore: " + err); });
      if (data.success) {
}
        alert("✅ File copiato: " + (data.path || destFolder));
        logActivity(`📁 Copiato: <code>${fullSourcePath}</code> → <strong>${destFolder}</strong>`);
      } else {
        alert("❌ Errore: " + data.error);
        logActivity(`❌ Errore copia file: ${data.error}`);
      }
    })
    .catch((e) => {
      alert("Errore di rete: " + e.message);
      console.error(e);
    });
};


// ─────────────────────────────────────────────────────────────────────────────
// ✅ Onload
// AVVIO
// ─────────────────────────────────────────────────────────────────────────────
window.addEventListener("load", function () {
window.addEventListener("load", function () {
  // 1) carica lista progetti
   loadAllProjects();
   loadAllProjects();
});


  // 2) nascondi eventuale campo API key legacy
// 🧾 REGISTRO ATTIVITÀ
   const keyField = document.getElementById('api-key') || document.getElementById('apiKeyInput');
window.logActivity = function (messaggio) {
   if (keyField) {
   const contenitore = document.getElementById("activityLogContent") || document.getElementById("activityLog");
    const row = keyField.closest('.form-row') || keyField.parentElement;
   if (!contenitore) return;
    if (row) row.style.display = 'none';
  const ora = new Date().toLocaleTimeString("it-IT");
     else keyField.style.display = 'none';
  const entry = document.createElement("div");
     // niente più localStorage di API key
  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.");
   }
   }
 
};
  // 3) setup import file semplice (se presente)
  setupImportaFileSemplificato();
});

Versione delle 16:45, 18 ago 2025

// ============================================
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// ============================================

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

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

  if (!prompt) {
    output.innerText = "⚠️ Inserisci un prompt di test.";
    return;
  }

  output.innerText = "⏳ Contatto il proxy sul server...";
  logActivity(`🚀 Test API via proxy – Modello: <strong>${model}</strong>`);

  try {
    const res = await fetch("/dashboard/api/openai_project_gpt.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ prompt, model })
    });

    const data = await res.json();

    if (data.status === "ok" && data.result) {
      output.innerText = "✅ Risposta: " + data.result;
      logActivity(`✅ Proxy OK – Modello: <strong>${model}</strong>`);
    } else {
      output.innerText = "❌ Errore: " + (data.error || "Risposta vuota");
      logActivity(`❌ Errore proxy: ${data.error || "risposta vuota"}`);
    }
  } catch (e) {
    output.innerText = "🚫 Errore di rete: " + e.message;
    logActivity(`❌ Errore rete: ${e.message}`);
  }
};

// 🎯 Analizza progetto con GPT (sempre via proxy)
window.analyzeProjectWithGPT = async function (title, notes) {
  try {
    const model =
      document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
    const prompt = `📌 Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}\n\nFornisci valutazione sintetica e suggerimenti operativi.`;
    logActivity(`🤖 Analisi GPT via proxy – <strong>${title}</strong>`);

    const res = await fetch("/dashboard/api/openai_project_gpt.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ prompt, model })
    });

    const data = await res.json();
    if (data.status === "ok" && data.result) {
      document.getElementById("response").value = data.result;
      logActivity(`✅ Analisi completata – <strong>${title}</strong>`);
    } else {
      alert("Errore GPT: " + (data.error || "Risposta vuota"));
      logActivity(`❌ Errore GPT: ${data.error || "risposta vuota"}`);
    }
  } catch (err) {
    console.error("❌ Errore completo GPT:", err);
    alert("Errore durante la richiesta a GPT:\n" + err.message);
    logActivity(`❌ Errore richiesta GPT: ${err.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");
  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>
  `;
  table.appendChild(newRow);
  window.closeProjectDialog();
  logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);

  const payload = { title, notes, date: new Date().toLocaleDateString("it-IT") };
  fetch("/dashboard/api/write_project.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
    credentials: "include"
  })
    .then((r) => r.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/Salva prompt.txt
window.loadPrompt = function () {
  fetch("/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt", {
    credentials: "include"
  })
    .then((r) => r.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((e) => {
      alert("Errore nel caricamento: " + e);
      logActivity("❌ Errore nel caricamento di 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" },
    credentials: "include",
    body: "text=" + encodeURIComponent(content)
  })
    .then((r) => {
      if (!r.ok) throw new Error("Errore nel salvataggio");
      return r.text();
    })
    .then(() => {
      logActivity("💾 Salvato prompt.txt dal form.");
      alert("Prompt salvato con successo.");
    })
    .catch((e) => {
      alert("Errore nel salvataggio: " + e);
      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" },
    credentials: "include",
    body: JSON.stringify({ projectName: project, subfolder, filename, content })
  })
    .then((r) => r.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((e) => {
      console.error("❌ Errore:", e);
      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)}`,
    { credentials: "include" }
  )
    .then((r) => r.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((e) => {
      console.error("Errore:", e);
      alert("Errore durante il caricamento del file.");
    });
};

// 🚀 Carica automaticamente i progetti
window.loadAllProjects = function () {
  fetch("/dashboard/api/read_all_projects.php", { credentials: "include" })
    .then((r) => r.json())
    .then((data) => {
      if (!Array.isArray(data)) {
        logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
        return;
      }
      const table = document.getElementById("projectRows");
      table.innerHTML = "";
      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((e) => {
      console.error("Errore nel caricamento progetti:", e);
      alert("Errore nel caricamento dei progetti.");
      logActivity("❌ Errore nel caricamento progetti.");
    });
};

// 📂 Importa file dal server (preset directory)
window.importServerFileFromPresetDir = function () {
  const baseDir = document.getElementById("baseDirSelect").value;
  const fileName = document.getElementById("fileNameInput").value.trim();
  const destFolder = document.getElementById("destinationPath").value.trim();

  if (!fileName || !destFolder) {
    alert("❌ Inserisci sia il nome file che la destinazione.");
    return;
  }

  const fullSourcePath = baseDir + fileName;

  fetch("/dashboard/api/copy_file_from_path.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify({ source: fullSourcePath, destination: destFolder })
  })
    .then((r) => r.json())
    .then((data) => {
      if (data.success) {
        alert("✅ File copiato: " + (data.path || destFolder));
        logActivity(`📁 Copiato: <code>${fullSourcePath}</code> → <strong>${destFolder}</strong>`);
      } else {
        alert("❌ Errore: " + data.error);
        logActivity(`❌ Errore copia file: ${data.error}`);
      }
    })
    .catch((e) => {
      alert("Errore di rete: " + e.message);
      console.error(e);
    });
};

// ✅ Onload
window.addEventListener("load", function () {
  loadAllProjects();
});

// 🧾 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.");
  }
};