Nessun oggetto della modifica
Nessun oggetto della modifica
Riga 1: Riga 1:
// ============================================
// ============================================
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// Pulito e coerente con "Gestione Progetti" (filesystem reale)
// ============================================
// ============================================


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


// ⚙️ CONNESSIONE API (via proxy server)
// Mini-log visuale in pagina
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.");
  }
};
 
// Log persistente lato server (Basic Auth inclusa)
function dashLog(msg, lvl='INFO', mod='Dashboard', act='') {
  const body = new URLSearchParams({ m: msg, lvl, mod, act });
  return fetch('/dashboard/api/log.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body,
    credentials: 'include'
  }).catch(e => console.error('dashLog fail:', e));
}
function logInfo (m, extra={}) { return dashLog(m, 'INFO',    extra.mod||'Dashboard', extra.act||''); }
function logWarn (m, extra={}) { return dashLog(m, 'WARNING', extra.mod||'Dashboard', extra.act||''); }
function logError(m, extra={}) { return dashLog(m, 'ERROR',  extra.mod||'Dashboard', extra.act||''); }
 
// ────────────────────────────────────────────
/* ⚙️ CONNESSIONE API (via proxy server) */
// ────────────────────────────────────────────
window.testAPIConnection = async function () {
window.testAPIConnection = async function () {
   const prompt = (document.getElementById("test-prompt")?.value || "").trim();
   const prompt = (document.getElementById("test-prompt")?.value || "").trim();
   const output = document.getElementById("api-result");
   const output = document.getElementById("api-result");
   const model =
   const model = document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
    document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";


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


   output.innerText = "⏳ Contatto il proxy sul server...";
   output.innerText = "⏳ Contatto il proxy sul server...";
Riga 31: Riga 63:
       body: JSON.stringify({ prompt, model })
       body: JSON.stringify({ prompt, model })
     });
     });
     const data = await res.json();
     const data = await res.json();


Riga 47: Riga 78:
};
};


