const db = require("../config/db");
const path = require("path");
/* const fileService = require("../services/file.service"); */
const profileFileService = require("../services/profile_file.service");
const imageService = require("../services/image.service");


// =====================================================
// Register Student
// =====================================================
exports.registerStudent = async (req, res) => {
    try {
        const {
            student_id,
            full_name,
            class_name,
            department,
            email,
            phone
        } = req.body;

        // Validation
        if (!student_id || !full_name || !class_name || !department) {
            return res.status(400).json({
                success: false,
                message: "Required fields are missing."
            });
        }

        // Duplicate Student ID check
        const [rows] = await db.query("SELECT id FROM students WHERE student_id=?", [student_id]);

        if (rows.length > 0) {
            return res.status(409).json({
                success: false,
                message: "Student ID already exists."
            });
        }

        // Insert Student
        const sql = `
            INSERT INTO students 
            (student_id, full_name, class_name, department, email, phone) 
            VALUES (?, ?, ?, ?, ?, ?)
        `;

        const [result] = await db.query(sql, [
            student_id,
            full_name,
            class_name,
            department,
            email || null,
            phone || null
        ]);

        res.status(201).json({
            success: true,
            message: "Student Registered Successfully",
            studentId: result.insertId
        });

    } catch (error) {
        console.error(error);
        res.status(500).json({
            success: false,
            message: error.message || "An error occurred during registration."
        });
    }
};

// =====================================================
// Upload Student Profile Photo
// =====================================================
// =====================================================
// Upload Student Profile Photo
// =====================================================

exports.uploadPhoto = async (req, res) => {

    try {

        const studentId = req.params.id;

        if (!req.file) {

            return res.status(400).json({

                success: false,

                message: "No image uploaded."

            });

        }

        // ---------------------------------------
        // Check Student
        // ---------------------------------------

        const [rows] = await db.query(

            "SELECT id FROM students WHERE id=?",

            [studentId]

        );

        if (rows.length === 0) {

            return res.status(404).json({

                success: false,

                message: "Student not found."

            });

        }

        // ---------------------------------------
        // Image Extension
        // ---------------------------------------

        const extension =

            path.extname(req.file.originalname)

            || ".jpg";

        // ---------------------------------------
        // Save Image
        // ---------------------------------------

        const absolutePath =
profileFileService.getProfileAbsolutePath(studentId);

await imageService.saveStudentProfile(
    req.file.buffer,
    absolutePath
    );
    console.log(req.file);

const relativePath =
profileFileService.getProfileRelativePath(studentId);

await db.query(
    "UPDATE students SET photo=? WHERE id=?",
    [
        relativePath,
        studentId
    ]
);

        // ---------------------------------------
        // Save Database
        // ---------------------------------------

       

        // ---------------------------------------
        // Public URL
        // ---------------------------------------

        const photoURL =

            profileFileService.getProfileURL(

                req,

                relativePath

            );

        // ---------------------------------------
        // Response
        // ---------------------------------------

        res.json({

            success: true,

            message: "Profile Photo Uploaded Successfully",

            photo: relativePath,

            photo_url: photoURL

        });

    }

    catch (error) {

        console.error(error);

        res.status(500).json({

            success: false,

            message: error.message

        });

    }

};

