Nota: dopo aver pubblicato, potrebbe essere necessario pulire la cache del proprio browser per vedere i cambiamenti.

  • Firefox / Safari: tieni premuto il tasto delle maiuscole Shift e fai clic su Ricarica, oppure premi Ctrl-F5 o Ctrl-R (⌘-R su Mac)
  • Google Chrome: premi Ctrl-Shift-R (⌘-Shift-R su un Mac)
  • Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5.
// ============================================
// 🔧 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
let __creating = false;

async function createProject() {
  if (__creating) return;                // evita doppio invio
  const input = document.getElementById('newProjectName');
  const raw   = (input?.value || '').trim();
  if (!raw) { alert('Inserisci un nome progetto'); return; }

  // 1) normalizza: sostituisci spazi con underscore
  const name = raw.replace(/\s+/g, '_');

  // 2) valida: solo A-Z a-z 0-9 _ -
  if (!/^[A-Za-z0-9_-]+$/.test(name)) {
    alert('Nome non valido. Usa solo A–Z, a–z, 0–9, _ e - (niente accenti/simboli).');
    return;
  }

  __creating = true;
  const btn = document.getElementById('btnCreateProject');
  if (btn) { btn.disabled = true; btn.textContent = 'Creo…'; }

  try {
    const r = await fetch('/dashboard/api/project_create.php', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type':'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ name })
    });

    let j;
    try { j = await r.json(); } catch { throw new Error('Risposta non-JSON dal server'); }

    if (!j.ok) {
      if (r.status === 409) throw new Error('Questo progetto esiste già.');
      if (r.status === 401) throw new Error('Non sei autenticato (Basic Auth). Apri /dashboard/api/project_list.php, inserisci user/pass e riprova.');
      if (j.error)          throw new Error(j.error);
      throw new Error('Creazione fallita.');
    }

    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);
  } finally {
    __creating = false;
    if (btn) { btn.disabled = false; btn.textContent = 'Crea progetto'; }
  }
}


// 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
// ────────────────────────────────────────────