const express = require('express');
var router = express.Router();
var exe = require("./connection");
var upload=require("express-fileupload");
const bcrypt = require("bcryptjs");
const nodemailer = require("nodemailer");
const crypto = require("crypto");


router.get("/", function (req, res) {
    res.render("user/index.ejs");
});



router.get("/login", function (req, res) {
    res.render("user/login.ejs");
});


const transporter = nodemailer.createTransport({

    service: "gmail",

    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }

});

// ===============================
// LOGIN POST
// ===============================

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

    try {

        const {
            loginEmail,
            loginPassword,
            redirect
        } = req.body;


        // --------------------------------
        // Basic Validation
        // --------------------------------

        if (!loginEmail || !loginPassword) {

            return res.json({
                status: false,
                message: "Please enter your email/mobile and password."
            });

        }


        // --------------------------------
        // Find User by Email OR Mobile
        // --------------------------------

        const users = await exe(
            `SELECT id, first_name, last_name, email, mobile, password
             FROM users
             WHERE email = ? OR mobile = ?
             LIMIT 1`,
            [loginEmail, loginEmail]
        );


        // --------------------------------
        // User Not Found
        // --------------------------------

        if (users.length === 0) {

            return res.json({
                status: false,
                message: "Invalid email/mobile or password."
            });

        }


        const user = users[0];


        // --------------------------------
        // Check Password
        // --------------------------------

        const passwordMatch = await bcrypt.compare(
            loginPassword,
            user.password
        );


        if (!passwordMatch) {

            return res.json({
                status: false,
                message: "Invalid email/mobile or password."
            });

        }


        // --------------------------------
        // CREATE SESSION
        // --------------------------------

        req.session.user = {

            id: user.id,

            first_name: user.first_name,

            last_name: user.last_name,

            email: user.email,

            mobile: user.mobile

        };


        // --------------------------------
        // Login Success
        // --------------------------------

        return res.json({

            status: true,

            message: `Welcome back, ${user.first_name}!`,

            redirect: redirect || "/candidate_admin",

            user: {

                id: user.id,

                firstName: user.first_name,

                lastName: user.last_name,

                email: user.email,

                mobile: user.mobile

            }

        });


    } catch (error) {

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

        return res.json({

            status: false,

            message: "Something went wrong while logging in."

        });

    }

});



