// controllers/dashboardController.js

// We no longer need the raw pool; all logic is in models.
const Attendance = require("../models/attendanceModel");
const Student = require("../models/studentModel");

const getDashboardStats = async (req, res) => {
  // The institution_id is now retrieved from the authenticated user
  const { institution_id } = req.user;

  try {
    // We can get these stats with two separate, simple model calls.
    const totalStudents = await Student.countAll(institution_id);
    const presentCount = await Attendance.getTodaysUniqueCount(institution_id);

    const absentCount = Math.max(0, totalStudents - presentCount);

    res.status(200).json({
      presentCount,
      absentCount,
      totalStudents,
    });
  } catch (err) {
    console.error("Error in getDashboardStats:", err);
    res.status(500).json({ message: "Server error while fetching dashboard stats." });
  }
};

const getRecentLogs = async (req, res) => {
  const { institution_id } = req.user;
  const limit = parseInt(req.query.limit, 10) || 5;

  try {
    // The model now handles the complex query
    const logs = await Attendance.getRecentLogs(institution_id, limit);
    res.status(200).json(logs);
  } catch (err) {
    console.error("Error in getRecentLogs:", err);
    res.status(500).json({ message: "Server error while fetching recent logs." });
  }
};

module.exports = {
  getDashboardStats,
  getRecentLogs,
};