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

router.get('/', (req, res) => {
  const db = getDb();
  const { type, status, client_id } = req.query;
  let sql = `SELECT e.*, c.name as client_name
    FROM engagements e JOIN clients c ON c.id = e.client_id WHERE 1=1`;
  const params = [];
  if (type) { sql += ' AND e.type = ?'; params.push(type); }
  if (status) { sql += ' AND e.status = ?'; params.push(status); }
  if (client_id) { sql += ' AND e.client_id = ?'; params.push(client_id); }
  sql += ' ORDER BY e.updated_at DESC';
  const engagements = db.prepare(sql).all(...params);
  res.render('engagement-list', { engagements, filters: req.query });
});

router.get('/new', (req, res) => {
  const db = getDb();
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  res.render('engagement-form', { engagement: null, clients, selected: req.query.client_id || null, error: null });
});

router.get('/new/:clientId', (req, res) => {
  const db = getDb();
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  const selected = req.params.clientId;
  res.render('engagement-form', { engagement: null, clients, selected, error: null });
});

router.post('/new', (req, res) => {
  const db = getDb();
  const { client_id, type, title, description, status, start_date, end_date } = req.body;
  if (!client_id || !title || !title.trim()) {
    const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
    return res.render('engagement-form', { engagement: null, clients, selected: client_id || null, error: 'Titel is verplicht' });
  }
  const result = db.prepare(`INSERT INTO engagements (client_id, type, title, description, status, start_date, end_date)
    VALUES (?, ?, ?, ?, ?, ?, ?)`).run(client_id, type, title, description, status || 'planned', start_date, end_date);
  res.redirect('/engagements/' + result.lastInsertRowid);
});

router.get('/:id', (req, res) => {
  const db = getDb();
  const engagement = db.prepare(`
    SELECT e.*, c.name as client_name
    FROM engagements e
    JOIN clients c ON c.id = e.client_id
    WHERE e.id = ?
  `).get(req.params.id);
  if (!engagement) return res.redirect('/engagements');
  const tasks = db.prepare('SELECT * FROM tasks WHERE engagement_id = ? ORDER BY created_at DESC').all(req.params.id);
  res.render('engagement-detail', { engagement, tasks });
});

router.get('/:id/edit', (req, res) => {
  const db = getDb();
  const engagement = db.prepare('SELECT * FROM engagements WHERE id = ?').get(req.params.id);
  if (!engagement) return res.redirect('/engagements');
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  res.render('engagement-form', { engagement, clients, selected: engagement.client_id, error: null });
});

router.post('/:id/edit', (req, res) => {
  const db = getDb();
  const { client_id, type, title, description, status, start_date, end_date, outcome } = req.body;
  db.prepare(`UPDATE engagements SET client_id=?, type=?, title=?, description=?, status=?, start_date=?, end_date=?, outcome=?, updated_at=datetime('now') WHERE id=?`)
    .run(client_id, type, title, description, status, start_date, end_date, outcome, req.params.id);
  res.redirect('/engagements/' + req.params.id);
});

router.post('/:id/delete', (req, res) => {
  const db = getDb();
  db.prepare('DELETE FROM engagements WHERE id = ?').run(req.params.id);
  res.redirect('/engagements');
});

router.post('/:id/status', (req, res) => {
  const db = getDb();
  db.prepare("UPDATE engagements SET status=?, updated_at=datetime('now') WHERE id=?")
    .run(req.body.status, req.params.id);
  res.redirect('/engagements/' + req.params.id);
});

module.exports = router;
