const db = require('../config/db');

exports.getAllUsers = async (req, res) => {
    const [rows] = await db.query('SELECT * FROM users');
    res.json(rows);
};

exports.getUserById = async (req, res) => {
    const [rows] = await db.query('SELECT * FROM users WHERE id = ?', [req.params.id]);
    if (rows.length === 0) return res.status(404).json({ error: 'User not found' });
    res.json(rows[0]);
};

exports.createUser = async (req, res) => {
    const { first_name, last_name, email, password_hash, role } = req.body;
    await db.query('INSERT INTO users (first_name, last_name, email, password_hash, role) VALUES (?, ?, ?, ?, ?)',
        [first_name, last_name, email, password_hash, role]);
    res.status(201).json({ message: 'User created' });
};

exports.updateUser = async (req, res) => {
    const { first_name, last_name, email, password_hash, role } = req.body;
    await db.query('UPDATE users SET first_name = ?, last_name = ?, email = ?, password_hash = ?, role = ? WHERE id = ?',
        [first_name, last_name, email, password_hash, role, req.params.id]);
    res.json({ message: 'User updated' });
};

exports.deleteUser = async (req, res) => {
    await db.query('DELETE FROM users WHERE id = ?', [req.params.id]);
    res.status(204).send();
};

exports.getUserGroups = async (req, res) => {
    const [rows] = await db.query(`
    SELECT g.* FROM groups g
    JOIN group_users gu ON gu.group_id = g.id
    WHERE gu.user_id = ?
  `, [req.params.id]);
    res.json(rows);
};

exports.getUserCours = async (req, res) => {
    const [rows] = await db.query(`
    SELECT DISTINCT c.* FROM courses c
    JOIN group_cours gc ON gc.course_id = c.id
    JOIN group_users gu ON gu.group_id = gc.group_id
    WHERE gu.user_id = ?
  `, [req.params.id]);
    res.json(rows);
};
