<?php
// includes/config_helper.php

function getConfigValue($key, $id_usuario, $default_value = null) {
    global $pdo; // Assumes $pdo is available globally from db.php

    // First, try to get user-specific configuration
    try {
        $stmt = $pdo->prepare("SELECT valor_config FROM configuraciones WHERE id_usuario = :id_usuario AND clave_config = :clave_config");
        $stmt->execute([':id_usuario' => $id_usuario, ':clave_config' => $key]);
        $value = $stmt->fetchColumn();
        if ($value !== false) {
            return $value;
        }
    } catch (PDOException $e) {
        // Log the error but continue to try global or default
        error_log("Error fetching user config for $key and user $id_usuario: " . $e->getMessage());
    }

    // If no user-specific config, try to get global configuration (id_usuario IS NULL)
    try {
        $stmt = $pdo->prepare("SELECT valor_config FROM configuraciones WHERE id_usuario IS NULL AND clave_config = :clave_config");
        $stmt->execute([':clave_config' => $key]);
        $value = $stmt->fetchColumn();
        if ($value !== false) {
            return $value;
        }
    } catch (PDOException $e) {
        error_log("Error fetching global config for $key: " . $e->getMessage());
    }

    // If neither found, return default value
    return $default_value;
}
?>