const express = require('express');
const Banner = require('../models/Banner');
const { authenticateToken, isAdmin } = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const router = express.Router();

// Configure Multer for Banner Images
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const dir = 'uploads/banners';
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        cb(null, dir);
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname.replace(/\s+/g, '-'));
    }
});

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

// GET All Banners (Public gets Active only, Admin gets all)
router.get('/', async (req, res) => {
    try {
        const isAdminRequest = req.query.admin === 'true';
        
        let where = {};
        if (!isAdminRequest) {
            where.status = 'Active';
        }

        const banners = await Banner.findAll({
            where,
            order: [['order', 'ASC'], ['createdAt', 'DESC']]
        });

        res.json(banners);
    } catch (error) {
        console.error('Error fetching banners:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// POST Create Banner (Admin Only)
router.post('/', authenticateToken, isAdmin, upload.single('image'), async (req, res) => {
    try {
        const bannerData = req.body;

        // Handle Image Upload
        if (req.file) {
            const protocol = req.protocol;
            const host = req.get('host');
            bannerData.image = `${protocol}://${host}/uploads/banners/${req.file.filename}`;
        } else if (!bannerData.image) {
            return res.status(400).json({ message: 'Image is required' });
        }

        const banner = await Banner.create(bannerData);
        res.status(201).json(banner);
    } catch (error) {
        console.error('Error creating banner:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// PUT Update Banner (Admin Only)
router.put('/:id', authenticateToken, isAdmin, upload.single('image'), async (req, res) => {
    try {
        const banner = await Banner.findByPk(req.params.id);
        if (!banner) {
            return res.status(404).json({ message: 'Banner not found' });
        }

        const bannerData = req.body;

        // Handle Image Upload
        if (req.file) {
            const protocol = req.protocol;
            const host = req.get('host');
            bannerData.image = `${protocol}://${host}/uploads/banners/${req.file.filename}`;
        }

        await banner.update(bannerData);
        res.json(banner);
    } catch (error) {
        console.error('Error updating banner:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// DELETE Banner (Admin Only)
router.delete('/:id', authenticateToken, isAdmin, async (req, res) => {
    try {
        const banner = await Banner.findByPk(req.params.id);
        if (!banner) {
            return res.status(404).json({ message: 'Banner not found' });
        }

        await banner.destroy();
        res.json({ message: 'Banner deleted successfully' });
    } catch (error) {
        console.error('Error deleting banner:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

module.exports = router;
