Nessun oggetto della modifica
Nessun oggetto della modifica
 
(24 versioni intermedie di uno stesso utente non sono mostrate)
Riga 1: Riga 1:
// Funzione per aprire e chiudere i box nella dashboard
 
window.toggleDashboardBox = function(id) {
// ============================================
// 🔧 CommonDashboard.js – versione GPT-4o + Percorsi corretti
// ============================================
 
// 📘 INTRODUZIONE
window.toggleDashboardBox = function (id) {
   const box = document.getElementById(id);
   const box = document.getElementById(id);
   if (box) {
   if (box) {
     box.style.display = (box.style.display === 'block') ? 'none' : 'block';
     box.style.display = box.style.display === "block" ? "none" : "block";
   }
   }
};
};


// Funzione per testare 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();
  const model = document.getElementById('model-select').value;
   const prompt = document.getElementById('test-prompt').value;
   const prompt = document.getElementById('test-prompt').value;
   const output = document.getElementById('api-result');
   const output = document.getElementById('api-result');
  const model = "gpt-4o-2024-05-13";


   if (!key || !prompt) {
   if (!key || !prompt) {
Riga 19: Riga 24:
   }
   }


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


   try {
   try {
Riga 38: 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(`✅ Test API riuscito – Modello: <strong>${model}</strong>`);
       logActivity(`✅ Risposta ricevuta – Modello: <strong>${model}</strong>`);
     } else if (data.error) {
     } else if (data.error) {
       output.innerText = "❌ Errore: " + data.error.message;
       output.innerText = "❌ Errore: " + data.error.message;
Riga 48: Riga 54:
   } catch (e) {
   } catch (e) {
     output.innerText = "🚫 Errore di rete o sintassi: " + e.message;
     output.innerText = "🚫 Errore di rete o sintassi: " + e.message;
    logActivity(`❌ Errore di connessione: ${e.message}`);
   }
   }
};
};


// Funzione mock per salvataggio
// 📊 STATO PROGETTI
window.saveFileChanges = function() {
  const selectedFile = document.getElementById("file-select").value;
  const newContent = document.getElementById("file-preview").value;
  alert("💾 Modifiche salvate per: " + selectedFile + "\n(contenuto simulato)");
  logActivity(`💾 File salvato: <strong>${selectedFile}</strong>`);
};
 
// Funzione per anteprima file simulata
window.loadFilePreview = function(filename) {
  const contentArea = document.getElementById("file-preview");
  const fakeContents = {
    "common.css": "/* Contenuto di esempio per common.css */\nbody { background: #fff; }",
    "common.js": "// Contenuto JS\nconsole.log('JS attivo');",
    "LocalSettings.php": "<?php\n# Impostazioni locali di MediaWiki\n$wgSitename = 'Masticationpedia';"
  };
  contentArea.value = fakeContents[filename] || "Contenuto non disponibile.";
};
 
// Funzione per aprire popup nuovo progetto
window.openProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "block";
};
 
// Funzione per chiudere popup nuovo progetto
window.closeProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "none";
};
 
// Funzione per aggiungere nuovo progetto
window.addNewProject = function () {
window.addNewProject = function () {
   const title = document.getElementById("newProjectTitle").value.trim();
   const title = document.getElementById("newProjectTitle").value.trim();
Riga 96: Riga 74:
   table.appendChild(newRow);
   table.appendChild(newRow);
   window.closeProjectDialog();
   window.closeProjectDialog();
   logActivity(`📌 Nuovo progetto aggiunto: <strong>${title}</strong> – ${notes}`);
   logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);
};


// Mini console per testare codice JS
  // 🔄 Salva su server
window.runTestCode = function () {
   const payload = {
  const code = document.getElementById('codeArea').value;
     title: title,
   const output = document.getElementById('consoleOutput');
     notes: notes,
  try {
    date: new Date().toLocaleDateString("it-IT")
     const result = eval(code);
   };
     output.textContent = "✅ Output:\n" + result;
  } catch (err) {
    output.textContent = "❌ Errore:\n" + err;
   }
};


