const express = require('express');
const router = express.Router();
const { getSettings, updateSetting, getDb } = require('../db');

const ALL_ICONS = [
  { key: 'layout-dashboard', label: 'Dashboard' },
  { key: 'users', label: 'Cliënten' },
  { key: 'briefcase', label: 'Engagements' },
  { key: 'server', label: 'Infrastructuur' },
  { key: 'check-circle', label: 'Taken' },
  { key: 'lightbulb', label: 'Advies' },
  { key: 'clock', label: 'Activiteit' },
  { key: 'eye', label: 'Overzicht (client)' },
  { key: 'phone', label: 'Contact' },
  { key: 'file-text', label: 'Designs' },
  { key: 'edit-3', label: 'Notities' },
  { key: 'folder', label: 'Bestanden' },
  { key: 'clipboard-list', label: 'Assessments' }
];

router.get('/', (req, res) => {
  const settings = getSettings();
  res.render('settings', {
    settings,
    icons: ALL_ICONS,
    user: { username: req.session.username },
    saved: req.query.saved === '1'
  });
});

router.post('/', (req, res) => {
  const { brand_name, language, theme, default_page, auto_refresh, items_per_page, debug_mode } = req.body;

  updateSetting('brand_name', brand_name || 'Mek-Tech Consulting');
  updateSetting('language', language || 'nl');
  updateSetting('theme', theme || 'dark');
  updateSetting('default_page', default_page || '/');
  updateSetting('auto_refresh', auto_refresh || '0');
  updateSetting('items_per_page', items_per_page || '50');
  updateSetting('debug_mode', debug_mode === '1' ? '1' : '0');

  const icon_colors = {};
  ALL_ICONS.forEach(icon => {
    const val = req.body['color_' + icon.key.replace(/-/g, '_')];
    if (val) icon_colors[icon.key] = val;
  });
  updateSetting('icon_colors', icon_colors);

  res.redirect('/settings?saved=1');
});

router.post('/reset', (req, res) => {
  const { DEFAULTS } = require('../db');
  const d = getDb();
  d.prepare('DELETE FROM app_settings').run();
  res.redirect('/settings');
});

module.exports = router;
