const router = require('express').Router({ mergeParams: true });
const auth   = require('../middleware/auth');
const db     = require('../lib/db');

router.use(auth);

// ── Main dashboard ────────────────────────────────────────────────────────────
router.get('/', (req, res) => {
  res.render('dashboard/index', { title: 'Dashboard' });
});

// ── Instagram hub (3 cards) ───────────────────────────────────────────────────
router.get('/instagram', (req, res) => {
  const user = db.prepare('SELECT * FROM users WHERE id=?').get(req.session.userId);
  res.render('dashboard/instagram', {
    title:   'Instagram',
    igAppId: process.env.IG_APP_ID || '',
    botUser: user,
  });
});

// ── Instagram creator (igcreator) ─────────────────────────────────────────────
router.get('/instagram/creator', (_req, res) => {
  res.render('dashboard/instagram-creator', {
    title:   'IG Creator',
    igAppId: process.env.IG_APP_ID || '',
  });
});

// ── Save bot settings ─────────────────────────────────────────────────────────
router.post('/instagram/bot-settings', (req, res) => {
  const { type, enabled, persona } = req.body;
  if (type === 'messages') {
    db.prepare('UPDATE users SET bot_msg_enabled=?, bot_msg_persona=? WHERE id=?')
      .run(enabled === '1' ? 1 : 0, persona || null, req.session.userId);
  } else if (type === 'comments') {
    db.prepare('UPDATE users SET bot_cmt_enabled=?, bot_cmt_persona=? WHERE id=?')
      .run(enabled === '1' ? 1 : 0, persona || null, req.session.userId);
  }
  res.json({ success: true });
});

// ── Connect / disconnect IG ───────────────────────────────────────────────────
router.get('/ig-disconnect', (req, res) => {
  db.prepare('UPDATE users SET ig_user_id=NULL, ig_token=NULL, ig_username=NULL WHERE id=?').run(req.user.id);
  req.flash('success', 'Instagram disconnected.');
  res.redirect(`/${req.params.lang}/dashboard/instagram`);
});

// ── Google Business hub ───────────────────────────────────────────────────────
router.get('/google', (req, res) => {
  const user = db.prepare('SELECT * FROM users WHERE id=?').get(req.session.userId);
  res.render('dashboard/google', { title: 'Google Business', gbUser: user });
});

module.exports = router;
