const express = require('express');
const router = express.Router();
const db = require('../models');
const Popup = db.Popup;
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Multer setup
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads/popup'),
  filename: (req, file, cb) =>
    cb(null, 'popup_' + Date.now() + path.extname(file.originalname)),
});
const upload = multer({ storage });

// GET popup
router.get('/', async (req, res) => {
  try {
    const popup = await Popup.findOne();
    if (!popup) return res.json({});
    res.json({ image: popup.image });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to fetch popup' });
  }
});

// POST popup (Upload or Replace)
router.post('/', upload.single('image'), async (req, res) => {
  try {
    // Delete old popup if exists
    const existing = await Popup.findOne();
    if (existing) {
      const oldImagePath = path.join(__dirname, '..', existing.image);
      if (fs.existsSync(oldImagePath)) {
        fs.unlinkSync(oldImagePath);
      }
      await existing.destroy();
    }

    // Save new popup
    const newPopup = await Popup.create({
      image: `uploads/popup/${req.file.filename}`
    });

    res.status(201).json(newPopup);
  } catch (err) {
    console.error('Upload error:', err);
    res.status(500).json({ error: 'Failed to upload popup' });
  }
});

// DELETE popup image
router.delete('/', async (req, res) => {
  try {
    const popup = await Popup.findOne();
    if (!popup) return res.status(404).json({ message: 'Popup not found' });

    const imagePath = path.join(__dirname, '..', popup.image);
    if (fs.existsSync(imagePath)) {
      fs.unlinkSync(imagePath);
    }

    await popup.destroy();
    res.json({ message: 'Popup deleted' });
  } catch (err) {
    console.error('Delete error:', err);
    res.status(500).json({ error: 'Failed to delete popup' });
  }
});

module.exports = router;
