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

try {
    require_once '../core/api.php';

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

    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Error al decodificar JSON en services-categories-create.php: " . json_last_error_msg());
        throw new Exception('ERROR AL PROCESAR DATOS');
    }
    if (!isset($data['name']) || empty(trim($data['name']))) {
        throw new Exception('NOMBRE REQUERIDO');
    }

    $name = filter_var(trim($data['name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM service_categories WHERE name = ?");
    $stmtCheck->execute([$name]);
    if ($stmtCheck->fetchColumn() > 0) {
        throw new Exception('CATEGORIA YA EXISTE');
    }

    $sql = "INSERT INTO service_categories (name) VALUES (?)";
    $stmt = $pdo->prepare($sql);
    
    if ($stmt->execute([$name])) {
        $last_id = $pdo->lastInsertId();
        $response = ['success' => true, 'message' => 'CATEGORIA CREADA', 'id' => (int)$last_id, 'name' => $name]; 
    } else {
        throw new Exception('FALLO AL EJECUTAR INSERCION');
    }
} catch (PDOException $e) {
    error_log("PDO Error en services-categories-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("General Error en services-categories-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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