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

router.get('/', (req, res) => {
  const db = getDb();
  const events = db.prepare(`
    SELECT e.*, c.name as client_name
    FROM calendar_events e
    LEFT JOIN clients c ON c.id = e.client_id
    WHERE e.user_id = ? OR e.user_id IS NULL
    ORDER BY e.start_time ASC
  `).all(req.session.userId);
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  const engagements = db.prepare('SELECT id, title FROM engagements ORDER BY title').all();
  res.render('calendar-list', { events, clients, engagements });
});

router.get('/api/events', (req, res) => {
  const db = getDb();
  const events = db.prepare(`
    SELECT e.*, c.name as client_name
    FROM calendar_events e
    LEFT JOIN clients c ON c.id = e.client_id
    WHERE (e.user_id = ? OR e.user_id IS NULL)
    ORDER BY e.start_time ASC
  `).all(req.session.userId);
  res.json(events.map(e => ({
    id: e.id,
    title: e.title,
    start: e.start_time,
    end: e.end_time,
    allDay: !!e.all_day,
    color: e.color,
    extendedProps: { description: e.description, client_name: e.client_name, event_type: e.event_type }
  })));
});

router.post('/new', (req, res) => {
  const db = getDb();
  const { title, description, client_id, engagement_id, event_type, start_time, end_time, all_day, color } = req.body;
  if (!title || !start_time) return res.redirect('/calendar');
  db.prepare('INSERT INTO calendar_events (user_id, client_id, engagement_id, title, description, event_type, start_time, end_time, all_day, color) VALUES (?,?,?,?,?,?,?,?,?,?)')
    .run(req.session.userId, client_id || null, engagement_id || null, title, description || '', event_type || 'meeting', start_time, end_time || start_time, all_day === '1' ? 1 : 0, color || '#58a6ff');
  logAudit(req.session.userId, req.session.username, 'event_created', 'calendar_event', null, `Event "${title}" aangemaakt`);
  res.redirect('/calendar');
});

router.post('/:id/edit', (req, res) => {
  const db = getDb();
  const { title, description, client_id, engagement_id, event_type, start_time, end_time, all_day, color } = req.body;
  if (!title) return res.redirect('/calendar');
  db.prepare("UPDATE calendar_events SET title=?, description=?, client_id=?, engagement_id=?, event_type=?, start_time=?, end_time=?, all_day=?, color=?, updated_at=datetime('now') WHERE id=?")
    .run(title, description, client_id || null, engagement_id || null, event_type, start_time, end_time, all_day === '1' ? 1 : 0, color, req.params.id);
  res.redirect('/calendar');
});

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

module.exports = router;
