<?php
require_once __DIR__ . '/../includes/config.php';

$createdBy = requireAuth();
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            if (isset($_GET['id'])) {
                $stmt = $pdo->prepare("
                    SELECT e.*, b.name as branch_name 
                    FROM employees e 
                    LEFT JOIN branches b ON e.branch_id = b.id 
                    WHERE e.id = ?
                ");
                $stmt->execute([$_GET['id']]);
                $employee = $stmt->fetch();
                
                if ($employee) {
                    jsonResponse($employee);
                } else {
                    jsonResponse(['error' => 'Funcionário não encontrado'], 404);
                }
            } else {
                $stmt = $pdo->query("
                    SELECT e.*, b.name as branch_name 
                    FROM employees e 
                    LEFT JOIN branches b ON e.branch_id = b.id 
                    ORDER BY e.name
                ");
                jsonResponse($stmt->fetchAll());
            }
            break;

        case 'POST':
            $data = getJsonInput();
            
            if (empty($data['name'])) {
                jsonResponse(['error' => 'Nome é obrigatório'], 400);
            }
            
            $id = generateId();
            
            $stmt = $pdo->prepare("
                INSERT INTO employees (id, name, cpf, phone, address, salary, branch_id, active, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, ?)
            ");
            $stmt->execute([
                $id,
                $data['name'],
                $data['cpf'] ?? null,
                $data['phone'] ?? null,
                $data['address'] ?? null,
                $data['salary'] ?? 0,
                $data['branch_id'] ?? null,
                $createdBy
            ]);
            
            $stmt = $pdo->prepare("SELECT * FROM employees WHERE id = ?");
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch(), 201);
            break;

        case 'PUT':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            $data = getJsonInput();
            
            if (empty($data['name'])) {
                jsonResponse(['error' => 'Nome é obrigatório'], 400);
            }
            
            $stmt = $pdo->prepare("
                UPDATE employees 
                SET name = ?, cpf = ?, phone = ?, address = ?, salary = ?, branch_id = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $data['name'],
                $data['cpf'] ?? null,
                $data['phone'] ?? null,
                $data['address'] ?? null,
                $data['salary'] ?? 0,
                $data['branch_id'] ?? null,
                $id
            ]);
            
            $stmt = $pdo->prepare("SELECT * FROM employees WHERE id = ?");
            $stmt->execute([$id]);
            $employee = $stmt->fetch();
            if ($employee) {
                jsonResponse($employee);
            } else {
                jsonResponse(['error' => 'Funcionário não encontrado'], 404);
            }
            break;

        case 'DELETE':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            $stmt = $pdo->prepare("UPDATE employees SET active = FALSE WHERE id = ?");
            $stmt->execute([$id]);
            
            if ($stmt->rowCount() > 0) {
                jsonResponse(['success' => true]);
            } else {
                jsonResponse(['error' => 'Funcionário não encontrado'], 404);
            }
            break;

        default:
            jsonResponse(['error' => 'Método não permitido'], 405);
    }
} catch (PDOException $e) {
    jsonResponse(['error' => 'Erro no banco de dados: ' . $e->getMessage()], 500);
}