function isCandidateLoggedIn(req, res, next) {

    if (!req.session.user) {

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

    }

    next();
}


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

    try {

        const {
            firstName,
            lastName,
            email,
            mobile,
            password,
            confirmPassword
        } = req.body;


        // --------------------------------
        // Basic Validation
        // --------------------------------

        if (!firstName || !lastName || !email || !mobile || !password || !confirmPassword) {

            return res.json({
                status: false,
                message: "Please fill all required fields."
            });

        }


        // --------------------------------
        // Password Match
        // --------------------------------

        if (password !== confirmPassword) {

            return res.json({
                status: false,
                message: "Password and Confirm Password do not match."
            });

        }


        // --------------------------------
        // Password Length
        // --------------------------------

        if (password.length < 8) {

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

        }


        // --------------------------------
        // Check Existing Email
        // --------------------------------

        const existingUser = await exe(
            "SELECT id FROM users WHERE email = ?",
            [email]
        );


        if (existingUser.length > 0) {

            return res.json({
                status: false,
                message: "An account with this email already exists."
            });

        }


        // --------------------------------
        // Hash Password
        // --------------------------------

        const hashedPassword = await bcrypt.hash(password, 10);


        // --------------------------------
        // Insert User
        // --------------------------------

        const result = await exe(
            `INSERT INTO users 
            (first_name, last_name, email, mobile, password)
            VALUES (?, ?, ?, ?, ?)`,
            [
                firstName,
                lastName,
                email,
                mobile,
                hashedPassword
            ]
        );


        // --------------------------------
        // Send Welcome Email
        // --------------------------------

        const transporter = nodemailer.createTransport({

            service: "gmail",

            auth: {
                user: process.env.EMAIL_USER,
                pass: process.env.EMAIL_PASS
            }

        });


        const mailOptions = {

            from: `"VSearch BGV" <${process.env.EMAIL_USER}>`,
            to: email,

            subject: "Welcome to VSearch BGV",

            html: `
            
            <div style="
                font-family: Arial, sans-serif;
                max-width: 600px;
                margin: auto;
                border: 1px solid #e5e7eb;
                border-radius: 10px;
                overflow: hidden;
            ">

                <div style="
                    background:#111827;
                    padding:25px;
                    text-align:center;
                    color:white;
                ">

                    <h2 style="margin:0;">
                        VSearch BGV
                    </h2>

                    <p style="margin:8px 0 0;">
                        Background Verification Portal
                    </p>

                </div>


                <div style="padding:30px;">

                    <h2 style="color:#111827;">
                        Welcome, ${firstName} ${lastName}! 🎉
                    </h2>

                    <p style="font-size:15px;color:#475569;">
                        Thank you for creating your account with
                        <strong>VSearch BGV</strong>.
                    </p>

                    <p style="font-size:15px;color:#475569;">
                        Your account has been successfully created.
                        You can now securely access the VSearch
                        Background Verification Portal.
                    </p>


                    <div style="
                        background:#f8fafc;
                        padding:18px;
                        border-radius:8px;
                        margin:20px 0;
                    ">

                        <p style="margin:5px 0;">
                            <strong>Name:</strong>
                            ${firstName} ${lastName}
                        </p>

                        <p style="margin:5px 0;">
                            <strong>Email:</strong>
                            ${email}
                        </p>

                        <p style="margin:5px 0;">
                            <strong>Mobile:</strong>
                            ${mobile}
                        </p>

                    </div>


                    <div style="text-align:center;margin:25px 0;">

                        <a href="http://localhost:3000/login"
                           style="
                           display:inline-block;
                           background:#2563eb;
                           color:#fff;
                           padding:12px 25px;
                           text-decoration:none;
                           border-radius:6px;
                           font-weight:bold;
                           ">
                           Login to Your Account
                        </a>

                    </div>


                    <p style="
                        color:#64748b;
                        font-size:13px;
                        margin-top:30px;
                    ">

                        If you did not create this account,
                        please contact our support team.

                    </p>

                </div>


                <div style="
                    background:#f8fafc;
                    padding:15px;
                    text-align:center;
                    color:#64748b;
                    font-size:12px;
                ">

                    © ${new Date().getFullYear()} VSearch BGV.
                    All rights reserved.

                </div>

            </div>

            `

        };


        await transporter.sendMail(mailOptions);


        // --------------------------------
        // Success Response
        // --------------------------------

        return res.json({

            status: true,

            message: "Your account has been created successfully."

        });


    } catch (error) {

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

        return res.json({

            status: false,

            message: "Something went wrong while creating your account."

        });

    }

});