// 🎯 Analizza progetto con GPT (sempre via proxy)
// ────────────────────────────────────────────
window.analyzeProjectWithGPT = async function (title, notes) {
/* 🧠 ANALISI PROGETTO (render pulito in card) */
// ────────────────────────────────────────────
 
// Renderer stile ChatGPT per #gptResponse
function renderGpt(text) {
  const box = document.getElementById('gptResponse');
  if (!box) return;
  if (!text) { box.innerHTML = '<em style="opacity:.7">Nessuna risposta</em>'; return; }
 
  let html = (text || '').replace(/\r\n/g, '\n')
    .replace(/^\s*#{3}\s?(.*)$/gm, '<h3 style="font-size:18px;margin:14px 0 6px;">$1</h3>')
    .replace(/^\s*#{2}\s?(.*)$/gm, '<h2 style="font-size:20px;margin:16px 0 8px;">$1</h2>')
    .replace(/^\s*#\s?(.*)$/gm,  '<h1 style="font-size:22px;margin:18px 0 10px;">$1</h1>')
    .replace(/^\s*-\s+(.*)$/gm,  '<li>$1</li>');
  html = html.replace(/(?:<li>.*<\/li>\n?)+/gs, m => `<ul style="margin:8px 0 14px 22px;">${m}</ul>`);
  html = html.split('\n').map(line => {
    if (/^<h\d|^<ul|^<li|^<\/ul>/.test(line)) return line;
    if (line.trim()==='') return '';
    return `<p style="margin:8px 0;">${line}</p>`;
  }).join('');
  box.innerHTML = html;
}
 
// Costruisce prompt dal form
function buildPromptForGPT() {
  const title      = (document.getElementById('newProjectTitle')?.value || '').trim();
  const notes      = (document.getElementById('newProjectNotes')?.value || '').trim();
  const goal        = (document.getElementById('p_goal')?.value || '').trim();
  const audience    = (document.getElementById('p_audience')?.value || '').trim();
  const deliverable = (document.getElementById('p_deliverable')?.value || '').trim();
  const constraints = (document.getElementById('p_constraints')?.value || '').trim();
 
  const out = [];
  out.push(`You are a senior editor and project designer. Provide a clear, actionable plan.`);
  if (title)      out.push(`\n# Title\n${title}`);
  if (notes)      out.push(`\n# Notes\n${notes}`);
  if (goal)        out.push(`\n# Goal\n${goal}`);
  if (audience)    out.push(`\n# Audience\n${audience}`);
  if (deliverable) out.push(`\n# Deliverables\n${deliverable}`);
  if (constraints) out.push(`\n# Constraints\n${constraints}`);
  out.push(`\n# Output format
- Executive Summary
- Strengths & Risks
- Step-by-step Plan (milestones)
- Resources & Budget hints
- Metrics of success`);
  return out.join('\n');
}
 
// Bottone "Analizza con GPT" (via proxy server). Se vuoi la chiamata reale, basta usare questo handler.
window.analyzeProjectWithGPT = async function () {
  const btn  = document.getElementById('btnAnalyze');
  const model = document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
  const prompt = buildPromptForGPT();
 
  btn && (btn.disabled = true, btn.textContent = 'Analizzo…');
  logActivity('🤖 Analisi GPT via proxy…');
 
   try {
   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", {
     const res = await fetch("/dashboard/api/openai_project_gpt.php", {
       method: "POST",
       method: "POST",
Riga 61: Riga 144:
       body: JSON.stringify({ prompt, model })
       body: JSON.stringify({ prompt, model })
     });
     });
    const data = await res.json();


    const data = await res.json();
     if (data.status === "ok" && data.result) {
     if (data.status === "ok" && data.result) {
       document.getElementById("response").value = data.result;
       renderGpt(data.result);
       logActivity(`✅ Analisi completata – <strong>${title}</strong>`);
       logActivity('✅ Analisi GPT completata');
      logInfo('GPT analysis done', { mod:'GPT', act:'analyze' });
     } else {
     } else {
       alert("Errore GPT: " + (data.error || "Risposta vuota"));
       renderGpt('❌ Errore GPT: ' + (data.error || 'Risposta vuota'));
       logActivity(`❌ Errore GPT: ${data.error || "risposta vuota"}`);
       logError('GPT analysis failed', { mod:'GPT', act:'analyze' });
     }
     }
   } catch (err) {
   } catch (err) {
     console.error("❌ Errore completo GPT:", err);
     renderGpt('❌ Errore di rete: ' + err.message);
    alert("Errore durante la richiesta a GPT:\n" + err.message);
     logError('GPT network error', { mod:'GPT', act:'analyze' });
     logActivity(`❌ Errore richiesta GPT: ${err.message}`);
   } finally {
   }
    btn && (btn.disabled = false, btn.textContent = 'Analizza con GPT');
};
 
// 📊 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
// ────────────────────────────────────────────
/* 📁 PROMPT / FILE (utility esistenti) */
// ────────────────────────────────────────────
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", {
     credentials: "include"
     credentials: "include"
   })
   })
    .then((r) => r.json())
  .then(r => r.json())
    .then((data) => {
  .then(data => {
      if (data.status === "ok") {
    if (data.status === "ok") {
        document.getElementById("promptArea").value = data.content;
      const el = document.getElementById("promptArea");
        logActivity("📥 Caricato prompt.txt nella textarea.");
      if (el) el.value = data.content;
      } else {
      logActivity("📥 Caricato prompt.txt nella textarea.");
        alert("Errore: " + data.error);
    } else {
        logActivity("❌ Errore nel caricamento: " + data.error);
      alert("Errore: " + data.error);
      }
      logActivity("❌ Errore nel caricamento: " + data.error);
    })
    }
    .catch((e) => {
  })
      alert("Errore nel caricamento: " + e);
  .catch(e => {
      logActivity("❌ Errore nel caricamento di prompt.txt.");
    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",
Riga 160: Riga 194:
     body: "text=" + encodeURIComponent(content)
     body: "text=" + encodeURIComponent(content)
   })
   })
    .then((r) => {
  .then(r => { if (!r.ok) throw new Error("Errore nel salvataggio"); return r.text(); })
      if (!r.ok) throw new Error("Errore nel salvataggio");
  .then(() => { logActivity("💾 Salvato prompt.txt dal form."); alert("Prompt salvato con successo."); })
      return r.text();
  .catch(e => { alert("Errore nel salvataggio: " + e); logActivity("❌ Errore nel salvataggio di prompt.txt."); });
    })
    .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