// =====================================================
// Register NFC Card
// =====================================================
exports.registerNFC = async (req, res) => {
    try {
        const studentId = req.params.id;
        const { nfc_uid } = req.body;

        // Validation
        if (!nfc_uid || nfc_uid.trim() === "") {
            return res.status(400).json({
                success: false,
                message: "NFC UID is required."
            });
        }

        // Check Student Exists
        const [studentRows] = await db.query("SELECT id FROM students WHERE id=?", [studentId]);

        if (studentRows.length === 0) {
            return res.status(404).json({
                success: false,
                message: "Student not found."
            });
        }

        // Check Duplicate NFC
        const [nfcRows] = await db.query("SELECT id FROM students WHERE nfc_uid=? AND id<>?", [nfc_uid, studentId]);

        if (nfcRows.length > 0) {
            return res.status(409).json({
                success: false,
                message: "This NFC card is already assigned to another student."
            });
        }

        // Update NFC UID
        await db.query("UPDATE students SET nfc_uid=? WHERE id=?", [nfc_uid, studentId]);

        res.json({
            success: true,
            message: "NFC Card Registered Successfully.",
            nfc_uid
        });

    } catch (error) {
        console.error(error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

// =====================================================
// Get Student By NFC UID
// =====================================================
// =====================================================
// Get Student By NFC UID
// =====================================================
exports.getStudentByNFC = async (req, res) => {

    try {

        const uid = req.params.uid;

        if (!uid) {

            return res.status(400).json({

                success: false,

                message: "NFC UID is required."

            });

        }

        const [rows] = await db.query(

            `

SELECT

id,

student_id,

full_name,

class_name,

department,

email,

phone,

photo,

nfc_uid,

face_trained,

training_status,

trained_images,

embedding_dimension,

ai_model,

face_trained_at

FROM students

WHERE nfc_uid=?

`,

            [uid]

        );

        if (rows.length === 0) {

            return res.status(404).json({

                success: false,

                message: "NFC Card is not registered."

            });

        }

        const student = {

            ...rows[0],

            photo_url: profileFileService.getProfileURL(

                req,

                rows[0].photo

            )

        };

        res.json({

            success: true,

            student

        });

    }

    catch (error) {

        console.error(error);

        res.status(500).json({

            success: false,

            message: error.message

        });

    }

};

// =====================================================
// Get All Students
// =====================================================
// =====================================================
// Get All Students
// =====================================================
exports.getStudents = async (req, res) => {

    try {

        const sql = `

SELECT

id,

student_id,

full_name,

class_name,

department,

email,

phone,

photo,

nfc_uid,

face_trained,

training_status,

trained_images,

embedding_dimension,

ai_model,

face_trained_at,

created_at

FROM students

ORDER BY id DESC

`;

        const [rows] = await db.query(sql);

        const students = rows.map(student => ({

            ...student,

            photo_url: profileFileService.getProfileURL(

                req,

                student.photo

            )

        }));

        res.json({

            success: true,

            total: students.length,

            students

        });

    }

    catch (error) {

        console.error(error);

        res.status(500).json({

            success: false,

            message: error.message

        });

    }

};

// =====================================================
// Get Student By ID
// =====================================================
// =====================================================
// Get Student By ID
// =====================================================
exports.getStudent = async (req, res) => {

    try {

        const id = req.params.id;

        const [rows] = await db.query(

            `

SELECT

id,

student_id,

full_name,

class_name,

department,

email,

phone,

photo,

nfc_uid,

face_trained,

training_status,

trained_images,

embedding_dimension,

ai_model,

face_trained_at,

created_at

FROM students

WHERE id=?

`,

            [id]

        );

        if (rows.length === 0) {

            return res.status(404).json({

                success: false,

                message: "Student not found."

            });

        }

        const student = {

            ...rows[0],

            photo_url: profileFileService.getProfileURL(

                req,

                rows[0].photo

            )

        };

        res.json({

            success: true,

            student

        });

    }

    catch (error) {

        console.error(error);

        res.status(500).json({

            success: false,

            message: error.message

        });

    }

};
// =====================================================
// Update Student
// =====================================================
exports.updateStudent = async (req, res) => {
    try {
        const id = req.params.id;
        const { full_name, class_name, department, email, phone } = req.body;

        const [result] = await db.query(
            `UPDATE students 
             SET full_name=?, class_name=?, department=?, email=?, phone=? 
             WHERE id=?`, 
            [full_name, class_name, department, email, phone, id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                message: "Student not found."
            });
        }

        res.json({
            success: true,
            message: "Student updated successfully."
        });

    } catch (error) {
        console.error(error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

// =====================================================
// Delete Student
// =====================================================
/**
 * ==================================================
 * Delete Student
 * DELETE /api/students/:id
 * ==================================================
 */

exports.deleteStudent = async (req, res) => {

    try {

        const { id } = req.params;

        const [rows] = await db.query(

            "SELECT * FROM students WHERE id = ?",

            [id]

        );

        if (rows.length === 0) {

            return res.status(404).json({

                success: false,

                message: "Student not found."

            });

        }

        await db.query(

            "DELETE FROM students WHERE id = ?",

            [id]

        );

        res.json({

            success: true,

            message: "Student deleted successfully."

        });

    }

    catch (error) {

        console.error(error);

        res.status(500).json({

            success: false,

            message: error.message

        });

    }

};