const express = require('express');
const bcrypt = require('bcryptjs');
const { query } = require('../db');
const auth = require('../middleware/auth');

const router = express.Router();

router.get('/', auth(), async (req, res) => {
  const { companyId, departmentId } = req.query;
  const rows = await query(
    'SELECT id, company_id, department_id, name, email, phone, role, is_active FROM employees WHERE (? IS NULL OR company_id = ?) AND (? IS NULL OR department_id = ?) ORDER BY id DESC',
    [companyId || null, companyId || null, departmentId || null, departmentId || null]
  );
  res.json(rows);
});

router.post('/', auth(), async (req, res) => {
  const { companyId, departmentId, name, email, phone, role = 'EMPLOYEE', password } = req.body;
  if (!companyId || !departmentId || !name || !email || !password) return res.status(400).json({ error: 'Missing fields' });
  const hash = await bcrypt.hash(password, 10);
  await query('INSERT INTO employees (company_id, department_id, name, email, phone, role, password_hash, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, 1)',
    [companyId, departmentId, name, email, phone || null, role, hash]);
  res.status(201).json({ ok: true });
});

router.put('/:id', auth(), async (req, res) => {
  const { name, email, phone, role, is_active, departmentId } = req.body;
  await query('UPDATE employees SET name = ?, email = ?, phone = ?, role = ?, is_active = ?, department_id = ? WHERE id = ?',
    [name, email, phone, role, is_active ? 1 : 0, departmentId, req.params.id]);
  res.json({ ok: true });
});

router.delete('/:id', auth(), async (req, res) => {
  await query('DELETE FROM employees WHERE id = ?', [req.params.id]);
  res.json({ ok: true });
});

module.exports = router;