// Salva / Carica files per GPT
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) { alert("Nome file o contenuto mancante."); return; }
   if (!filename || !content) {
    alert("Inserisci un nome file e assicurati che il contenuto non sia vuoto.");
    return;
  }


   fetch("/dashboard/api/write_file.php", {
   fetch("/dashboard/api/write_file.php", {
Riga 192: Riga 213:
     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((data) => {
  .then(data => {
      if (data.status === "ok") {
    if (data.status === "ok") {
        document.getElementById("gpt-response-area").value = data.content;
      logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
        logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
      alert("File salvato: " + (data.path || filename));
        alert("File salvato con successo in: " + data.path);
    } else {
      } else {
      alert("Errore: " + data.error);
        alert("Errore: " + data.error);
      logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
        logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
    }
      }
  })
    })
  .catch(e => { alert("Errore durante il salvataggio."); console.error(e); });
    .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) { alert("Inserisci il nome del file da caricare."); return; }


  if (!filename) {
   fetch(`/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(subfolder)}&filename=${encodeURIComponent(filename)}`, { credentials: "include" })
    alert("Inserisci il nome del file da caricare.");
   .then(r => r.json())
    return;
  .then(data => {
  }
    if (data.status === "ok") {
 
      const ta = document.getElementById("gpt-response-area");
   fetch(
      if (ta) ta.value = data.content;
    `/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(
      logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`);
      subfolder
    } else {
    )}&filename=${encodeURIComponent(filename)}`,
      alert("Errore: " + data.error);
    { credentials: "include" }
      logActivity(`❌ Errore nel caricamento di ${filename}: ${data.error}`);
   )
    }
    .then((r) => r.json())
  })
    .then((data) => {
  .catch(e => { alert("Errore durante il caricamento del file."); console.error(e); });
      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 () {
/* 🧪 STRUMENTI DI TEST */
  fetch("/dashboard/api/read_all_projects.php", { credentials: "include" })
// ────────────────────────────────────────────
    .then((r) => r.json())
window.runTestCode = function () {
    .then((data) => {
  const ta = document.getElementById('codeArea');
      if (!Array.isArray(data)) {
  if (!ta) { alert('Area di test non trovata (#codeArea).'); return; }
        logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
  const src = ta.value || '';
        return;
  try { return new Function(src)(); }
      }
  catch (e) { alert('Errore nel codice:\n' + e.message); }
      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.");
    });
};
};


// ────────────────────────────────────────────
/* =======================
/* =======================
  * Gestione Progetti stabile
  * 📂 GESTIONE PROGETTI (REALE)
  * ======================= */
  * ======================= */
 
// ────────────────────────────────────────────
const API = {
const API = {
   list:  '/dashboard/api/project_list.php',
   list:  '/dashboard/api/project_list.php',
Riga 285: Riga 270:
};
};


// Stato corrente
let currentProject = null;
let currentProject = null;


// Carica lista
async function loadAllProjects() {
async function loadAllProjects() {
   try {
   try {
     const r = await fetch('/dashboard/api/project_list.php', {
     const r = await fetch(API.list, { credentials:'include', cache:'no-store' });
      credentials: 'include',   // <<<<< QUESTO È FONDAMENTALE
      cache: 'no-store'
    });
     const txt = await r.text();
     const txt = await r.text();
     let j;
     let j; try { j = JSON.parse(txt); } catch { throw new Error('Risposta non-JSON dalla lista progetti'); }
    try { j = JSON.parse(txt); }
    catch { throw new Error('Risposta non-JSON dalla lista progetti'); }
 
     if (!j.ok) throw new Error(j.error || 'Lista progetti fallita');
     if (!j.ok) throw new Error(j.error || 'Lista progetti fallita');
     renderProjects(j.projects || []);
     renderProjects(j.projects || []);
Riga 307: Riga 286:
}
}


 
// Disegna lista
function renderProjects(projects) {
function renderProjects(projects) {
   const ul = document.getElementById('projectsList');
   const ul = document.getElementById('projectsList');
  if (!ul) return;
   ul.innerHTML = '';
   ul.innerHTML = '';
  if (!projects.length) {
    ul.innerHTML = '<li style="color:#777;">Nessun progetto trovato.</li>';
    return;
  }


   projects.forEach(p => {
   projects.forEach(p => {
Riga 319: Riga 304:
     li.style.margin = '6px 0';
     li.style.margin = '6px 0';


     const name = p.name;
     const label = document.createElement('span');
    label.textContent = p.name;
    label.style.fontWeight = (p.name === currentProject ? '700' : '500');


     const btnOpen = document.createElement('button');
     const btnOpen = document.createElement('button');
     btnOpen.textContent = 'Apri';
     btnOpen.textContent = 'Apri';
     btnOpen.onclick = () => { selectProject(name); };
     btnOpen.onclick = () => { selectProject(p.name); };


     const btnZip = document.createElement('button');
     const btnZip = document.createElement('button');
     btnZip.textContent = 'ZIP';
     btnZip.textContent = 'ZIP';
     btnZip.title = 'Crea backup zip';
     btnZip.title = 'Crea backup zip';
     btnZip.onclick = () => backupProject(name);
     btnZip.onclick = () => backupProject(p.name);


     const btnDel = document.createElement('button');
     const btnDel = document.createElement('button');
     btnDel.textContent = '🗑️';
     btnDel.textContent = '🗑️';
     btnDel.title = 'Sposta nel cestino (soft delete)';
     btnDel.title = 'Sposta nel cestino (soft delete)';
     btnDel.onclick = () => deleteProject(name);
     btnDel.onclick = () => deleteProject(p.name);
 
    const label = document.createElement('span');
    label.textContent = name;
    label.style.fontWeight = (name === currentProject ? '700' : '400');


     li.append(label, btnOpen, btnZip, btnDel);
     li.append(label, btnOpen, btnZip, btnDel);
Riga 344: Riga 327:
}
}


// Seleziona progetto correntemente attivo
function selectProject(name) {
function selectProject(name) {
   currentProject = name;
   currentProject = name;
   logInfo('Project selected', { mod:'Progetti', act:'select' });
   logInfo('Project selected', { mod:'Progetti', act:'select' });
   loadAllProjects(); // rinfresca la lista per evidenziare in bold
   loadAllProjects();
  // TODO: qui richiami eventuale caricamento file/struttura per quel progetto
}
}


// Crea progetto
// Crea
async function createProject() {
async function createProject() {
   const input = document.getElementById('newProjectName');
   const input = document.getElementById('newProjectName');
   const name = (input.value || '').trim();
   const name = (input?.value || '').trim();
   if (!name) return alert('Inserisci un nome progetto');
   if (!name) return alert('Inserisci un nome progetto');


   try {
   try {
    const body = new URLSearchParams({ name });
     const r = await fetch(API.create, {
     const r = await fetch(API.create, { method:'POST', body, credentials:'include' });
      method:'POST',
      credentials:'include',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ name })
    });
     const j = await r.json();
     const j = await r.json();
     if (!j.ok) throw new Error(j.error || 'create failed');
     if (!j.ok) throw new Error(j.error || 'create failed');
Riga 374: Riga 359:
}
}


// Soft delete → sposta nel cestino
// Elimina (soft)
async function deleteProject(name) {
async function deleteProject(name) {
   if (!confirm(`Sicuro di spostare "${name}" nel cestino?`)) return;
   if (!confirm(`Sicuro di spostare "${name}" nel cestino?`)) return;
   try {
   try {
    const body = new URLSearchParams({ name });
     const r = await fetch(API.del, {
     const r = await fetch(API.del, { method:'POST', body, credentials:'include' });
      method:'POST',
      credentials:'include',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ name })
    });
     const j = await r.json();
     const j = await r.json();
     if (!j.ok) throw new Error(j.error || 'delete failed');
     if (!j.ok) throw new Error(j.error || 'delete failed');
Riga 392: Riga 381:
}
}


// Backup in ZIP
// Backup
async function backupProject(name) {
async function backupProject(name) {
   try {
   try {
    const body = new URLSearchParams({ name });
     const r = await fetch(API.backup, {
     const r = await fetch(API.backup, { method:'POST', body, credentials:'include' });
      method:'POST',
      credentials:'include',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ name })
    });
     const j = await r.json();
     const j = await r.json();
     if (!j.ok) throw new Error(j.error || 'backup failed');
     if (!j.ok) throw new Error(j.error || 'backup failed');
Riga 412: Riga 405:
   const btnCreate = document.getElementById('btnCreateProject');
   const btnCreate = document.getElementById('btnCreateProject');
   if (btnCreate) btnCreate.addEventListener('click', createProject);
   if (btnCreate) btnCreate.addEventListener('click', createProject);
  loadAllProjects();
});
// 📂 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;
   const analyzeBtn = document.getElementById('btnAnalyze');
  if (analyzeBtn) analyzeBtn.addEventListener('click', window.analyzeProjectWithGPT);


   fetch("/dashboard/api/copy_file_from_path.php", {
   loadAllProjects(); // subito all’avvio
    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) {
// FINE FILE
  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.");
  }
};
 
 
 
// ▶️ Console JS interna (Strumenti di Test)
window.runTestCode = function () {
  const ta = document.getElementById('codeArea');
  if (!ta) {
    alert('Area di test non trovata (#codeArea).');
    return;
  }
  const src = ta.value || '';
  try {
    const result = new Function(src)(); // sandbox, meglio di eval
    console.log('▶ runTestCode: OK', result);
    return result;
  } catch (e) {
    console.error('▶ runTestCode: errore', e);
    alert('Errore nel codice:\n' + e.message);
  }
};
 
// --- LOG LITE: 3 helper super semplici -----------------------
function dashLog(msg, lvl='INFO', mod='Dashboard', act='') {
  const body = new URLSearchParams({ m: msg, lvl, mod, act });
  return fetch('/dashboard/api/log.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body
  }).catch(e => console.error('dashLog fail:', e));
}
function logInfo (m, extra={}) { return dashLog(m, 'INFO',    extra.mod||'Dashboard', extra.act||''); }
function logWarn (m, extra={}) { return dashLog(m, 'WARNING', extra.mod||'Dashboard', extra.act||''); }
function logError(m, extra={}) { return dashLog(m, 'ERROR',  extra.mod||'Dashboard', extra.act||''); }
// --------------------------------------------------------------

Versione delle 17:49, 14 set 2025

// ============================================
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// Pulito e coerente con "Gestione Progetti" (filesystem reale)
// ============================================

// ────────────────────────────────────────────
// 🧭 UTILITÀ GENERALI
// ────────────────────────────────────────────
window.toggleDashboardBox = function (id) {
  const box = document.getElementById(id);
  if (box) box.style.display = box.style.display === "block" ? "none" : "block";
};

// Mini-log visuale in pagina
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.");
  }
};

// Log persistente lato server (Basic Auth inclusa)
function dashLog(msg, lvl='INFO', mod='Dashboard', act='') {
  const body = new URLSearchParams({ m: msg, lvl, mod, act });
  return fetch('/dashboard/api/log.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body,
    credentials: 'include'
  }).catch(e => console.error('dashLog fail:', e));
}
function logInfo (m, extra={}) { return dashLog(m, 'INFO',    extra.mod||'Dashboard', extra.act||''); }
function logWarn (m, extra={}) { return dashLog(m, 'WARNING', extra.mod||'Dashboard', extra.act||''); }
function logError(m, extra={}) { return dashLog(m, 'ERROR',   extra.mod||'Dashboard', extra.act||''); }

// ────────────────────────────────────────────
/* ⚙️ 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}`);
  }
};

// ────────────────────────────────────────────
/* 🧠 ANALISI PROGETTO (render pulito in card) */
// ────────────────────────────────────────────

// Renderer stile ChatGPT per #gptResponse
function renderGpt(text) {
  const box = document.getElementById('gptResponse');
  if (!box) return;
  if (!text) { box.innerHTML = '<em style="opacity:.7">Nessuna risposta</em>'; return; }

  let html = (text || '').replace(/\r\n/g, '\n')
    .replace(/^\s*#{3}\s?(.*)$/gm, '<h3 style="font-size:18px;margin:14px 0 6px;">$1</h3>')
    .replace(/^\s*#{2}\s?(.*)$/gm, '<h2 style="font-size:20px;margin:16px 0 8px;">$1</h2>')
    .replace(/^\s*#\s?(.*)$/gm,   '<h1 style="font-size:22px;margin:18px 0 10px;">$1</h1>')
    .replace(/^\s*-\s+(.*)$/gm,   '<li>$1</li>');
  html = html.replace(/(?:<li>.*<\/li>\n?)+/gs, m => `<ul style="margin:8px 0 14px 22px;">${m}</ul>`);
  html = html.split('\n').map(line => {
    if (/^<h\d|^<ul|^<li|^<\/ul>/.test(line)) return line;
    if (line.trim()==='') return '';
    return `<p style="margin:8px 0;">${line}</p>`;
  }).join('');
  box.innerHTML = html;
}

// Costruisce prompt dal form
function buildPromptForGPT() {
  const title       = (document.getElementById('newProjectTitle')?.value || '').trim();
  const notes       = (document.getElementById('newProjectNotes')?.value || '').trim();
  const goal        = (document.getElementById('p_goal')?.value || '').trim();
  const audience    = (document.getElementById('p_audience')?.value || '').trim();
  const deliverable = (document.getElementById('p_deliverable')?.value || '').trim();
  const constraints = (document.getElementById('p_constraints')?.value || '').trim();

  const out = [];
  out.push(`You are a senior editor and project designer. Provide a clear, actionable plan.`);
  if (title)       out.push(`\n# Title\n${title}`);
  if (notes)       out.push(`\n# Notes\n${notes}`);
  if (goal)        out.push(`\n# Goal\n${goal}`);
  if (audience)    out.push(`\n# Audience\n${audience}`);
  if (deliverable) out.push(`\n# Deliverables\n${deliverable}`);
  if (constraints) out.push(`\n# Constraints\n${constraints}`);
  out.push(`\n# Output format
- Executive Summary
- Strengths & Risks
- Step-by-step Plan (milestones)
- Resources & Budget hints
- Metrics of success`);
  return out.join('\n');
}

// Bottone "Analizza con GPT" (via proxy server). Se vuoi la chiamata reale, basta usare questo handler.
window.analyzeProjectWithGPT = async function () {
  const btn   = document.getElementById('btnAnalyze');
  const model = document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
  const prompt = buildPromptForGPT();

  btn && (btn.disabled = true, btn.textContent = 'Analizzo…');
  logActivity('🤖 Analisi GPT via proxy…');

  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) {
      renderGpt(data.result);
      logActivity('✅ Analisi GPT completata');
      logInfo('GPT analysis done', { mod:'GPT', act:'analyze' });
    } else {
      renderGpt('❌ Errore GPT: ' + (data.error || 'Risposta vuota'));
      logError('GPT analysis failed', { mod:'GPT', act:'analyze' });
    }
  } catch (err) {
    renderGpt('❌ Errore di rete: ' + err.message);
    logError('GPT network error', { mod:'GPT', act:'analyze' });
  } finally {
    btn && (btn.disabled = false, btn.textContent = 'Analizza con GPT');
  }
};

// ────────────────────────────────────────────
/* 📁 PROMPT / FILE (utility esistenti) */
// ────────────────────────────────────────────
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") {
      const el = document.getElementById("promptArea");
      if (el) el.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 / Carica files per GPT
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("Nome file o contenuto mancante."); 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") {
      logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
      alert("File salvato: " + (data.path || filename));
    } else {
      alert("Errore: " + data.error);
      logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
    }
  })
  .catch(e => { alert("Errore durante il salvataggio."); console.error(e); });
};

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") {
      const ta = document.getElementById("gpt-response-area");
      if (ta) ta.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 => { alert("Errore durante il caricamento del file."); console.error(e); });
};

