const express = require('express');
const router = express.Router();
const db = require('../db/database');
const { requireAdmin } = require('../middleware/auth');

router.get('/', requireAdmin, async (req, res) => {
  try {
    const [rows] = await db.query("SELECT key_name, value FROM settings WHERE key_name != 'panel_password'");
    const settings = {};
    rows.forEach(r => settings[r.key_name] = r.value);
    
    const [admins] = await db.query('SELECT panel_url, panel_username FROM admins LIMIT 1');
    if (admins.length > 0) {
      settings.panel_url = admins[0].panel_url;
      settings.panel_username = admins[0].panel_username;
    }
    
    res.json(settings);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch settings' });
  }
});

router.put('/', requireAdmin, async (req, res) => {
  try {
    const { site_title, support_link } = req.body;
    
    for (const [key, value] of Object.entries({ site_title, support_link })) {
      if (value !== undefined) {
        await db.query(
          'INSERT INTO settings (key_name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?',
          [key, value, value]
        );
      }
    }
    
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to update settings' });
  }
});

module.exports = router;
