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

function initReportsTable() {
  const db = getDb();
  db.exec(`
    CREATE TABLE IF NOT EXISTS reports (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      report_type TEXT DEFAULT 'client_summary',
      client_id INTEGER REFERENCES clients(id) ON DELETE SET NULL,
      project_id INTEGER,
      config TEXT DEFAULT '{}',
      created_at TEXT DEFAULT (datetime('now'))
    )
  `);
}

router.get('/', (req, res) => {
  initReportsTable();
  const db = getDb();
  const tab = req.query.tab || 'builder';
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  let projects = [];
  try { projects = db.prepare('SELECT id, name FROM projects ORDER BY name').all(); } catch (e) {}
  const savedReports = db.prepare(`
    SELECT r.*, c.name as client_name FROM reports r
    LEFT JOIN clients c ON c.id = r.client_id ORDER BY r.created_at DESC LIMIT 20
  `).all();
  res.render('reports', { tab, clients, projects, savedReports });
});

router.post('/generate', async (req, res) => {
  const { report_type, client_id, project_id, date_from, date_to, format } = req.body;
  const db = getDb();
  let data = [];

  if (report_type === 'client_summary') {
    data = db.prepare(`
      SELECT c.*,
        (SELECT COUNT(*) FROM engagements e WHERE e.client_id = c.id) as engagement_count,
        (SELECT COALESCE(SUM(i.total),0) FROM invoices i WHERE i.client_id = c.id) as total_revenue
      FROM clients c WHERE (? = '' OR c.id = ?)
    `).all(client_id || '', client_id || '');
  } else if (report_type === 'financial') {
    data = db.prepare(`
      SELECT i.*, c.name as client_name FROM invoices i
      LEFT JOIN clients c ON c.id = i.client_id
      WHERE (? = '' OR i.created_at >= ?) AND (? = '' OR i.created_at <= ?)
    `).all(date_from || '', date_from || '', date_to || '', date_to || '');
  }

  if (format === 'pdf' || format === 'excel') {
    return res.json({ data, note: 'Export naar PDF/Excel — installeer pdfkit/exceljs of gebruik JSON' });
  }
  res.json({ data });
});

router.post('/save', (req, res) => {
  initReportsTable();
  const db = getDb();
  const { name, report_type, client_id, project_id, config } = req.body;
  db.prepare(`INSERT INTO reports (name, report_type, client_id, project_id, config) VALUES (?, ?, ?, ?, ?)`)
    .run(name, report_type, client_id, project_id, JSON.stringify(config || {}));
  res.redirect('/reports');
});

module.exports = router;
