"use strict";
const { Router } = require("express");
const { query, insert, update } = require("../db");
const { getSession } = require("../auth");
const router = Router();

router.get("/attendance", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const { classId, date } = req.query;
  if (!classId || !date) return res.status(400).json({ error: "classId and date required" });
  const allStudents = await query("SELECT * FROM students WHERE class_id=?", [classId]);
  const rows = await query("SELECT * FROM attendance WHERE class_id=? AND date=?", [classId, date]);
  const attMap = new Map(rows.map(r => [r.student_id, r]));
  res.json(allStudents.map(s => ({
    studentId: s.id, studentName: `${s.first_name} ${s.last_name}`, studentCode: s.student_id,
    status: attMap.get(s.id)?.status ?? "absent", attendanceId: attMap.get(s.id)?.id ?? null,
  })));
});

router.get("/attendance/summary", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const { studentId } = req.query;
  if (!studentId) return res.status(400).json({ error: "studentId required" });
  const rows = await query("SELECT * FROM attendance WHERE student_id=? ORDER BY date DESC", [studentId]);
  const total = rows.length;
  const present = rows.filter(r => r.status === "present").length;
  const absent = rows.filter(r => r.status === "absent").length;
  const late = rows.filter(r => r.status === "late").length;
  const excused = rows.filter(r => r.status === "excused").length;
  res.json({ total, present, absent, late, excused, percentage: total > 0 ? Math.round((present / total) * 100) : 0, records: rows.slice(0, 30) });
});

router.post("/attendance", async (req, res) => {
  const session = getSession(req);
  if (!session || (session.role !== "admin" && session.role !== "teacher")) return res.status(403).json({ error: "Staff only" });
  const { classId, date, records } = req.body;
  if (!classId || !date || !Array.isArray(records)) return res.status(400).json({ error: "classId, date, records required" });
  await query("DELETE FROM attendance WHERE class_id=? AND date=?", [classId, date]);
  for (const r of records) {
    await query("INSERT INTO attendance (class_id, student_id, date, status, marked_by) VALUES (?,?,?,?,?)",
      [classId, r.studentId, date, r.status, session.displayName]);
  }
  res.json({ saved: records.length });
});

module.exports = router;
