const express = require('express');
const router = express.Router();
const db = require('../db');

router.get('/', async (req, res) => {
  try {
    const rows = await db.query('SELECT setting_key, setting_value, setting_type, category FROM settings');
    const out = {};
    for (const r of rows) out[r.setting_key] = r.setting_value;
    res.json(out);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/:id', async (req, res) => {
  if (!req.session.user_id) return res.status(401).json({ error: 'Unauthorized' });
  // In a real app we'd check if role == Admin or owner.
  
  const value = req.body.value;
  if (value === undefined) return res.status(400).json({ error: 'value required' });
  
  try {
    await db.query('INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?', [req.params.id, value, value]);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
