import express from 'express'; import pool from '../database.js'; const router = express.Router(); // GET all violations router.get('/', async (req, res) => { try { const [rows] = await pool.execute(` SELECT id, student_id as studentId, rule_id as ruleId, date, description, score, sanction, timestamp, photo_url as photoUrl FROM violations ORDER BY timestamp DESC `); res.json(rows); } catch (error) { console.error('Error fetching violations:', error); res.status(500).json({ error: 'Failed to fetch violations' }); } }); // GET violations by student router.get('/student/:studentId', async (req, res) => { try { const [rows] = await pool.execute(` SELECT id, student_id as studentId, rule_id as ruleId, date, description, score, sanction, timestamp, photo_url as photoUrl FROM violations WHERE student_id = ? ORDER BY timestamp DESC `, [req.params.studentId]); res.json(rows); } catch (error) { console.error('Error fetching student violations:', error); res.status(500).json({ error: 'Failed to fetch violations' }); } }); // POST create violation router.post('/', async (req, res) => { try { const { id, studentId, ruleId, date, description, score, sanction, timestamp, photoUrl } = req.body; await pool.execute(` INSERT INTO violations (id, student_id, rule_id, date, description, score, sanction, timestamp, photo_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `, [id || Date.now().toString(), studentId, ruleId, date, description, score, sanction || '-', timestamp || Date.now(), photoUrl || null]); res.status(201).json({ status: 'success', message: 'Violation recorded' }); } catch (error) { console.error('Error creating violation:', error); res.status(500).json({ error: 'Failed to create violation' }); } }); // DELETE violation router.delete('/:id', async (req, res) => { try { await pool.execute('DELETE FROM violations WHERE id = ?', [req.params.id]); res.json({ status: 'success', message: 'Violation deleted' }); } catch (error) { console.error('Error deleting violation:', error); res.status(500).json({ error: 'Failed to delete violation' }); } }); export default router;