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

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

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

// Create new tuition class
router.post('/create', upload.single('cbanner'), (req, res) => {
    const {
        id,
        className,
        classType,
        subject,
        district,
        classLevel,
        startDate,
        time,
        classFee,
        description,
        teacherName,
        teacherQualification,
        teacherEmail,
        contact,
        location,
    } = req.body;

    console.log('Received fields:', req.body);

    if (!id || !className || !classType || !subject || !district || !classLevel || !teacherName || !teacherQualification || !teacherEmail || !contact || !location) {
        return res.status(400).json({ message: "Please fill in all required fields" });
    }

    const cbanner = req.file ? req.file.filename : null;
    console.log('Uploading file:', cbanner);

    const saveClass = `
        INSERT INTO tuition (
            id, className, classType, subject,district, classLevel, startDate, time, classFee,  cbanner, description,
            teacherName, teacherQualification, teacherEmail, contact, location, deleted, approved
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE, FALSE)
    `;
    const saveValues = [
        id, className, classType, subject, district, classLevel, startDate, time, classFee, cbanner, description,
        teacherName, teacherQualification, teacherEmail, contact, location, 
    ];

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

  
// Update class details
router.post('/update/:id', upload.single('cbanner'), (req, res) => {
  const {
    className, classType, subject, district, classLevel, startDate, time, classFee,
    description, teacherName, teacherQualification, teacherEmail, contact, location
  } = req.body;

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

  const updateClass = `
    UPDATE tuition SET
    className = ?, classType = ?, subject = ?, district = ?, classLevel = ?, startDate = ?, time = ?, classFee = ?, description = ?,
    teacherName = ?, teacherQualification = ?, teacherEmail = ?, contact = ?, location = ?, cbanner = ?
    WHERE id = ?
  `;
  const updateValues = [
    className, classType, subject, district, classLevel, startDate, time, classFee,
    description, teacherName, teacherQualification, teacherEmail, contact, location, cbanner, req.params.id
  ];

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


// Get all approved and non-deleted tuition classes with optional filters
router.get('/all', (req, res) => {
    const { classType, subject, classLevel, id } = req.query;
    let query = 'SELECT * FROM tuition WHERE deleted = FALSE AND approved = TRUE';
    const values = [];
  
    if (classType) {
      query += ' AND classType = ?';
      values.push(classType);
    }
    if (subject) {
      query += ' AND subject = ?';
      values.push(subject);
    }
    if (classLevel) {
      query += ' AND classLevel = ?';
      values.push(classLevel);
    }
    if (id) {
      query += ' AND id = ?';
      values.push(id);
    }
  
    db.query(query, values, (err, results) => {
      if (err) {
        console.error('Error fetching classes:', err);
        return res.status(500).json({ message: 'Server error while fetching classes' });
      }
      res.json(results);
    });
  });
  

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

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

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

// Move class to deleted state
router.post('/delete/:id', (req, res) => {
  const query = 'UPDATE tuition 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).json({ message: 'Server error' });
    }
    res.json({ message: 'Class moved to deleted state' });
  });
});

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

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

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

// Approve class from created state
router.post('/approve/:id', (req, res) => {
  const query = 'UPDATE tuition 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).json({ message: 'Server error' });
    }
    res.json({ message: 'Class approved' });
  });
});

// Restore class from deleted state
router.post('/restore/:id', (req, res) => {
  const query = 'UPDATE tuition 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).json({ message: 'Server error' });
    }
    res.json({ message: 'Class restored successfully' });
  });
});

// Permanently delete class
router.delete('/delete/permanent/:id', (req, res) => {
  const query = 'DELETE FROM tuition 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).json({ message: 'Server error' });
    }
    res.json({ message: 'Class permanently deleted' });
  });
});

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

module.exports = router;