// ────────────────────────────────────────────
/* 🧪 STRUMENTI DI TEST */
// ────────────────────────────────────────────
window.runTestCode = function () {
  const ta = document.getElementById('codeArea');
  if (!ta) { alert('Area di test non trovata (#codeArea).'); return; }
  const src = ta.value || '';
  try { return new Function(src)(); }
  catch (e) { alert('Errore nel codice:\n' + e.message); }
};

// ────────────────────────────────────────────
/* =======================
 * 📂 GESTIONE PROGETTI (REALE)
 * ======================= */
// ────────────────────────────────────────────
const API = {
  list:   '/dashboard/api/project_list.php',
  create: '/dashboard/api/project_create.php',
  del:    '/dashboard/api/project_delete.php',
  backup: '/dashboard/api/project_backup.php'
};

let currentProject = null;

// Carica lista
async function loadAllProjects() {
  try {
    const r = await fetch(API.list, { credentials:'include', cache:'no-store' });
    const txt = await r.text();
    let j; try { j = JSON.parse(txt); } catch { throw new Error('Risposta non-JSON dalla lista progetti'); }
    if (!j.ok) throw new Error(j.error || 'Lista progetti fallita');
    renderProjects(j.projects || []);
  } catch (e) {
    console.error('project_list error:', e);
    alert('Errore nel caricamento dei progetti: ' + e.message);
  }
}

