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

// Middleware to check if learner exists
function requireLearner(req, res, next) {
  if (!req.session.learnerId) {
    return res.redirect('/');
  }
  next();
}

// Home page
router.get('/', (req, res) => {
  res.render('index');
});

// Start training - enter name and agency
router.get('/start', async (req, res) => {
  const agencies = await db.getAllAgencies();
  res.render('start', { agencies });
});

router.post('/start', async (req, res) => {
  const { name, agencyCode, email } = req.body;

  if (!name || !agencyCode) {
    const agencies = await db.getAllAgencies();
    return res.status(400).render('start', {
      agencies,
      error: 'Please enter your name and select an agency.'
    });
  }

  const agency = await db.getAgencyByCode(agencyCode);
  if (!agency) {
    const agencies = await db.getAllAgencies();
    return res.status(400).render('start', {
      agencies,
      error: 'Invalid agency code.'
    });
  }

  // Create learner
  const learnerId = await db.createLearner(agency.id, name, email || null);
  req.session.learnerId = learnerId;
  req.session.completedModules = [];
  req.session.examStarted = false;

  res.redirect('/modules/1');
});

// Module view
router.get('/modules/:moduleNum', requireLearner, async (req, res) => {
  const moduleNum = parseInt(req.params.moduleNum);
  const learner = await db.getLearner(req.session.learnerId);
  const completedModules = await db.getCompletedModules(req.session.learnerId);

  // Check if module is valid
  if (moduleNum < 1 || moduleNum > modules.length) {
    return res.status(404).render('error', { message: 'Module not found.' });
  }

  const module = modules[moduleNum - 1];
  const isCompleted = completedModules.includes(moduleNum);
  const progress = Math.round((completedModules.length / modules.length) * 100);

  res.render('modules/module', {
    module,
    moduleNum,
    isCompleted,
    completedModules,
    progress,
    totalModules: modules.length,
    learnerName: learner.name
  });
});

// Submit module quiz
router.post('/modules/:moduleNum/submit', requireLearner, async (req, res) => {
  const moduleNum = parseInt(req.params.moduleNum);

  if (moduleNum < 1 || moduleNum > modules.length) {
    return res.status(404).json({ error: 'Module not found.' });
  }

  const module = modules[moduleNum - 1];
  const answers = req.body.answers || {};
  let correct = 0;

  // Score answers
  module.questions.forEach((question, index) => {
    const userAnswer = answers[index] === 'true' || answers[index] === true;
    if (userAnswer === question.answer) {
      correct++;
    }
  });

  const score = Math.round((correct / module.questions.length) * 100);
  const passed = score >= 70;

  if (passed) {
    await db.completeModule(req.session.learnerId, moduleNum);
  }

  res.json({
    passed,
    score,
    correct,
    total: module.questions.length
  });
});

// Module completion page
router.get('/modules/:moduleNum/complete', requireLearner, async (req, res) => {
  const moduleNum = parseInt(req.params.moduleNum);
  const learner = await db.getLearner(req.session.learnerId);
  const completedModules = await db.getCompletedModules(req.session.learnerId);
  const module = modules[moduleNum - 1];

  const progress = Math.round((completedModules.length / modules.length) * 100);
  const nextModuleNum = moduleNum < modules.length ? moduleNum + 1 : null;
  const canStartExam = completedModules.length === modules.length;

  res.render('modules/complete', {
    module,
    moduleNum,
    nextModuleNum,
    canStartExam,
    progress,
    completedModules,
    totalModules: modules.length,
    learnerName: learner.name
  });
});

module.exports = router;
