import express from 'express'; import pool from '../database.js'; const router = express.Router(); // GET all students router.get('/', async (req, res) => { try { const [rows] = await pool.execute(` SELECT id, name, class, parent_name as parentName, parent_phone as parentPhone FROM students ORDER BY class, name `); res.json(rows); } catch (error) { console.error('Error fetching students:', error); res.status(500).json({ error: 'Failed to fetch students' }); } }); // GET single student router.get('/:id', async (req, res) => { try { const [rows] = await pool.execute(` SELECT id, name, class, parent_name as parentName, parent_phone as parentPhone FROM students WHERE id = ? `, [req.params.id]); if (rows.length === 0) { return res.status(404).json({ error: 'Student not found' }); } res.json(rows[0]); } catch (error) { console.error('Error fetching student:', error); res.status(500).json({ error: 'Failed to fetch student' }); } }); // POST create student router.post('/', async (req, res) => { try { const { id, name, class: studentClass, parentName, parentPhone } = req.body; await pool.execute(` INSERT INTO students (id, name, class, parent_name, parent_phone) VALUES (?, ?, ?, ?, ?) `, [id, name, studentClass, parentName, parentPhone]); res.status(201).json({ status: 'success', message: 'Student created' }); } catch (error) { console.error('Error creating student:', error); res.status(500).json({ error: 'Failed to create student' }); } }); // PUT update student router.put('/:id', async (req, res) => { try { const { name, class: studentClass, parentName, parentPhone } = req.body; await pool.execute(` UPDATE students SET name = ?, class = ?, parent_name = ?, parent_phone = ? WHERE id = ? `, [name, studentClass, parentName, parentPhone, req.params.id]); res.json({ status: 'success', message: 'Student updated' }); } catch (error) { console.error('Error updating student:', error); res.status(500).json({ error: 'Failed to update student' }); } }); // DELETE student router.delete('/:id', async (req, res) => { try { await pool.execute('DELETE FROM students WHERE id = ?', [req.params.id]); res.json({ status: 'success', message: 'Student deleted' }); } catch (error) { console.error('Error deleting student:', error); res.status(500).json({ error: 'Failed to delete student' }); } }); export default router;