// Disegna lista
function renderProjects(projects) {
  const ul = document.getElementById('projectsList');
  if (!ul) return;
  ul.innerHTML = '';

  if (!projects.length) {
    ul.innerHTML = '<li style="color:#777;">Nessun progetto trovato.</li>';
    return;
  }

  projects.forEach(p => {
    const li = document.createElement('li');
    li.style.display = 'flex';
    li.style.alignItems = 'center';
    li.style.gap = '8px';
    li.style.margin = '6px 0';

    const label = document.createElement('span');
    label.textContent = p.name;
    label.style.fontWeight = (p.name === currentProject ? '700' : '500');

    const btnOpen = document.createElement('button');
    btnOpen.textContent = 'Apri';
    btnOpen.onclick = () => { selectProject(p.name); };

    const btnZip = document.createElement('button');
    btnZip.textContent = 'ZIP';
    btnZip.title = 'Crea backup zip';
    btnZip.onclick = () => backupProject(p.name);

    const btnDel = document.createElement('button');
    btnDel.textContent = '🗑️';
    btnDel.title = 'Sposta nel cestino (soft delete)';
    btnDel.onclick = () => deleteProject(p.name);

    li.append(label, btnOpen, btnZip, btnDel);
    ul.appendChild(li);
  });
}

function selectProject(name) {
  currentProject = name;
  logInfo('Project selected', { mod:'Progetti', act:'select' });
  loadAllProjects();
}

