{% extends 'base.html' %}
{% set active = 'impostazioni' %}
{% block page_title %}Impostazioni{% endblock %}
{% block header_title %}Impostazioni{% endblock %}

{% block content %}
<div style="max-width:760px;display:flex;flex-direction:column;gap:24px">

  <!-- ── Stats ───────────────────────────────────────────────── -->
  <div class="card">
    <div class="card-title">Statistiche database</div>
    <div id="statsGrid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:12px;margin-top:4px">
      <div class="stat-card"><div class="stat-value" id="stTx">…</div><div class="stat-label">Transazioni</div></div>
      <div class="stat-card"><div class="stat-value" id="stCat">…</div><div class="stat-label">Categorie</div></div>
      <div class="stat-card"><div class="stat-value" id="stRec">…</div><div class="stat-label">Ricorrenti</div></div>
      <div class="stat-card"><div class="stat-value" id="stGoal">…</div><div class="stat-label">Obiettivi</div></div>
      <div class="stat-card"><div class="stat-value" id="stTag">…</div><div class="stat-label">Tag</div></div>
      <div class="stat-card"><div class="stat-value" id="stFile">…</div><div class="stat-label">Allegati</div></div>
      <div class="stat-card"><div class="stat-value" id="stDb">…</div><div class="stat-label">Dim. database</div></div>
    </div>
  </div>

  <!-- ── Backup ───────────────────────────────────────────────── -->
  <div class="card">
    <div class="card-title">💾 Backup dati</div>
    <p style="color:var(--muted);font-size:.875rem;margin-bottom:16px">
      Crea un archivio ZIP con il database e tutti gli allegati (scontrini, foto).
      Conserva il file in un posto sicuro — ti servirà per ripristinare i dati su un nuovo PC.
    </p>
    <div style="background:var(--surface2);border-radius:10px;padding:14px 16px;margin-bottom:16px;font-size:.82rem;color:var(--muted)">
      <strong style="color:var(--text)">Il backup contiene:</strong>
      <ul style="margin:6px 0 0 16px;line-height:1.9">
        <li>contabilita.db — tutte le transazioni, categorie, obiettivi, tag</li>
        <li>allegati/ — scontrini e documenti caricati</li>
      </ul>
    </div>
    <button class="btn btn-primary" style="font-size:.95rem;padding:10px 22px" onclick="downloadBackup()">
      ⬇ Scarica backup
    </button>
    <span id="backupStatus" style="margin-left:12px;font-size:.82rem;color:var(--muted)"></span>
  </div>

  <!-- ── Restore ──────────────────────────────────────────────── -->
  <div class="card">
    <div class="card-title">📂 Ripristina dati</div>
    <p style="color:var(--muted);font-size:.875rem;margin-bottom:6px">
      Carica un file ZIP creato dalla funzione di backup per ripristinare tutti i tuoi dati.
    </p>
    <div style="background:#f59e0b18;border:1px solid #f59e0b44;border-radius:8px;padding:12px 14px;margin-bottom:16px;font-size:.82rem">
      ⚠️ <strong>Attenzione:</strong> il ripristino <strong>sovrascrive</strong> il database e gli allegati attuali.
      Questa operazione non può essere annullata. Esegui prima un backup se necessario.
    </div>
    <div style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap">
      <div class="form-group" style="margin:0;flex:1;min-width:220px">
        <label class="form-label">File di backup (.zip)</label>
        <input type="file" class="form-control" id="restoreFile" accept=".zip" style="padding:5px">
      </div>
      <button class="btn btn-danger" style="padding:10px 20px" onclick="confirmRestore()">
        ↺ Ripristina
      </button>
    </div>
    <span id="restoreStatus" style="display:block;margin-top:10px;font-size:.82rem"></span>
  </div>

</div>

<!-- ── Restore confirm modal ────────────────────────────────── -->
<div class="modal-overlay" id="restoreModal" onclick="if(event.target===this)closeRestoreModal()">
  <div class="modal-box" style="max-width:360px;text-align:center">
    <div style="font-size:2.4rem;margin-bottom:10px">⚠️</div>
    <h5 style="margin-bottom:6px">Ripristinare i dati?</h5>
    <p style="color:var(--muted);font-size:.875rem;margin-bottom:18px">
      Tutti i dati attuali verranno <strong>sostituiti</strong> con quelli del backup.<br>
      L'operazione non può essere annullata.
    </p>
    <div style="display:flex;gap:10px;justify-content:center">
      <button class="btn btn-ghost" onclick="closeRestoreModal()">Annulla</button>
      <button class="btn btn-danger" onclick="doRestore()">Sì, ripristina</button>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
