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) => {
    cb(null, 'Upload/images/courses');
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname));
  }
});

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

// Save course data to database
router.post('/create', upload.single('cologo'), (req, res) => {
  const {
    university,
    universityType,
    courseName,
    level,
    duration,
    startDate,
    category,
    specification,
    courseFee,
    careerOpportunities,
    industry,
    codescription,
    instituteAddress,
    institutePhone,
    instituteEmail,
    instituteLocation,
    institute_id
  } = req.body;

  // Check for required fields
  if (!university || !universityType || !courseName || !level || !duration || !startDate || !institute_id) {
    return res.status(400).json({ message: "Please fill in all required fields" });
  }

  // Check if the course already exists
  const checkCourseQuery = 'SELECT * FROM courses WHERE university = ? AND courseName = ? AND institute_id = ?';
  db.query(checkCourseQuery, [university, courseName, institute_id], (err, results) => {
    if (err) {
      console.error('Error checking course existence:', err);
      return res.status(500).json({ message: 'Server error while checking course existence' });
    }

    if (results.length > 0) {
      return res.status(400).json({ message: 'Course already exists' });
    }

    // Insert new course
    const cologo = req.file ? req.file.filename : null;
    const saveCourse = `
      INSERT INTO courses (
        university, universityType, courseName, level, duration, startDate, category, specification, courseFee,
        careerOpportunities, industry, cologo, codescription, instituteAddress, institutePhone,
        instituteEmail, instituteLocation, institute_id, deleted, approved
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE, FALSE)
    `;
    const saveValues = [
      university, universityType, courseName, level, duration, startDate, category, specification, courseFee,
      careerOpportunities, industry, cologo, codescription, instituteAddress, institutePhone,
      instituteEmail, instituteLocation, institute_id
    ];

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

// Update course details
router.post('/update/:id', upload.single('cologo'), (req, res) => {
  const {
    university, universityType, courseName, level, duration, startDate,
    category, specification, courseFee, careerOpportunities, industry, codescription,
    instituteAddress, institutePhone, instituteEmail, instituteLocation
  } = req.body;

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

  const updateCourse = `
    UPDATE courses SET
    university = ?, universityType = ?, courseName = ?, level = ?, duration = ?, startDate = ?, category = ?, specification = ?, courseFee = ?, careerOpportunities = ?, industry = ?, cologo = ?, codescription = ?, instituteAddress = ?, institutePhone = ?, instituteEmail = ?, instituteLocation = ?
    WHERE id = ?
  `;
  const updateValues = [
    university, universityType, courseName, level, duration, startDate,
    category, specification, courseFee, careerOpportunities, industry, cologo,
    codescription, instituteAddress, institutePhone, instituteEmail, instituteLocation, req.params.id
  ];

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

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

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

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

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

  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 courses
router.get('/deleted', (req, res) => {
  const { institute_id } = req.query;
  let query = 'SELECT * FROM courses 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 course to deleted state
router.post('/delete/:id', (req, res) => {
  const query = 'UPDATE courses 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: 'Course moved to deleted state' });
  });
});

// Get all non-deleted and non-approved courses
router.get('/pending', (req, res) => {
  const { institute_id } = req.query;
  let query = 'SELECT * FROM courses 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 course from created state
router.post('/approve/:id', (req, res) => {
  const query = 'UPDATE courses 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: 'Course approved' });
  });
});

// Restore course from deleted state
router.post('/restore/:id', (req, res) => {
  const query = 'UPDATE courses 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: 'Course restored successfully' });
  });
});

// Permanently delete course
router.delete('/delete/permanent/:id', (req, res) => {
  const query = 'DELETE FROM courses 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: 'Course permanently deleted' });
  });
});

// Get course by course ID
router.get('/:id', (req, res) => {
  const id = req.params.id;
  db.query('SELECT * FROM courses 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: 'Course not found' });
    }
    res.json(results[0]);
  });
});

module.exports = router;