// Inizializzazione automatica dei comportamenti al caricamento
  fetch("/dashboard/api/write_project.php", {
document.addEventListener("DOMContentLoaded", function () {
    method: "POST",
   const fileSelect = document.getElementById("fileSelect");
    headers: { "Content-Type": "application/json" },
  if (fileSelect) {
    body: JSON.stringify(payload)
     fileSelect.addEventListener("change", function () {
   })
       const selected = this.value;
    .then((res) => res.json())
       window.loadFilePreview(selected);
    .then((data) => {
      if (!data.success) {
        alert("⚠️ Errore salvataggio su server: " + data.error);
        logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
      }
    })
     .catch((err) => {
       alert("❌ Errore rete salvataggio progetto.");
       console.error("Errore invio progetto:", err);
      logActivity("❌ Errore rete durante salvataggio progetto.");
     });
     });
  }
};
});


// Funzione per scrivere nel registro attività
window.openProjectDialog = function () {
window.logActivity = function (messaggio) {
   document.getElementById("newProjectDialog").style.display = "block";
   const contenitore = document.getElementById("activityLogContent");
};
  if (!contenitore) return;


  const ora = new Date().toLocaleTimeString("it-IT");
window.closeProjectDialog = function () {
   const paragrafo = document.createElement("p");
   document.getElementById("newProjectDialog").style.display = "none";
  paragrafo.innerHTML = `<strong>[${ora}]</strong> ${messaggio}`;
};
  contenitore.appendChild(paragrafo);


   // Scorrimento automatico verso il basso
// 📥 Carica prompt.txt
  contenitore.scrollTop = contenitore.scrollHeight;
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.");
    });
};
};


// Funzione per pulire il registro
// 💾 Salva prompt.txt
window.clearActivityLog = function () {
window.savePrompt = function () {
   const contenitore = document.getElementById("activityLogContent");
   const content = document.getElementById("promptArea").value;
   contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
   fetch('/dashboard/api/write_prompt.php', {
  logActivity("🧹 Log svuotato manualmente.");
    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.");
    });
};
};


