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

try {
    $pdo = getConnection();
    
    $query = "SELECT * FROM categorias ORDER BY nome";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $categorias = $stmt->fetchAll();
    
    $data = array();
    foreach ($categorias as $categoria) {
        $row = array();
        $row[] = $categoria['id'];
        $row[] = $categoria['nome'];
        $row[] = $categoria['descricao'];
        $row[] = '<button class="btn btn-sm btn-primary editar-categoria" data-id="'.$categoria['id'].'">Editar</button> 
                  <button class="btn btn-sm btn-danger excluir-categoria" data-id="'.$categoria['id'].'">Excluir</button>';
        $data[] = $row;
    }
    
    echo json_encode(array(
        "draw" => isset($_POST['draw']) ? intval($_POST['draw']) : 0,
        "recordsTotal" => count($categorias),
        "recordsFiltered" => count($categorias),
        "data" => $data
    ));
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(array("error" => "Erro ao carregar categorias: " . $e->getMessage()));
}
