const express = require('express');
const router = express.Router();
const db = require('../database/db');
const bcrypt = require('bcrypt');


router.post('/login', (req, res) => {
    const { email, password } = req.body;

    if (!email || !password) {
        return res.status(400).send('empty');
    }

    const loginQuery = 'SELECT * FROM institute WHERE email = ?';
    const loginValues = [email];

    db.query(loginQuery, loginValues, (err, results) => {
        if (err) {
            console.error('Error checking existing data:', err);
            return res.status(500).send('Server error');
        }

        if (results.length > 0) {
            const user = results[0];
            const storedHash = user.password;

            // Compare entered password with stored hash
            bcrypt.compare(password, storedHash, (err, isMatch) => {
                if (err) {
                    console.error('Error comparing passwords:', err);
                    return res.status(500).send('Server error');
                }

                if (isMatch) {
                    return res.json(user);
                } else {
                    return res.json({ message: 'Invalid' });
                }
            });
        } else {
            return res.json({ message: 'Invalid' });
        }
    });
});

//send node

router.post('/send', (req, res) => {

    const { id, name, email, password, approve } = req.body;

    if (!id || !email || !password || !name || !approve) {
        return res.status(400).send('empty');
    }

    const checkQuary = 'SELECT * FROM institute WHERE email = ? ';
    const checkValues = [email, id];

    db.query(checkQuary, checkValues, (err, results) => {
        if (err) {
            console.error('Error checking existing data:', err);
            return res.status(500).send('Server error');
        }

        if (results.length > 0) {

            console.log(results)

            //NodeMailer
            var nodemailer = require('nodemailer');


            if (approve === "true") {

                let transporter = nodemailer.createTransport({
                    service: 'gmail',
                    auth: {
                        user: 'randyruch5@gmail.com',
                        pass: 'luxlrqakfenxkyzi'
                    }
                });



                let mailOptions = {
                    from: 'randyruch5@gmail.com',
                    to: email,
                    subject: 'Login Data Test',
                    html: `
                        <div style="font-family: Arial, sans-serif; color: #333;">
                            <div style="background-color: #f7f7f7; padding: 20px; border-bottom: 1px solid #ccc;">
                                <h2 style="margin: 0; color:#0e0534;">Education App</h2>
                            </div>
                            <div style="padding: 20px;">
                                <p style="font-size: 16px;">Dear ${name}</p>
                                <p style="font-size: 16px;">We have approved your organization and now you can proceed with our system.<br/> Use the username and password below to access your dashboard <span style="border-radius: 4px; background-color: red; color: black; padding:0px 1px 1px 0px;"><b>Do not share this with others</b></span> </p>
                                <div style="padding: 10px; background-color: #e7f3fe; border: 1px solid #b3d4fc; border-radius: 4px;">
                                    <p style="margin: 0; font-size: 16px;"><strong>Username :</strong> ${email}</p>
                                    <p style="margin: 0; font-size: 16px;"><strong>Password :</strong> ${password}</p>
                                </div>
                                <p style="font-size: 16px;">Please use the following button to login:</p>
                                <div style="text-align: center; margin: 20px 0;">
                                    <a href="http://localhost:3000/rlogin" style="background-color: #0e0534; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px; font-size: 16px;">Login</a>
                                </div>
                                <p style="font-size: 16px;">Best regards,</p>
                                <p style="font-size: 16px;"><strong>Randy Ruch</strong></p>
                            </div>
                            <div style="background-color: #f7f7f7; padding: 10px; border-top: 1px solid #ccc; text-align: center;">
                                <p style="font-size: 12px; color: #777;">&copy; 2024 Education App. All rights reserved.</p>
                            </div>
                        </div>
                    `
                };

                transporter.sendMail(mailOptions, function (error, info) {
                    if (error) {
                        console.log(error);
                    } else {
                        return res.send({ msg: "Success" })
                    }
                });

            } else {

                let transporter = nodemailer.createTransport({
                    service: 'gmail',
                    auth: {
                        user: 'randyruch5@gmail.com',
                        pass: 'luxlrqakfenxkyzi'
                    }
                });

                let mailOptions = {
                    from: 'randyruch5@gmail.com',
                    to: email,
                    subject: 'Login Data Test',
                    html: `
                        <div style="font-family: Arial, sans-serif; color: #333;">
                            <div style="background-color: #f7f7f7; padding: 20px; border-bottom: 1px solid #ccc;">
                                <h2 style="margin: 0; color:#0e0534;">Education App</h2>
                            </div>
                            <div style="padding: 20px;">
                                <p style="font-size: 16px;">Dear ${name}</p>
                                <p style="font-size: 16px;"> Unfortunately ,your organization has not been approved at this time. <br/> Please review the submission requirements and try again. <br/> If you have any questions or need assistance, contact us.</p>
                            
                                <p style="font-size: 16px;">Please use the following Contact Us button to contact:</p>
                                <div style="text-align: center; margin: 20px 0;">
                                    <a href="http://localhost:3000/Contact" style="background-color: #0e0534; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px; font-size: 16px;">Contact Us</a>
                                </div>
                                <p style="font-size: 16px;">Best regards,</p>
                                <p style="font-size: 16px;"><strong>Randy Ruch</strong></p>
                            </div>
                            <div style="background-color: #f7f7f7; padding: 10px; border-top: 1px solid #ccc; text-align: center;">
                                <p style="font-size: 12px; color: #777;">&copy; 2024 Education App. All rights reserved.</p>
                            </div>
                        </div>
                    `
                };


                transporter.sendMail(mailOptions, function (error, info) {
                    if (error) {
                        console.log(error);
                    } else {
                        return res.send({ msg: "Success" })
                    }
                });

            }


        } else {
            return res.json({ message: 'Invalid' });
        }

    });



})