// ===================== CONNESSIONE API ==========================
// 💾 Salva RISPOSTA GPT IN FILE
function testAPIConnection() {
window.salvaFileDaTextarea = function () {
   const apiKey = document.getElementById('api-key').value.trim();
   const content = document.getElementById("gpt-response-area").value;
   const prompt = document.getElementById('test-prompt').value.trim();
   const filename = document.getElementById("gpt-filename").value.trim();
   const model = document.getElementById('model-select').value;
   const subfolder = document.getElementById("gpt-subfolder").value;
  const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";


   if (!apiKey || !prompt) {
   if (!filename || !content) {
     alert("⚠️ Inserisci sia la chiave API che il prompt.");
     alert("Inserisci un nome file e assicurati che il contenuto non sia vuoto.");
     return;
     return;
   }
   }


   document.getElementById('api-result').textContent = "⏳ In attesa di risposta...";
   fetch('/dashboard/api/write_file.php', {
 
     method: 'POST',
  fetch("https://api.openai.com/v1/chat/completions", {
     method: "POST",
     headers: {
     headers: {
       "Authorization": "Bearer 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",
       'Content-Type': 'application/json'
      "Content-Type": "application/json"
     },
     },
     body: JSON.stringify({
     body: JSON.stringify({
       model: model,
       projectName: project,
       messages: [{ role: "user", content: prompt }]
       subfolder: subfolder,
      filename: filename,
      content: content
     })
     })
   })
   })
  .then(response => response.json())
    .then(response => response.json())
  .then(data => {
    .then(data => {
     const output = data.choices?.[0]?.message?.content || "❌ Nessuna risposta ricevuta.";
      if (data.status === "ok") {
     document.getElementById('api-result').textContent = output;
        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 nuovo Progetto (legacy compatibilità)
function addNewProject() {
  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 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)
   })
   })
  .catch(error => {
    .then((res) => res.json())
    console.error("Errore nella richiesta:", error);
    .then((data) => {
     document.getElementById('api-result').textContent = "🚫 Errore nella connessione API.";
      if (data.success) {
   });
        const row = document.createElement("tr");
        row.innerHTML = `<td>${title}</td><td style='color:green;font-weight:bold;'>✅ Completato</td><td>${payload.date}</td><td>${notes}</td>`;
        document.getElementById("projectRows").appendChild(row);
        closeProjectDialog();
      } else {
        alert("Errore salvataggio: " + data.error);
      }
    })
    .catch((err) => {
      console.error("Errore invio progetto:", err);
      alert("Errore di rete durante il salvataggio del progetto.");
     });
}
 
// 🚀 ========= 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>
        `;
        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.");
    });
};
 
// ✅ Avvia caricamento al load della Dashboard
if (typeof window.onload === 'function') {
   const oldOnLoad = window.onload;
  window.onload = function () {
    oldOnLoad();
    loadAllProjects();
  };
} else {
  window.onload = function () {
    loadAllProjects();
  };
}
}


// ✅ AL CARICAMENTO PAGINA: Carica tutti i progetti visibili nella tabella
window.onload = function () {
  loadAllProjects();
};




// =================== Carica in OpenAI ? ==============
// 🧾 REGISTRO ATTIVITÀ
window.uploadToOpenAI = async function () {
window.logActivity = function (messaggio) {
   const log = document.getElementById("activityLogContent");
   const contenitore = document.getElementById("activityLogContent") || document.getElementById("activityLog");
  const fileSelect = document.getElementById("fileSelect");
   if (!contenitore) return;
   const fileName = fileSelect ? fileSelect.value : "";


   if (!fileName) {
   const ora = new Date().toLocaleTimeString("it-IT");
    logActivity("⚠️ Nessun file selezionato.");
  const entry = document.createElement("div");
    return;
  entry.innerHTML = `<span style="color:gray;">[${ora}]</span> ${messaggio}`;
   }
   contenitore.prepend(entry);
};


  try {
window.clearActivityLog = function () {
    const response = await fetch("/oauth/sync_to_openai.php?file=" + encodeURIComponent(fileName));
  const contenitore = document.getElementById("activityLogContent");
    const result = await response.text();
   if (contenitore) {
    logActivity(`🔄 File "${fileName}" → ${result}`);
    contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
   } catch (err) {
     logActivity("🧹 Log svuotato manualmente.");
     logActivity(`❌ Errore sincronizzazione: ${err.message}`);
   }
   }
};
};

Versione attuale delle 17:22, 2 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}`);
  }
};

// 📊 STATO PROGETTI
window.addNewProject = function () {
  const title = document.getElementById("newProjectTitle").value.trim();
  const notes = document.getElementById("newProjectNotes").value.trim();
  if (!title) 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>
  `;
  table.appendChild(newRow);
  window.closeProjectDialog();
  logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);

  // 🔄 Salva su server
  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}`);
      }
    })
    .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 nuovo Progetto (legacy compatibilità)
function addNewProject() {
  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 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)
  })
    .then((res) => res.json())
    .then((data) => {
      if (data.success) {
        const row = document.createElement("tr");
        row.innerHTML = `<td>${title}</td><td style='color:green;font-weight:bold;'>✅ Completato</td><td>${payload.date}</td><td>${notes}</td>`;
        document.getElementById("projectRows").appendChild(row);
        closeProjectDialog();
      } else {
        alert("Errore salvataggio: " + data.error);
      }
    })
    .catch((err) => {
      console.error("Errore invio progetto:", err);
      alert("Errore di rete durante il salvataggio del progetto.");
    });
}

// 🚀 ========= 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>
        `;
        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.");
    });
};

// ✅ Avvia caricamento al load della Dashboard
if (typeof window.onload === 'function') {
  const oldOnLoad = window.onload;
  window.onload = function () {
    oldOnLoad();
    loadAllProjects();
  };
} else {
  window.onload = function () {
    loadAllProjects();
  };
}

// ✅ AL CARICAMENTO PAGINA: Carica tutti i progetti visibili nella tabella
window.onload = 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.");
  }
};