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

requireAuth();

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;

switch ($method) {
    case 'GET':
        if ($id) {
            $stmt = $pdo->prepare('SELECT * FROM categories WHERE id = ?');
            $stmt->execute([$id]);
            $category = $stmt->fetch();
            if ($category) {
                jsonResponse($category);
            } else {
                jsonResponse(['error' => 'Categoria não encontrada'], 404);
            }
        } else {
            $type = $_GET['type'] ?? null;
            if ($type) {
                $stmt = $pdo->prepare('SELECT * FROM categories WHERE type = ? ORDER BY name');
                $stmt->execute([$type]);
            } else {
                $stmt = $pdo->query('SELECT * FROM categories ORDER BY type, name');
            }
            jsonResponse($stmt->fetchAll());
        }
        break;

    case 'POST':
        $data = getJsonInput();
        $id = generateId();
        $stmt = $pdo->prepare('INSERT INTO categories (id, name, type, description) VALUES (?, ?, ?, ?)');
        $stmt->execute([
            $id,
            $data['name'] ?? '',
            $data['type'] ?? 'expense',
            $data['description'] ?? null
        ]);
        
        $stmt = $pdo->prepare('SELECT * FROM categories WHERE id = ?');
        $stmt->execute([$id]);
        jsonResponse($stmt->fetch(), 201);
        break;

    case 'PUT':
        if (!$id) jsonResponse(['error' => 'ID obrigatório'], 400);
        $data = getJsonInput();
        $stmt = $pdo->prepare('UPDATE categories SET name = ?, type = ?, description = ? WHERE id = ?');
        $stmt->execute([
            $data['name'] ?? '',
            $data['type'] ?? 'expense',
            $data['description'] ?? null,
            $id
        ]);
        
        $stmt = $pdo->prepare('SELECT * FROM categories WHERE id = ?');
        $stmt->execute([$id]);
        $category = $stmt->fetch();
        if ($category) {
            jsonResponse($category);
        } else {
            jsonResponse(['error' => 'Categoria não encontrada'], 404);
        }
        break;

    case 'DELETE':
        if (!$id) jsonResponse(['error' => 'ID obrigatório'], 400);
        $stmt = $pdo->prepare('DELETE FROM categories WHERE id = ?');
        $stmt->execute([$id]);
        if ($stmt->rowCount() > 0) {
            jsonResponse(['success' => true]);
        } else {
            jsonResponse(['error' => 'Categoria não encontrada'], 404);
        }
        break;

    default:
        jsonResponse(['error' => 'Método não permitido'], 405);
}
