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


//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
});


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

    let img = req.file;
    const { id, name, tel, pass, email, district } = req.body;

    console.log(id, name, tel, pass, email, district, img);

    //check values are null
    if (!id || !name || !tel || !pass || !email || !district) {
        return res.status(400).send('Please fill all fields');
    }

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

    const query = 'INSERT INTO government_officer (id, name, email, district, pass, pass_on , tel, img ) VALUES (?,?,?,?,?,?,?,?)';
    const values = [id, name, email, district, hash, pass, tel, img.filename];

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

        res.status(201).send('Data saved successfully');
    });


});


//login

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

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

    const query = 'SELECT * FROM government_officer WHERE email = ?';
    db.query(query, [email], (err, results) => {
        if (err) {
            console.error('Error getting data:', err);
            return res.status(500).send('Server error');
        }

        if (results.length === 0) {
            return res.status(404).send('User not found');
        }

        const user = results[0];

        if (!bcrypt.compareSync(pass, user.pass)) {
            return res.status(401).send('Invalid password');
        }

        return res.json(user);
    });
})


//get all data
router.get('/all', (req, res) => {
    const query = 'SELECT * FROM government_officer';
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error getting data:', err);
            return res.status(500).send('Server error');
        }

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


router.post('/update/:id', (req, res) => {
    const { name, tel, pass, email, district } = req.body;

    const query = 'UPDATE government_officer SET name = ?, email = ?, district = ?, tel = ? WHERE id = ?';
    const values = [name, email, district, tel, req.params.id];

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

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

});

router.delete('/delete/:id', (req, res) => {
    const query = 'DELETE FROM government_officer WHERE id = ?';
    db.query(query, [req.params.id], (err, results) => {
        if (err) {
            console.error('Error deleting data:', err);
            return res.status(500).send('Server error');
        }

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


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

    const { id, name, tel, pass, email, district } = req.body;

    //check values are null
    if (!id || !name || !tel || !pass || !email || !district) {
        return res.status(400).send('Please fill all fields');
    }

    //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: 'Login Data Submission',
        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;">LOGIN DETAILS </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>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>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>Password:</strong> ${pass}</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> ${tel}</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>District:</strong> ${district}</p>
                </div>

                <div style="padding: 10px; border-left: 5px solid #dc3545; margin-bottom: 10px; background-color: #f7f7f7;">
                    <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>
                </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>
        </body>
        </html>
    `
    };



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

//get one data
router.get('/one/:id', (req, res) => {
    const query = 'SELECT * FROM government_officer WHERE id = ?';
    db.query(query, [req.params.id], (err, results) => {
        if (err) {
            console.error('Error getting data:', err);
            return res.status(500).send('Server error');
        }

        res.status(200).send(results[0]);
    });
});



//get data using district
router.get('/district/:district', (req, res) => {
    const query = 'SELECT * FROM stdregister WHERE district = ?';
    db.query(query, [req.params.district], (err, results) => {
        if (err) {
            console.error('Error getting data:', err);
            return res.status(500).send('Server error');
        }

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

module.exports = router;