// Crea
async function createProject() {
  const input = document.getElementById('newProjectName');
  const name = (input?.value || '').trim();
  if (!name) return alert('Inserisci un nome progetto');

  try {
    const r = await fetch(API.create, {
      method:'POST',
      credentials:'include',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ name })
    });
    const j = await r.json();
    if (!j.ok) throw new Error(j.error || 'create failed');
    logInfo('Project created', { mod:'Progetti', act:'create' });
    input.value = '';
    await loadAllProjects();
    selectProject(name);
  } catch (e) {
    console.error(e);
    logError('Project create failed', { mod:'Progetti', act:'create' });
    alert('Errore creazione: ' + e.message);
  }
}

// Elimina (soft)
async function deleteProject(name) {
  if (!confirm(`Sicuro di spostare "${name}" nel cestino?`)) return;
  try {
    const r = await fetch(API.del, {
      method:'POST',
      credentials:'include',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ name })
    });
    const j = await r.json();
    if (!j.ok) throw new Error(j.error || 'delete failed');
    logWarn('Project moved to trash', { mod:'Progetti', act:'delete' });
    if (currentProject === name) currentProject = null;
    await loadAllProjects();
  } catch (e) {
    console.error(e);
    logError('Project delete failed', { mod:'Progetti', act:'delete' });
    alert('Errore eliminazione: ' + e.message);
  }
}

// Backup
async function backupProject(name) {
  try {
    const r = await fetch(API.backup, {
      method:'POST',
      credentials:'include',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ name })
    });
    const j = await r.json();
    if (!j.ok) throw new Error(j.error || 'backup failed');
    logInfo('Project zipped', { mod:'Progetti', act:'backup' });
    alert(`Backup creato: ${j.zip}`);
  } catch (e) {
    console.error(e);
    logError('Project backup failed', { mod:'Progetti', act:'backup' });
    alert('Errore backup: ' + e.message);
  }
}

// Bind UI
document.addEventListener('DOMContentLoaded', () => {
  const btnCreate = document.getElementById('btnCreateProject');
  if (btnCreate) btnCreate.addEventListener('click', createProject);

  const analyzeBtn = document.getElementById('btnAnalyze');
  if (analyzeBtn) analyzeBtn.addEventListener('click', window.analyzeProjectWithGPT);

  loadAllProjects(); // subito all’avvio
});

// ────────────────────────────────────────────
// FINE FILE
// ────────────────────────────────────────────