async function loadStats() {
  const d = await fetch('/api/stats').then(r => r.json());
  document.getElementById('stTx').textContent   = d.transactions   ?? '—';
  document.getElementById('stCat').textContent  = d.categories     ?? '—';
  document.getElementById('stRec').textContent  = d.recurring      ?? '—';
  document.getElementById('stGoal').textContent = d.goals          ?? '—';
  document.getElementById('stTag').textContent  = d.tags           ?? '—';
  document.getElementById('stFile').textContent = d.allegati_count ?? '—';
  const kb = d.db_size_bytes ? Math.round(d.db_size_bytes / 1024) : 0;
  document.getElementById('stDb').textContent   = kb < 1024 ? `${kb} KB` : `${(kb/1024).toFixed(1)} MB`;
}

async function downloadBackup() {
  const btn = document.querySelector('[onclick="downloadBackup()"]');
  const st  = document.getElementById('backupStatus');
  btn.disabled = true; btn.textContent = '⏳ Preparazione…'; st.textContent = '';

  try {
    const ts      = new Date().toISOString().slice(0,10).replace(/-/g,'');
    const defName = `ContabilitaFamily_backup_${ts}.zip`;

    if (window.pywebview && window.pywebview.api) {
      // Desktop (pywebview): mostra dialogo "Salva con nome" nativo
      const res = await window.pywebview.api.save_backup(defName);
      if (res.cancelled) {
        st.textContent = ''; // utente ha annullato
      } else if (res.success) {
        st.textContent = `✅ Salvato in: ${res.path}`;
        st.style.color = 'var(--income)';
        showToast('Backup salvato', 'success');
      } else {
        throw new Error(res.error || 'Errore');
      }
    } else {
      // Fallback browser: scarica via HTTP
      const r = await fetch('/api/backup');
      if (!r.ok) { const j = await r.json(); throw new Error(j.error || 'Errore'); }
      const cd    = r.headers.get('Content-Disposition') || '';
      const match = cd.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      const fname = match ? match[1].replace(/['"]/g,'') : defName;
      const blob  = await r.blob();
      const url   = URL.createObjectURL(blob);
      const a     = document.createElement('a'); a.href = url; a.download = fname;
      document.body.appendChild(a); a.click(); document.body.removeChild(a);
      URL.revokeObjectURL(url);
      st.textContent = `✅ Download avviato: ${fname}`;
      st.style.color = 'var(--income)';
    }
  } catch(e) {
    st.textContent = `❌ ${e.message}`;
    st.style.color = 'var(--expense)';
  } finally {
    btn.disabled = false; btn.textContent = '⬇ Scarica backup';
  }
}

function confirmRestore() {
  if (!document.getElementById('restoreFile').files[0]) {
    showToast('Seleziona un file ZIP', 'error'); return;
  }
  document.getElementById('restoreModal').classList.add('open');
}
function closeRestoreModal() {
  document.getElementById('restoreModal').classList.remove('open');
}

async function doRestore() {
  closeRestoreModal();
  const file = document.getElementById('restoreFile').files[0];
  const st   = document.getElementById('restoreStatus');
  const btn  = document.querySelector('[onclick="confirmRestore()"]');
  btn.disabled = true; st.textContent = '⏳ Ripristino in corso…'; st.style.color = 'var(--muted)';
  const fd = new FormData(); fd.append('file', file);
  try {
    const r = await fetch('/api/restore', { method: 'POST', body: fd });
    const j = await r.json();
    if (!r.ok || !j.success) throw new Error(j.error || 'Errore');
    st.textContent = `✅ ${j.message || 'Dati ripristinati con successo.'}`;
    st.style.color = 'var(--income)';
    showToast('Dati ripristinati', 'success');
    loadStats();
  } catch(e) {
    st.textContent = `❌ ${e.message}`;
    st.style.color = 'var(--expense)';
    showToast(e.message, 'error');
  } finally {
    btn.disabled = false;
  }
}

loadStats();
</script>
{% endblock %}