//chnage password 
router.post('/change', (req, res) => {

    const { id, password } = req.body;

    console.log(req.body);

    if (!id || !password) {
        return res.status(400).send('empty');
    }


    //hash password
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);

    const query = 'UPDATE institute SET password = ? , password_on = ? , firstlog = ?  WHERE id = ?';
    const values = [hash, password, "true", id];

    db.query(query, values, (err, result) => {

        if (err) {
            console.error('Error updating data:', err);
            return res.status(500).send('Server error');
        }

        res.json({ message: 'Password updated successfully' });
    });



});


//check email in institute table
router.post('/checkemail', (req, res) => {

    const { email, role } = req.body;

    if (!email, !role) {
        return res.status(400).send('empty');
    }
    console.log(email, role);

    let checkQuary = " "

    if (role === 'ins') {
        checkQuary = 'SELECT * FROM institute WHERE email = ? ';
    } else if (role === 'gc') {
        checkQuary = 'SELECT * FROM government_officer WHERE email = ? ';
    }
    const checkValues = [email];

    db.query(checkQuary, checkValues, (err, results) => {
        if (err) {
            console.error('Error checking existing data:', err);
            return res.status(500).send('Server error');
        }

        if (results.length > 0) {
            return res.json(results);
        } else {
            return res.json({ message: 'Valid' });
        }

    });
});


router.post('/sendpassword', (req, res) => {

    const { id, email } = req.body;

    if (!id) {
        return res.status(400).send('empty');
    }


    //NodeMailer
    var nodemailer = require('nodemailer');

    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'randyruch5@gmail.com',
            pass: 'luxlrqakfenxkyzi'
        }
    });

    let mailOptions = {
        from: 'randyruch5@gmail.com',
        to: email,
        subject: 'Password Change Request',
        html: `
            <div style="font-family: Arial, sans-serif; text-align: left; font-size: 18px;">
            <h2 style="font-size: 24px;">Password Change Request</h2>
            <p>Hi,</p>
            <p>You requested to change your password. Please click the button below to proceed:</p>
            <a href="http://localhost:3000/changepassf/${id}" 
               style="display: inline-block; padding: 12px 24px; font-size: 18px; color: #ffffff; background-color: #007bff; text-decoration: none; border-radius: 5px; margin-top: 20px;">
               Change Password
            </a>
            <p>If you did not request this, please ignore this email.</p>
        </div>
        `
    }

    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error);
        } else {
            return res.send({ msg: "Success" })
        }
    });



})


//fjob apply form mail send
router.post('/sendapplyf', (req, res) => {

    const { name, email, contact, addr, passno, mess, aemail } = req.body;

    //NodeMailer
    var nodemailer = require('nodemailer');

    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'randyruch5@gmail.com',
            pass: 'luxlrqakfenxkyzi'
        }
    });


    let mailOptions = {
        from: 'randyruch5@gmail.com',
        to: aemail, // Replace with the system admin's email address
        subject: 'Application form Skills Sri Lanka',
        html: `
        <html>
        <body style="font-family: Arial, sans-serif; color: #333;">
            <div style="max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
                <h2 style="color: #0056b3; border-bottom: 2px solid #0056b3; padding-bottom: 10px;">Application form Skills Sri Lanka</h2>
                
                <div style="padding: 10px; border-left: 5px solid #0056b3; margin-bottom: 10px; background-color: #f0f8ff;">
                    <p style="font-size: 16px; line-height: 1.5;"><strong>Client Name : </strong> ${name}</p>
                </div>
                
                <div style="padding: 10px; border-left: 5px solid #28a745; margin-bottom: 10px; background-color: #e6ffee;">
                    <p style="font-size: 16px; line-height: 1.5;"><strong>Client Email : </strong> ${email}</p>
                </div>
                
                <div style="padding: 10px; border-left: 5px solid #ffc107; margin-bottom: 10px; background-color: #fff9e6;">
                    <p style="font-size: 16px; line-height: 1.5;"><strong>Client Address : </strong> ${addr}</p>
                </div>

                 <div style="padding: 10px; border-left: 5px solid #ffc107; margin-bottom: 10px; background-color: #fff9e6;">
                    <p style="font-size: 16px; line-height: 1.5;"><strong>Passport Number : </strong> ${passno}</p>
                </div>
                
                <div style="padding: 10px; border-left: 5px solid #dc3545; margin-bottom: 10px; background-color: #ffe6e6;">
                    <p style="font-size: 16px; line-height: 1.5;"><strong>Contact Number:</strong> ${contact}</p>
                </div>
                
                <div style="padding: 10px; border-left: 5px solid #17a2b8; margin-bottom: 10px; background-color: #e6f9ff;">
                    <p style="font-size: 16px; line-height: 1.5;"><strong>Client Message : </strong></p>
                    <p style="font-size: 16px; line-height: 1.5; white-space: pre-line;">${mess}</p>
                </div>
                
                <div style="background-color: #f7f7f7; padding: 10px; border-top: 1px solid #ccc; text-align: center;">
                    <p style="font-size: 12px; color: #777;">&copy; 2024 Skills Sri Lanka. All rights reserved.</p>
                </div>
                
            </div>
        </body>
        </html>
        `
    };

    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error);
        } else {
            return res.send({ msg: "Success" })
        }
    });

})







module.exports = router;