/**
 * ==========================================================
 * Smart Attendance System
 * Attendance Service
 * ==========================================================
 */

const AttendanceModel = require("./model");
const time = require("../../utils/time");

class AttendanceService {

    /**
     * ======================================================
     * Mark Attendance
     * ======================================================
     */

    static async markAttendance(data) {

        const {

            face_student_id,

            nfc_uid,

            device_id,

            ip_address,

            face_image = null

        } = data;

        // -----------------------------
        // Face Verification
        // -----------------------------

        const student = await AttendanceModel.getStudentById(
            face_student_id
        );

        if (!student.length) {

            return {

                success: false,

                message: "Student not found."

            };

        }

        // -----------------------------
        // NFC Verification
        // -----------------------------

        const nfcStudent =
            await AttendanceModel.getStudentByNFC(
                nfc_uid
            );

        if (!nfcStudent.length) {

            return {

                success: false,

                message: "NFC Card not registered."

            };

        }

        if (student[0].id !== nfcStudent[0].id) {

            return {

                success: false,

                message: "Face and NFC mismatch."

            };

        }

        // -----------------------------
        // Attendance Date
        // -----------------------------

        const today =
            new Date().toISOString().split("T")[0];

        // -----------------------------
        // Already Marked?
        // -----------------------------

        const already =
            await AttendanceModel.checkTodayAttendance(

                student[0].id,

                today

            );

        if (already.length) {

            return {

                success: false,

                message: "Attendance already marked."

            };

        }

        // -----------------------------
        // Time Validation
        // -----------------------------

        if (!time.hasStarted()) {

            return {

                success: false,

                message: "Attendance not started."

            };

        }

        if (time.hasEnded()) {

            return {

                success: false,

                message: "Attendance closed."

            };

        }

        const now = new Date();

        const status =
            time.isLate()
                ? "Late"
                : "Present";

        // -----------------------------
        // Save
        // -----------------------------

        await AttendanceModel.markAttendance({

            student_id: student[0].id,

            attendance_date: today,

            check_in: now,

            face_verified: 1,

            nfc_verified: 1,

            device_id,

            ip_address,

            face_image,

            status,

            remarks: null

        });

        return {

            success: true,

            message: "Attendance marked successfully.",

            data: {

                student: student[0],

                status

            }

        };

    }

    /**
     * ======================================================
     * Checkout
     * ======================================================
     */

    static async checkout(studentId) {

        const today =
            new Date().toISOString().split("T")[0];

        const now = new Date();

        const attendance =
            await AttendanceModel.checkTodayAttendance(

                studentId,

                today

            );

        if (!attendance.length) {

            return {

                success: false,

                message: "Check-in not found."

            };

        }

        if (attendance[0].check_out) {

            return {

                success: false,

                message: "Already checked out."

            };

        }

        await AttendanceModel.checkout(

            studentId,

            today,

            now

        );

        return {

            success: true,

            message: "Checkout successful."

        };

    }

    /**
     * ======================================================
     * Today's Attendance
     * ======================================================
     */

    static async todayAttendance() {

        const today =
            new Date().toISOString().split("T")[0];

        return await AttendanceModel.getTodayAttendance(
            today
        );

    }

    /**
     * ======================================================
     * Student History
     * ======================================================
     */

    static async studentHistory(studentId) {

        return await AttendanceModel.getStudentAttendance(
            studentId
        );

    }

    /**
     * ======================================================
     * Monthly Report
     * ======================================================
     */

    static async monthlyReport(year, month) {

        return await AttendanceModel.getMonthlyAttendance(

            year,

            month

        );

    }

    /**
     * ======================================================
     * Dashboard Statistics
     * ======================================================
     */

    static async statistics() {

        const today =
            new Date().toISOString().split("T")[0];

        return await AttendanceModel.getTodayStatistics(
            today
        );

    }

}

module.exports = AttendanceService;