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

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

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

// Check if the event already exists
const checkEventExists = (university, eventName, institute_id, callback) => {
  const checkEventQuery = 'SELECT * FROM events WHERE university = ? AND eventName = ? AND institute_id = ?';
  db.query(checkEventQuery, [university, eventName, institute_id], (err, results) => {
    if (err) {
      console.error('Error checking event existence:', err);
      return callback(err);
    }
    callback(null, results.length > 0);
  });
};

// Save event data to database
router.post('/create', upload.single('banner'), (req, res) => {
  const {
    university,
    universityType,
    eventName,
    venue,
    date,
    time,
    link,
    description,
    inWebsite,
    instituteAddress,
    institutePhone,
    instituteEmail,
    institute_id
  } = req.body;

  // Check for required fields
  if (!university || !universityType || !eventName || !venue || !date || !time || !institute_id) {
    return res.status(400).json({ message: "Please fill in all required fields" });
  }

  // Check if the event already exists
  checkEventExists(university, eventName, institute_id, (err, exists) => {
    if (err) {
      return res.status(500).json({ message: 'Server error while checking event existence' });
    }
    if (exists) {
      return res.status(400).json({ message: 'Event already exists' });
    }

    // Insert new event
    const banner = req.file ? req.file.filename : null;
    const saveEvent = `
      INSERT INTO events (
        university, universityType, eventName, venue, date, time, link, description, banner, inWebsite,
        instituteAddress, institutePhone, instituteEmail, institute_id, deleted, approved
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE, FALSE)
    `;
    const saveValues = [
      university, universityType, eventName, venue, date, time, link, description, banner, inWebsite,
      instituteAddress, institutePhone, instituteEmail, institute_id
    ];

    db.query(saveEvent, saveValues, (err, result) => {
      if (err) {
        console.error('Error inserting event:', err);
        return res.status(500).json({ message: 'Server error while inserting event' });
      }
      res.json({ message: 'Event created successfully' });
    });
  });
});

// Update event details
router.post('/update/:id', upload.single('banner'), (req, res) => {
  const {
    university, universityType, eventName, venue, date, time, link, description,
    inWebsite, instituteAddress, institutePhone, instituteEmail
  } = req.body;

  const banner = req.file ? req.file.filename : null;

  const updateEvent = `
    UPDATE events SET
    university = ?, universityType = ?, eventName = ?, venue = ?, date = ?, time = ?, link = ?, description = ?, banner = ?, inWebsite = ?, instituteAddress = ?, institutePhone = ?, instituteEmail = ?
    WHERE id = ?
  `;
  const updateValues = [
    university, universityType, eventName, venue, date, time, link, description, banner,
    inWebsite, instituteAddress, institutePhone, instituteEmail, req.params.id
  ];

  db.query(updateEvent, updateValues, (err, result) => {
    if (err) {
      console.error('Error updating event:', err);
      return res.status(500).send('Server error');
    }
    res.json({ message: 'Event updated successfully' });
  });
});

// Get all approved and non-deleted events with optional filters
router.get('/all', (req, res) => {
  const { universityType, institute_id } = req.query;
  let query = 'SELECT * FROM events WHERE deleted = FALSE AND approved = TRUE';
  const values = [];

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

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

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

// Get all deleted events
router.get('/deleted', (req, res) => {
  const { institute_id } = req.query;
  let query = 'SELECT * FROM events WHERE deleted = TRUE';
  const values = [];

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

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

// Move event to deleted state
router.post('/delete/:id', (req, res) => {
  const query = 'UPDATE events SET deleted = TRUE WHERE id = ?';
  const values = [req.params.id];
  db.query(query, values, (err, result) => {
    if (err) {
      console.error('Error updating data:', err);
      return res.status(500).send('Server error');
    }
    res.json({ message: 'Event moved to deleted state' });
  });
});

// Get all non-deleted and non-approved events
router.get('/pending', (req, res) => {
  const { institute_id } = req.query;
  let query = 'SELECT * FROM events WHERE deleted = FALSE AND approved = FALSE';
  const values = [];

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

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

// Approve event from created state
router.post('/approve/:id', (req, res) => {
  const query = 'UPDATE events SET approved = TRUE WHERE id = ?';
  const values = [req.params.id];
  db.query(query, values, (err, result) => {
    if (err) {
      console.error('Error updating data:', err);
      return res.status(500).send('Server error');
    }
    res.json({ message: 'Event approved' });
  });
});

// Restore event from deleted state
router.post('/restore/:id', (req, res) => {
  const query = 'UPDATE events SET deleted = FALSE WHERE id = ?';
  const values = [req.params.id];
  db.query(query, values, (err, result) => {
    if (err) {
      console.error('Error updating data:', err);
      return res.status(500).send('Server error');
    }
    res.json({ message: 'Event restored successfully' });
  });
});

// Permanently delete event
router.delete('/delete/permanent/:id', (req, res) => {
  const query = 'DELETE FROM events WHERE id = ?';
  const values = [req.params.id];
  db.query(query, values, (err, result) => {
    if (err) {
      console.error('Error deleting data:', err);
      return res.status(500).send('Server error');
    }
    res.json({ message: 'Event permanently deleted' });
  });
});

// Get event by event ID
router.get('/:id', (req, res) => {
  const id = req.params.id;
  db.query('SELECT * FROM events WHERE id = ?', [id], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    if (results.length === 0) {
      return res.status(404).json({ message: 'Event not found' });
    }
    res.json(results[0]);
  });
});


module.exports = router;