router.post("/forgot-password", async function (req, res) {

    try {

        const { email } = req.body;

        if (!email) {
            return res.json({
                status: false,
                message: "Please enter your email address."
            });
        }

        const users = await exe(
            "SELECT id, first_name, last_name, email FROM users WHERE email = ? LIMIT 1",
            [email]
        );

        if (users.length === 0) {
            return res.json({
                status: false,
                message: "No account found with this email address."
            });
        }

        const user = users[0];

        // Generate secure token
        const resetToken = crypto.randomBytes(32).toString("hex");

        // Token valid for 30 minutes
        const expiry = new Date(Date.now() + 30 * 60 * 1000);

        await exe(
            `UPDATE users
             SET reset_token = ?, reset_token_expiry = ?
             WHERE id = ?`,
            [resetToken, expiry, user.id]
        );

        const resetLink =
            `http://localhost:3000/reset-password/${resetToken}`;

        await transporter.sendMail({

            from: `"VSearch BGV" <${process.env.EMAIL_USER}>`,

            to: user.email,

            subject: "Reset Your VSearch BGV Password",

            html: `
                <div style="
                    font-family:Arial,sans-serif;
                    max-width:600px;
                    margin:auto;
                    border:1px solid #e5e7eb;
                    border-radius:10px;
                    overflow:hidden;
                ">

                    <div style="
                        background:#111827;
                        color:#fff;
                        padding:25px;
                        text-align:center;
                    ">
                        <h2>VSearch BGV</h2>
                        <p>Background Verification Portal</p>
                    </div>

                    <div style="padding:30px;">

                        <h2>
                            Hello ${user.first_name}!
                        </h2>

                        <p>
                            We received a request to reset your
                            VSearch BGV account password.
                        </p>

                        <p>
                            Click the button below to create a new password.
                        </p>

                        <div style="text-align:center;margin:30px 0;">

                            <a href="${resetLink}"
                               style="
                               background:#2563eb;
                               color:white;
                               padding:13px 25px;
                               text-decoration:none;
                               border-radius:6px;
                               font-weight:bold;
                               ">
                               Reset Password
                            </a>

                        </div>

                        <p style="color:#64748b;font-size:13px;">
                            This link will expire in 30 minutes.
                        </p>

                        <p style="color:#64748b;font-size:13px;">
                            If you did not request a password reset,
                            you can safely ignore this email.
                        </p>

                    </div>

                    <div style="
                        background:#f8fafc;
                        padding:15px;
                        text-align:center;
                        color:#64748b;
                        font-size:12px;
                    ">
                        © ${new Date().getFullYear()} VSearch BGV.
                        All rights reserved.
                    </div>

                </div>
            `

        });

        return res.json({
            status: true,
            message: "Password reset link has been sent to your email address."
        });

    } catch (error) {

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

        return res.json({
            status: false,
            message: "Unable to process your request. Please try again."
        });

    }

});

router.get("/reset-password/:token", async function (req, res) {

    try {

        const { token } = req.params;

        const users = await exe(
            `SELECT id
             FROM users
             WHERE reset_token = ?
             AND reset_token_expiry > NOW()
             LIMIT 1`,
            [token]
        );

        if (users.length === 0) {

            return res.send(`
                <h2>Invalid or Expired Reset Link</h2>
                <p>Please request a new password reset link.</p>
            `);

        }

        res.render("user/reset-password.ejs", {
            token: token
        });

    } catch (error) {

        console.log(error);

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

    }

});

router.post("/reset-password/:token", async function (req, res) {

    try {

        const { token } = req.params;

        const {
            password,
            confirmPassword
        } = req.body;


        if (!password || !confirmPassword) {

            return res.json({
                status: false,
                message: "Please enter both passwords."
            });

        }


        if (password !== confirmPassword) {

            return res.json({
                status: false,
                message: "Passwords do not match."
            });

        }


        if (password.length < 8) {

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

        }


        const users = await exe(
            `SELECT id
             FROM users
             WHERE reset_token = ?
             AND reset_token_expiry > NOW()
             LIMIT 1`,
            [token]
        );


        if (users.length === 0) {

            return res.json({
                status: false,
                message: "This reset link is invalid or expired."
            });

        }


        const hashedPassword = await bcrypt.hash(password, 10);


        await exe(
            `UPDATE users
             SET password = ?,
                 reset_token = NULL,
                 reset_token_expiry = NULL
             WHERE id = ?`,
            [hashedPassword, users[0].id]
        );


        return res.json({

            status: true,

            message: "Your password has been reset successfully."

        });


    } catch (error) {

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

        return res.json({

            status: false,

            message: "Unable to reset your password."

        });

    }

});










router.post("/prepare-checkout", async function (req, res) {

    try {

        const { services } = req.body;

        if (!Array.isArray(services) || services.length === 0) {

            return res.json({
                status: false,
                message: "Please select at least one service."
            });

        }

        let subtotal = 0;

        const packageServices = services.map(service => {

            const price = Number(service.price) || 0;
            const quantity = Number(service.quantity) || 1;

            const total = price * quantity;

            subtotal += total;

            return {
                name: service.name,
                price: price,
                quantity: quantity,
                total: total
            };

        });

        const gst = Math.round(subtotal * 0.18);

        const grandTotal = subtotal + gst;


        // Save selected package
        req.session.checkoutPackage = {

            services: packageServices,
            subtotal: subtotal,
            gst: gst,
            grandTotal: grandTotal

        };


        // Login check
        if (!req.session.user) {

            return res.status(401).json({

                status: false,
                message: "Please login first.",
                redirect: "/checkout"

            });

        }


        return res.json({

            status: true,
            message: "Checkout prepared successfully.",
            redirect: "/checkout"

        });


    } catch (error) {

        console.log("Prepare Checkout Error:", error);

        return res.status(500).json({

            status: false,
            message: "Something went wrong."

        });

    }

});





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

