const express = require('express');
const router = express.Router();
const db = require('../database/db');
const multer = require('multer');
const path = require('path');
const { Console } = require('console');
const bcrypt = require('bcrypt');


//create multer storage
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        return cb(null, 'Upload/images');
    },
    filename: (req, file, cb) => {
        return cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname));
    }

});

//upload image
const upload = multer({
    storage: storage
});


//register job
router.post('/register', upload.single('img'), (req, res) => {

    let img = req.file;

    const { id, aname, ano, aaddr, contact, email, jobtit, fType, msalry, avacn, otfc, mca, reqq, pdate, cdate, country, approve, deleted } = req.body;

    console.log(id, aname, ano, aaddr, contact, email, jobtit, fType, msalry, avacn, otfc, mca, reqq, pdate, cdate, country, approve, deleted, img);

    if (!id || !aname || !ano || !aaddr || !contact || !email || !jobtit || !fType || !msalry || !avacn || !otfc || !mca || !reqq || !pdate || !cdate || !country || !approve || !deleted) {
        return res.status(400).send('Please fill all fields');
    }

    const query = 'INSERT INTO fjob (id, aname, ano, aaddr, contact, email, jobtit, fType, msalry, avacn, otfc, mca, reqq, pdate, cdate, country, approve, deleted, img) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
    const values = [id, aname, ano, aaddr, contact, email, jobtit, fType, msalry, avacn, otfc, mca, reqq, pdate, cdate, country, approve, deleted, img.filename];

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

        return res.status(200).send('Data inserted successfully');
    });



})


// Get all approved jobs with optional filters
router.get('/getall', (req, res) => {
    let query = 'SELECT * FROM fjob WHERE approve = "true"';
    const values = [];

    // Apply filters if present in the request query
    if (req.query.fType) {
        query += ' AND fType = ?';
        values.push(req.query.fType);
    }

    if (req.query.country) {
        query += ' AND country = ?';
        values.push(req.query.country);
    }

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

        return res.status(200).send(results);
    });
});


//get all approve == false
router.get('/getallapprove', (req, res) => {
    const query = 'SELECT * FROM fjob WHERE approve = "false"';

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

        return res.status(200).send(results);
    });

})


//update approve
router.post('/updateapprove', (req, res) => {
    const { id, approve } = req.body;

    if (!id || !approve) {
        return res.status(400).send('Please fill all fields');
    }

    const query = 'UPDATE fjob SET approve = ? WHERE id = ?';
    const values = [approve, id];

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

        return res.status(200).send('Data updated successfully');
    });
})


//delete 
router.post('/delete', (req, res) => {
    const { id } = req.body;

    if (!id) {
        return res.status(400).send('Please fill all fields');
    }

    const query = 'DELETE FROM fjob WHERE id = ?';
    const values = [id];

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

        return res.status(200).send('Data deleted successfully');
    });

})


//get one using id
router.get('/getone/:id', (req, res) => {
    const id = req.params.id;
    console.log(id);
    if (!id) {
        return res.status(400).send('Please fill all fields');
    }

    const query = 'SELECT * FROM fjob WHERE id = ?';
    const values = [id];

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

        return res.json(results);
    });

})



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

    const { email, name, id } = 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: email,
        subject: 'Job Approval from Skills Sri Lanka',
        html: `
        <html>
        <body style="font-family: Arial, sans-serif; color: #333; background-color: #f4f4f4; padding: 20px;">
            <div style="max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px; background-color: #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
                <h2 style="color: #0056b3; border-bottom: 2px solid #0056b3; padding-bottom: 10px; text-align: center;">Job Approval Confirmation</h2>
                
                <p style="font-size: 16px; line-height: 1.6;">
                    Dear <strong>${name}</strong>,
                </p>
                
                <p style="font-size: 16px; line-height: 1.6;">
                    We are excited to inform you that your job posting has been approved! Your job is now live on our website. All applications for this position will be sent to the following email:
                </p>
                
                <div style="padding: 15px; border-left: 5px solid #28a745; background-color: #e6ffee; margin-bottom: 20px; border-radius: 5px;">
                    <p style="font-size: 16px; line-height: 1.5;"><strong>Email:</strong> ${email}</p>
                </div>
    
                <p style="font-size: 16px; line-height: 1.6;">
                    If you need to make any changes or have questions about the listing, feel free to reach out to us.
                </p>
                
                <div style="text-align: center; margin: 30px 0;">
                    <a href="http://localhost:3000/fjob/${id}" style="background-color: #0056b3; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-size: 16px;">Visit Our Website</a>
                </div>
                
                <p style="font-size: 16px; line-height: 1.6;">Best regards,</p>
                <p style="font-size: 16px; line-height: 1.6;">The Skills Sri Lanka Team</p>
                
                <div style="background-color: #f7f7f7; padding: 10px; border-top: 1px solid #ccc; text-align: center; margin-top: 40px;">
                    <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;