const express = require('express');
const router = express.Router();
const db = require('../database/db');
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('/addImage', upload.single('img'), (req, res) => {

    const {position} = req.body;
    let img = req.file;

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

    //check if position is on database
    const checkQuary = 'SELECT * FROM advertisement WHERE Position = ?';
    const checkValues = [position];

    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.status(400).send('Advertisement already exists');
        }
        const query = 'INSERT INTO advertisement (img, Position) VALUES (?,?)';
        const values = [img.filename, position];
    
        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');
        });


    });

    
})

//getall

router.get('/getAll', (req, res) => {
    
        const query = 'SELECT * FROM advertisement';
    
        db.query(query, (err, result) => {
            if (err) {
                res.status(500).send({ message: err.message });
            } else {
                res.json(result);
            }
        });
})


//delete
router.delete('/delete/:id', (req, res) => {
    const id = req.params.id;
    const query = 'DELETE FROM advertisement WHERE id = ?';
    db.query(query, id, (err, result) => {
        if (err) {
            res.status(500).send({ message: err.message });
        } else {
            res.json({ message: 'Advertisement deleted successfully' });
        }
    });
});












module.exports = router;