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

// Configure multer for file uploads
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../Upload/images/intschls'));
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  },
});

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

// Create a new international school
router.post('/create', upload.single('logo'), (req, res) => {
  const {
    id,
    intschlName,
    branchestableRows,
    commonEmail,
    commonPhone,
    studyLevel,
    description,
    facilities,
    mainLocation,
    website, 
  } = req.body;

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

  // Validate required fields
  if (!intschlName || !commonEmail || !commonPhone || !id || !mainLocation || !website) {
    return res.status(400).json({ error: 'Please fill in all required fields.' });
  }

  let parsedBranches;

  try {
    parsedBranches = JSON.parse(branchestableRows);
  } catch (error) {
    console.error('Error parsing branchestableRows:', error);
    return res.status(400).json({ error: 'Invalid format for branch information.' });
  }

  const schoolData = {
    id,
    logo,
    intschlName,
    branchestableRows: JSON.stringify(parsedBranches),
    commonEmail,
    commonPhone,
    studyLevel,
    description,
    facilities,
    mainLocation,
    website, 
  };

  const sql = 'INSERT INTO international_schools SET ?';

  db.query(sql, schoolData, (err, result) => {
    if (err) {
      console.error('Error inserting data:', err);
      return res.status(500).json({ error: 'An error occurred while saving the school.' });
    }

    res.status(200).json({ message: 'International School registered successfully!' });
  });
});

const transporter = nodemailer.createTransport({
  service: 'gmail', 
  auth: {
      user: 'randyruch5@gmail.com',
      pass: 'luxlrqakfenxkyzi'
  }
});

router.post('/send', (req, res) => {
  const { id, name, email, subject, message } = req.body;

  const mailOptions = {
      from: 'your-email@gmail.com',
      to: email,
      subject: subject,
      text: message
  };

  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          console.error('Error sending email:', error);
          return res.status(500).json({ error: 'Failed to send email' });
      }
      res.status(200).json({ message: 'Email sent successfully' });
  });
});


// Update school details
router.put('/update/:id', upload.single('logo'), (req, res) => {
  const id = req.params.id;
  const {
    intschlName,
    branchestableRows,
    commonEmail,
    commonPhone,
    studyLevel,
    description,
    facilities,
    mainLocation,
    website, 
  } = req.body;

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

  let parsedBranches;

  try {
    parsedBranches = JSON.parse(branchestableRows);
  } catch (error) {
    console.error('Error parsing branchestableRows:', error);
    return res.status(400).json({ error: 'Invalid format for branch information.' });
  }

  const updatedData = {
    intschlName,
    branchestableRows: JSON.stringify(parsedBranches),
    commonEmail,
    commonPhone,
    studyLevel,
    description,
    facilities,
    mainLocation,
    website, 
    ...(logo && { logo }),
  };

  const sql = 'UPDATE international_schools SET ? WHERE id = ?';

  db.query(sql, [updatedData, id], (err, result) => {
    if (err) {
      console.error('Error updating data:', err);
      return res.status(500).json({ error: 'An error occurred while updating the school.' });
    }

    res.status(200).json({ message: 'International School updated successfully!' });
  });
});

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

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

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

    results.forEach(school => {
      if (school.branchestableRows) {
        try {
          school.branchestableRows = JSON.parse(school.branchestableRows);
        } catch (err) {
          console.error('Error parsing branchestableRows:', err);
        }
      }
    });

    res.json(results);
  });
});

// Get all deleted international schools
router.get('/deleted', (req, res) => {
  const query = 'SELECT * FROM international_schools WHERE deleted = TRUE';
  db.query(query, (err, results) => {
    if (err) {
      console.error('Error getting data:', err);
      return res.status(500).send('Server error');
    }
    res.json(results);
  });
});

// Move international schools to deleted state
router.post('/delete/:id', (req, res) => {
  const query = 'UPDATE international_schools 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: 'International School moved to deleted state' });
  });
});

// Get all non-deleted and non-approved international schools
router.get('/pending', (req, res) => {
  const query = 'SELECT * FROM international_schools WHERE deleted = FALSE AND approved = FALSE';
  db.query(query, (err, results) => {
    if (err) {
      console.error('Error getting data:', err);
      return res.status(500).send('Server error');
    }
    res.json(results);
  });
});

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

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

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

// Get International School by ID
router.get('/:id', (req, res) => {
  const id = req.params.id;
  db.query('SELECT * FROM international_schools WHERE id = ?', [id], (error, result) => {
    if (error) {
      console.error('Error retrieving data:', error);
      return res.status(500).send('Server error');
    }

    const school = result[0];
    if (school && school.branchestableRows) {
      try {
        school.branchestableRows = JSON.parse(school.branchestableRows);
      } catch (err) {
        console.error('Error parsing branchestableRows:', err);
        return res.status(500).send('Error parsing branchestableRows.');
      }
    }

    res.json(school);
  });
});

module.exports = router;