//     try {

//         // Login check
//         if (!req.session.user) {

//             return res.redirect(
//                 "/login?redirect=/user/checkout"
//             );

//         }

//         // Package check
//         if (!req.session.checkoutPackage) {

//             return res.redirect(
//                 "/user/makeown_package"
//             );

//         }

//         // Render checkout page
//         res.render("user/checkout.ejs", {

//             user: req.session.user,

//             package: req.session.checkoutPackage

//         });

//     } catch (error) {

//         console.log("Checkout Page Error:", error);

//         return res.redirect(
//             "/user/makeownpackage"
//         );

//     }

// });





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

    try {

        // User login नसल्यास login page वर पाठवा
        if (!req.session.user) {

            return res.redirect(
                "/login?redirect=/user/checkout"
            );

        }

        // Package session मध्ये नसेल
        if (!req.session.checkoutPackage) {

            return res.redirect(
                "/user/makeown-package"
            );

        }

        res.render("user/checkout.ejs", {

            user: req.session.user,

            package: req.session.checkoutPackage

        });

    } catch (error) {

        console.log("Checkout Page Error:", error);

        return res.redirect(
            "/user/makeown-package"
        );

    }

});







router.get("/about-us", function (req, res) {
    res.render("user/about-us.ejs");
});


router.get("/address-verification", function (req, res) {
    res.render("user/address_verification.ejs");
});

router.get("/advance-package", function (req, res) {
    res.render("user/advance_package.ejs");
});

router.get("/ai-solutions", function (req, res) {
    res.render("user/ai_solutions.ejs");
});

router.get("/api-hub", function (req, res) {
    res.render("user/api_hub.ejs");
});

router.get("/basic-package", function (req, res) {
    res.render("user/basic_package.ejs");
});

router.get("/blue-collar-verification", function (req, res) {
    res.render("user/blue_collar_verification.ejs");
});

// router.get("/contact-us", function (req, res) {
//     res.render("user/contact-us.ejs");
// });

router.get("/corporates-verification", function (req, res) {
    res.render("user/corporates_verification.ejs");
});

router.get("/criminal-verification", function (req, res) {
    res.render("user/criminal_verification.ejs");
});

router.get("/database-verification", function (req, res) {
    res.render("user/database_verification.ejs");
});

router.get("/education-verification", function (req, res) {
    res.render("user/education_verification.ejs");
});

router.get("/employment-verification", function (req, res) {
    res.render("user/employment_verification.ejs");
});

router.get("/financial-verification", function (req, res) {
    res.render("user/financial_verification.ejs");
});

router.get("/identity-verification", function (req, res) {
    res.render("user/identity_verification.ejs");
});

router.get("/individual-package-bgv", function (req, res) {
    res.render("user/individual_package_bgv.ejs");
});

router.get("/industry", function (req, res) {
    res.render("user/industry.ejs");
});

router.get("/makeown-package", function (req, res) {
    res.render("user/makeown_package.ejs");
});

router.get("/our-usp", function (req, res) {
    res.render("user/our_usp.ejs");
});

router.get("/our-history", function (req, res) {
    res.render("user/our-history.ejs");
});

// router.get("/our-team", function (req, res) {
//     res.render("user/our-team.ejs");
// });

router.get("/reference-verification", function (req, res) {
    res.render("user/reference_verification.ejs");
});

router.get("/standard-package", function (req, res) {
    res.render("user/standard_package.ejs");
});

router.get("/vision-mission", function (req, res) {
    res.render("user/vision_mission.ejs");
});

router.get("/white-collar-verification", function (req, res) {
    res.render("user/white_collar_verification.ejs");
});




module.exports = router;