let notificationEvents = [];

function boolInt(value) {
  return value ? 1 : 0;
}

function bytesToSize(bytes) {
  const n = Number(bytes || 0);
  if (n < 1024) return n + ' B';
  if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
  return (n / 1024 / 1024).toFixed(1) + ' MB';
}

function pill(status) {
  const s = String(status || 'unknown');
  const cls = ['sent','created'].includes(s) ? 'pill-green' : (['failed','error'].includes(s) ? 'pill-red' : 'pill-muted');
  return `<span class="pill ${cls}">${Pyrk.esc(s)}</span>`;
}


function syncMailDriverFields() {
  const driver = document.getElementById('mailDriver')?.value || 'log';
  const smtp = document.getElementById('smtpFields');
  if (smtp) smtp.hidden = driver !== 'smtp';
  const state = document.getElementById('emailSystemState');
  if (state) state.textContent = driver === 'smtp' ? 'SMTP' : (driver === 'mail' ? 'PHP mail' : 'Log only');
}


function renderEvents(events) {
  notificationEvents = events || [];
  const box = document.getElementById('notificationEventsGrid');
  box.innerHTML = notificationEvents.map(event => `
    <article class="notification-event-card" data-event-key="${Pyrk.esc(event.event_key)}">
      <div>
        <strong>${Pyrk.esc(event.label)}</strong>
        <small>${Pyrk.esc(event.event_key)}</small>
      </div>
      <label class="mini-switch"><input type="checkbox" data-field="enabled" ${Number(event.enabled) ? 'checked' : ''}><span>Enabled</span></label>
      <label class="mini-switch"><input type="checkbox" data-field="notify_admin" ${Number(event.notify_admin) ? 'checked' : ''}><span>Admin</span></label>
      <label class="mini-switch"><input type="checkbox" data-field="notify_user" ${Number(event.notify_user) ? 'checked' : ''}><span>Member</span></label>
    </article>`).join('');
}

function collectEvents() {
  return Array.from(document.querySelectorAll('.notification-event-card')).map(card => ({
    event_key: card.dataset.eventKey,
    enabled: boolInt(card.querySelector('[data-field="enabled"]').checked),
    notify_admin: boolInt(card.querySelector('[data-field="notify_admin"]').checked),
    notify_user: boolInt(card.querySelector('[data-field="notify_user"]').checked)
  }));
}

function renderLogs(logs) {
  const body = document.getElementById('notificationLogsBody');
  body.innerHTML = (logs || []).map(row => `<tr>
    <td><strong>${Pyrk.esc(row.event_key || 'manual')}</strong></td>
    <td>${Pyrk.esc(row.to_email || '—')}</td>
    <td>${Pyrk.esc(row.subject || '—')}</td>
    <td>${pill(row.status)}</td>
    <td>${Pyrk.esc(row.created_at || '')}</td>
  </tr>`).join('') || '<tr><td colspan="5" class="muted">No email activity yet.</td></tr>';
}

function renderBackups(backups) {
  const body = document.getElementById('backupLogsBody');
  body.innerHTML = (backups || []).map(row => `<tr>
    <td><strong>${Pyrk.esc(row.file_name || '—')}</strong><small>${Pyrk.esc(row.error_message || '')}</small></td>
    <td>${bytesToSize(row.size_bytes)}</td>
    <td>${pill(row.status)}</td>
    <td>${Pyrk.esc(row.method || '—')}</td>
    <td>${Pyrk.esc(row.created_at || '')}</td>
  </tr>`).join('') || '<tr><td colspan="5" class="muted">No backups yet.</td></tr>';

  const latest = (backups || [])[0];
  document.getElementById('latestBackupState').textContent = latest ? (latest.status || 'created') : 'None';
}

