const express = require("express");
const router = express.Router();
const exe = require("./connection");

const bcrypt = require("bcryptjs");
const nodemailer = require("nodemailer");
const crypto = require("crypto");


router.get("/", async function (req, res) {

    // Check candidate login
    if (!req.session || !req.session.user) {
        return res.redirect("/login");
    }

    try {

        res.render("candidate_admin/index.ejs", {
            user: req.session.user
        });

    } catch (error) {

        console.log("Dashboard Error:", error);

        res.status(500).send("Something went wrong");

    }

});




// Candidate Profile
router.get("/profile", async function (req, res) {

    try {

        if (!req.session || !req.session.user) {
            return res.redirect('/login');
        }

        const userId = req.session.user.id;

        const result = await exe(
            "SELECT * FROM users WHERE id = ?",
            [userId]
        );

        if (result.length === 0) {
            return res.redirect('/login');
        }

        res.render("candidate_admin/profile.ejs", {
            user: result[0]
        });

    } catch (error) {

        console.log("Profile Error:", error);

        res.status(500).send("Something went wrong");

    }

});


// Change Password Page
router.get("/change-password", function (req, res) {

    if (!req.session || !req.session.user) {
        return res.redirect("/login");
    }

    res.render("candidate_admin/change-password.ejs", {
        user: req.session.user
    });

});


// Change Password
router.post("/change-password", async function (req, res) {

    try {

        if (!req.session || !req.session.user) {

            return res.json({
                status: false,
                message: "Please login first."
            });

        }


        const userId = req.session.user.id;

        const {
            currentPassword,
            newPassword,
            confirmPassword
        } = req.body;


        // Validation
        if (!currentPassword || !newPassword || !confirmPassword) {

            return res.json({
                status: false,
                message: "All password fields are required."
            });

        }


        if (newPassword.length < 8) {

            return res.json({
                status: false,
                message: "New password must be at least 8 characters."
            });

        }


        if (newPassword !== confirmPassword) {

            return res.json({
                status: false,
                message: "New password and confirm password do not match."
            });

        }


        // Get current password
        const users = await exe(
            `SELECT id, password
             FROM users
             WHERE id = ?
             LIMIT 1`,
            [userId]
        );


        if (users.length === 0) {

            return res.json({
                status: false,
                message: "User account not found."
            });

        }


        const user = users[0];


        // Check current password
        const passwordMatch = await bcrypt.compare(
            currentPassword,
            user.password
        );


        if (!passwordMatch) {

            return res.json({
                status: false,
                message: "Current password is incorrect."
            });

        }


        // Prevent same password
        const samePassword = await bcrypt.compare(
            newPassword,
            user.password
        );


        if (samePassword) {

            return res.json({
                status: false,
                message: "New password must be different from your current password."
            });

        }


        // Hash new password
        const hashedPassword = await bcrypt.hash(
            newPassword,
            10
        );


        // Update password
        await exe(
            `UPDATE users
             SET password = ?
             WHERE id = ?`,
            [hashedPassword, userId]
        );


        return res.json({

            status: true,

            message: "Your password has been changed successfully."

        });


    } catch (error) {

        console.log("Change Password Error:", error);

        return res.json({

            status: false,

            message: "Something went wrong while changing your password."

        });

    }

});


router.get("/my-bgv-report", function (req, res) {

    if (!req.session || !req.session.user) {
        return res.redirect("/login");
    }

    res.render("candidate_admin/my-bgv-report.ejs", {
        user: req.session.user
    });

});


router.get("/my-bgv-component", function (req, res) {

    if (!req.session || !req.session.user) {
        return res.redirect("/login");
    }

    res.render("candidate_admin/my-bgv-component.ejs", {
        user: req.session.user
    });

});

router.get("/bgv-insuff", function (req, res) {

    if (!req.session || !req.session.user) {
        return res.redirect("/login");
    }

    res.render("candidate_admin/bgv-insuff.ejs", {
        user: req.session.user
    });

});

router.get("/self-declaration", function (req, res) {

    if (!req.session || !req.session.user) {
        return res.redirect("/login");
    }

    res.render("candidate_admin/self-declaration.ejs", {
        user: req.session.user
    });

});


router.get("/my-orders", async function (req, res) {

    try {

        if (!req.session || !req.session.user) {
            return res.redirect("/login");
        }

        const userId = req.session.user.id;

        // Temporary until we connect your actual orders table
        const orders = [];

        res.render("candidate_admin/my-orders.ejs", {
            user: req.session.user,
            orders: orders
        });

    } catch (error) {

        console.log("My Orders Error:", error);

        res.status(500).send("Something went wrong.");

    }

});


router.get("/bgv-report-status", async function (req, res) {

    try {

        if (!req.session || !req.session.user) {
            return res.redirect("/login");
        }

        const userId = req.session.user.id;

        // Actual BGV status table connect झाल्यावर query इथे add करू
        const bgvStatus = {
            overall_status: "In Progress",
            initiated_date: null,
            completed_date: null,
            progress: 0
        };

        const components = [];

        res.render("candidate_admin/bgv-report-status.ejs", {
            user: req.session.user,
            bgvStatus: bgvStatus,
            components: components
        });

    } catch (error) {

        console.log("BGV Report Status Error:", error);

        res.status(500).send("Something went wrong.");

    }

});









// Logout
router.get("/logout", function (req, res) {

    req.session.destroy(function (err) {

        if (err) {
            console.log("Logout Error:", err);
            return res.status(500).send("Unable to logout");
        }

        // Remove session cookie
        res.clearCookie('connect.sid');

        // Redirect to login page
        res.redirect('/login');

    });

});



module.exports = router;