<?php 
ob_start();
header('Content-Type: application/json');
$response_data = ['success' => false, 'categories' => [], 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    $stmt = $pdo->query("SELECT id, name FROM service_categories ORDER BY name ASC");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_categories = [];
    foreach ($categories as $category) {
        $formatted_categories[] = [
            'id' => (int)$category['id'],
            'name' => filter_var($category['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)
        ];
    }

    $response_data = ['success' => true, 'categories' => $formatted_categories];
} catch (PDOException $e) {
    error_log("Error PDO al cargar categorías en services-categories-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general al cargar categorías en services-categories-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR INESPERADO';
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response_data);
exit;
?>