const express = require('express');
const router = express.Router();
const { getDB } = require('../config/database');
const { auth } = require('../middleware/auth');
const { ok, logActivity } = require('../helpers/response');

router.get('/', async (req, res, next) => {
  try {
    const db = getDB();
    const [rows] = await db.query('SELECT `key`, value FROM settings');
    const settings = Object.fromEntries(rows.map(r => [r.key, r.value]));
    ok(res, settings);
  } catch (e) { next(e); }
});

// Whitelist — hanya key ini yang boleh diubah via API
const ALLOWED_KEYS = [
  'site_name', 'site_desc', 'site_logo',
  'contact_email', 'contact_phone', 'address',
  'prayer_city', 'prayer_country', 'prayer_method',
  'feature_konsultasi', 'feature_newsletter', 'feature_donasi',
  'maintenance_mode',
];

router.put('/', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    for (const [k, v] of Object.entries(req.body)) {
      if (!ALLOWED_KEYS.includes(k)) continue; // skip key yang tidak diizinkan
      await db.query('INSERT INTO settings (`key`, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE value = ?, updated_at = CURRENT_TIMESTAMP', [k, v, v]);
    }
    await logActivity('INFO', 'Pengaturan diperbarui', req.user.id, req.ip);
    ok(res, null, 'Pengaturan berhasil disimpan');
  } catch (e) { next(e); }
});

router.post('/logo', auth(['Admin']), require('../config/multer').upload.single('logo'), async (req, res, next) => {
  try {
    if (!req.file) return require('../helpers/response').err(res, 'File logo wajib diupload');
    const db = getDB();
    const logoUrl = `/uploads/${req.file.filename}`;
    await db.query('INSERT INTO settings (`key`, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE value = ?, updated_at = CURRENT_TIMESTAMP', ['site_logo', logoUrl, logoUrl]);
    await logActivity('INFO', 'Logo situs diperbarui', req.user.id, req.ip);
    ok(res, { site_logo: logoUrl }, 'Logo berhasil diperbarui');
  } catch (e) { next(e); }
});

module.exports = router;
