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

// Endpoint to submit the application form
router.post('/apply', (req, res) => {
    const { 
        name, 
        mobile, 
        dob, 
        address, 
        district, 
        province, 
        email, 
        levelOfStudy, 
        message, 
        institute_id, 
        courses_id 
    } = req.body;

    // Check if all required fields are provided
    if (!name || !mobile || !dob || !address || !district || !province || !email || !levelOfStudy) {
        return res.status(400).json({ message: 'Please fill in all required fields' });
    }
    
    // Improved duplicate check
    const checkQuery = 'SELECT * FROM appliedforms WHERE name = ? AND email = ? AND mobile = ? AND dob = ?';
    db.query(checkQuery, [name, email, mobile, dob], (checkError, checkResults) => {
        if (checkError) {
            console.error('Error checking existing records:', checkError);
            return res.status(500).json({ message: 'Failed to check existing applications', error: checkError.message });
        }
    
        if (checkResults.length > 0) {
            return res.status(400).json({ message: 'Application with this name, email, and mobile number already exists' });
        }
    
        // Insert the new record
        const insertQuery = 'INSERT INTO appliedforms (name, mobile, dob, address, district, province, email, levelOfStudy, message, institute_id, courses_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
        
        db.query(insertQuery, [name, mobile, dob, address, district, province, email, levelOfStudy, message, institute_id, courses_id], (insertError, insertResults) => {
            if (insertError) {
                console.error('Error inserting data:', insertError);
                return res.status(500).json({ message: 'Failed to submit application', error: insertError.message });
            }
            res.status(200).json({ message: 'Application submitted successfully' });
        });
    });
});
    
// Endpoint to get all applied forms
router.get('/appliedforms', (req, res) => {
    const query = 'SELECT * FROM appliedforms ORDER BY id DESC';

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

module.exports = router;
