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

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

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

// Create new scholarship
router.post('/create', upload.single('banner'), (req, res) => {
    const {
        sProgrammeName,
        country,
        university,
        closingDate,
        description,
        instituteWebsite,
        institutePhone,
        instituteEmail,
        institute_id
    } = req.body;

    // Ensure all required fields are provided
    if (!sProgrammeName || !country || !university || !closingDate || !description ||
        !instituteWebsite || !institutePhone || !instituteEmail || !institute_id) {
        return res.status(400).json({ message: "Please fill in all required fields" });
    }

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

    // SQL query to insert a new scholarship
    const saveScholarship = `
        INSERT INTO scholarships (
            sProgrammeName, country, university, closingDate, description, instituteWebsite, institutePhone, 
            instituteEmail, banner, institute_id, approved, deleted
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,  FALSE, FALSE)
    `;

    const saveValues = [
        sProgrammeName, country, university, closingDate, description, instituteWebsite, institutePhone,
        instituteEmail, banner, institute_id
    ];

    db.query(saveScholarship, saveValues, (err, result) => {
        if (err) {
            console.error('Error saving scholarship:', err);
            return res.status(500).json({ message: 'Server error' });
        }
        res.status(200).json({ message: 'Scholarship added successfully' });
    });
});

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

    if (country) {  
        query += ' AND country = ?';
        values.push(country);
      }
  
    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 scholarships
  router.get('/deleted', (req, res) => {
    const { institute_id } = req.query;
    let query = 'SELECT * FROM scholarships 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 stdLoans to deleted state
  router.post('/delete/:id', (req, res) => {
    const query = 'UPDATE scholarships 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: ' Scholarship moved to deleted state' });
    });
  });
  
  // Get all non-deleted and non-approved scholarships
  router.get('/pending', (req, res) => {
    const { institute_id } = req.query;
    let query = 'SELECT * FROM scholarships 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 scholarships from created state
  router.post('/approve/:id', (req, res) => {
    const query = 'UPDATE scholarships 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: 'Scholarship approved' });
    });
  });
  
  // Restore scholarships from deleted state
  router.post('/restore/:id', (req, res) => {
    const query = 'UPDATE scholarships 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: 'Scholarship restored successfully' });
    });
  });
  
  // Permanently delete scholarships
  router.delete('/delete/permanent/:id', (req, res) => {
    const query = 'DELETE FROM scholarships 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: 'Scholarship permanently deleted' });
    });
  });
  
  // Get stdLoans by scholarships ID
  router.get('/:id', (req, res) => {
    const id = req.params.id;
    db.query('SELECT * FROM scholarships WHERE id = ?', [id], (error, result) => {
      if (error) {
        console.error('Error retrieving data:', error);
        return res.status(500).send('Server error');
      }
      res.json(result[0]);
    });
  });
  
module.exports = router;