async function loadNotificationCenter() {
  const res = await Pyrk.get('notifications.php', {action: 'overview'});
  if (!res.ok) {
    Pyrk.toast('notificationSettingsMsg', res);
    return;
  }

  const s = res.data.settings || {};
  document.getElementById('emailNotificationsEnabled').checked = Number(s.email_notifications_enabled) === 1;
  document.getElementById('emailAdminRecipients').value = s.email_admin_recipients || '';
  document.getElementById('emailFooterText').value = s.email_footer_text || '';
  document.getElementById('mailDriver').value = s.mail_driver || 'log';
  document.getElementById('mailFromEmail').value = s.mail_from_email || '';
  document.getElementById('mailFromName').value = s.mail_from_name || 'Pyrk';
  document.getElementById('smtpHost').value = s.smtp_host || '';
  document.getElementById('smtpPort').value = s.smtp_port || 587;
  document.getElementById('smtpUsername').value = s.smtp_username || '';
  document.getElementById('smtpEncryption').value = s.smtp_encryption || 'tls';
  const pwNote = document.getElementById('smtpSavedPasswordNote');
  if (pwNote) pwNote.textContent = s.smtp_password_saved ? 'SMTP password is saved. Leave password blank to keep it.' : 'No SMTP password is saved yet.';
  syncMailDriverFields();
  document.getElementById('dbBackupEnabled').checked = Number(s.db_backup_enabled) === 1;
  document.getElementById('dbBackupRetentionDays').value = s.db_backup_retention_days || 30;
  document.getElementById('dbBackupPath').value = s.db_backup_path || '';

  document.getElementById('emailSystemState').textContent = Number(s.email_notifications_enabled) === 1 ? (s.mail_driver === 'smtp' ? 'SMTP' : (s.mail_driver === 'mail' ? 'PHP mail' : 'Log only')) : 'Off';
  document.getElementById('adminRecipientCount').textContent = String((res.data.admin_recipients || []).length);

  renderEvents(res.data.events || []);
  renderLogs(res.data.logs || []);
  renderBackups(res.data.backups || []);
}

async function saveNotificationSettings() {
  const payload = {
    action: 'save_settings',
    email_notifications_enabled: boolInt(document.getElementById('emailNotificationsEnabled').checked),
    email_admin_recipients: document.getElementById('emailAdminRecipients').value,
    email_footer_text: document.getElementById('emailFooterText').value,
    mail_driver: document.getElementById('mailDriver').value,
    mail_from_email: document.getElementById('mailFromEmail').value,
    mail_from_name: document.getElementById('mailFromName').value,
    smtp_host: document.getElementById('smtpHost').value,
    smtp_port: Number(document.getElementById('smtpPort').value || 587),
    smtp_username: document.getElementById('smtpUsername').value,
    smtp_password: document.getElementById('smtpPassword').value,
    smtp_encryption: document.getElementById('smtpEncryption').value,
    db_backup_enabled: boolInt(document.getElementById('dbBackupEnabled').checked),
    db_backup_retention_days: Number(document.getElementById('dbBackupRetentionDays').value || 30),
    db_backup_path: document.getElementById('dbBackupPath').value,
    events: collectEvents()
  };
  const res = await Pyrk.post('notifications.php', payload);
  Pyrk.toast('notificationSettingsMsg', res);
  if (res.ok) {
    const pw = document.getElementById('smtpPassword');
    if (pw) pw.value = '';
    await loadNotificationCenter();
  }
}

async function testEmail() {
  const email = prompt('Send test email to:', '');
  if (email === null) return;
  const res = await Pyrk.post('notifications.php', {action: 'test_email', email});
  const result = res.data?.result || {};
  let details = res.message || (res.ok ? 'Test processed' : 'Test failed');
  if (result.error) details += `\n\nError: ${result.error}`;
  alert(details);
  await loadNotificationCenter();
}

async function createBackup() {
  if (!confirm('Create a database backup now? This may take a few seconds.')) return;
  const btn = document.getElementById('createBackupBtn');
  btn.disabled = true;
  btn.textContent = 'Creating backup...';
  const res = await Pyrk.post('notifications.php', {action: 'create_backup'});
  alert(res.message || (res.ok ? 'Backup created' : 'Backup failed'));
  btn.disabled = false;
  btn.textContent = 'Create DB backup';
  await loadNotificationCenter();
}

document.getElementById('mailDriver')?.addEventListener('change', syncMailDriverFields);
document.getElementById('saveNotificationSettingsBtn').addEventListener('click', saveNotificationSettings);
document.getElementById('testEmailBtn').addEventListener('click', testEmail);
document.getElementById('createBackupBtn').addEventListener('click', createBackup);
document.getElementById('enableAllEventsBtn').addEventListener('click', () => {
  document.querySelectorAll('#notificationEventsGrid input[type="checkbox"]').forEach(i => i.checked = true);
});
document.getElementById('disableAllEventsBtn').addEventListener('click', () => {
  document.querySelectorAll('#notificationEventsGrid [data-field="enabled"]').forEach(i => i.checked = false);
});

loadNotificationCenter();
