prefix . self::TABLE_COMPONENTS; } /** * Verificar si las tablas necesitan ser creadas o actualizadas */ public function maybe_create_tables() { $installed_version = get_option(self::DB_VERSION_OPTION); if ($installed_version !== self::DB_VERSION) { $this->create_tables(); update_option(self::DB_VERSION_OPTION, self::DB_VERSION); } } /** * Crear tablas personalizadas */ public function create_tables() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $this->get_table_name(); $sql = "CREATE TABLE $table_name ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, component_name VARCHAR(50) NOT NULL, config_key VARCHAR(100) NOT NULL, config_value TEXT NOT NULL, data_type ENUM('string', 'boolean', 'integer', 'json') DEFAULT 'string', version VARCHAR(10) DEFAULT NULL, updated_at DATETIME NOT NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY component_config (component_name, config_key), INDEX idx_component (component_name), INDEX idx_updated (updated_at) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); // Verificar si la tabla se creó correctamente if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name) { error_log("APUS DB Manager: Tabla $table_name creada/actualizada exitosamente"); return true; } else { error_log("APUS DB Manager: Error al crear tabla $table_name"); return false; } } /** * Verificar si una tabla existe */ public function table_exists() { global $wpdb; $table_name = $this->get_table_name(); return $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; } /** * Guardar configuración de un componente * * @param string $component_name Nombre del componente * @param string $config_key Clave de configuración * @param mixed $config_value Valor de configuración * @param string $data_type Tipo de dato (string, boolean, integer, json) * @param string $version Versión del tema * @return bool|int ID del registro o false en caso de error */ public function save_config($component_name, $config_key, $config_value, $data_type = 'string', $version = null) { global $wpdb; $table_name = $this->get_table_name(); // Convertir valor según tipo if ($data_type === 'json' && is_array($config_value)) { $config_value = json_encode($config_value, JSON_UNESCAPED_UNICODE); } elseif ($data_type === 'boolean') { $config_value = $config_value ? '1' : '0'; } // Usar ON DUPLICATE KEY UPDATE para INSERT o UPDATE $result = $wpdb->query($wpdb->prepare( "INSERT INTO $table_name (component_name, config_key, config_value, data_type, version, updated_at) VALUES (%s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE config_value = VALUES(config_value), data_type = VALUES(data_type), version = VALUES(version), updated_at = VALUES(updated_at)", $component_name, $config_key, $config_value, $data_type, $version, current_time('mysql') )); return $result !== false ? $wpdb->insert_id : false; } /** * Obtener configuración de un componente * * @param string $component_name Nombre del componente * @param string $config_key Clave específica (opcional) * @return array|mixed Configuración completa o valor específico */ public function get_config($component_name, $config_key = null) { global $wpdb; $table_name = $this->get_table_name(); if ($config_key !== null) { // Obtener un valor específico $row = $wpdb->get_row($wpdb->prepare( "SELECT config_value, data_type FROM $table_name WHERE component_name = %s AND config_key = %s", $component_name, $config_key )); if ($row) { return $this->parse_value($row->config_value, $row->data_type); } return null; } // Obtener toda la configuración del componente $rows = $wpdb->get_results($wpdb->prepare( "SELECT config_key, config_value, data_type FROM $table_name WHERE component_name = %s", $component_name )); $config = array(); foreach ($rows as $row) { $config[$row->config_key] = $this->parse_value($row->config_value, $row->data_type); } return $config; } /** * Parsear valor según tipo de dato * * @param string $value Valor almacenado * @param string $data_type Tipo de dato * @return mixed Valor parseado */ private function parse_value($value, $data_type) { switch ($data_type) { case 'boolean': return (bool) $value; case 'integer': return (int) $value; case 'json': return json_decode($value, true); default: return $value; } } /** * Eliminar configuraciones de un componente * * @param string $component_name Nombre del componente * @param string $config_key Clave específica (opcional) * @return bool Éxito de la operación */ public function delete_config($component_name, $config_key = null) { global $wpdb; $table_name = $this->get_table_name(); if ($config_key !== null) { return $wpdb->delete( $table_name, array( 'component_name' => $component_name, 'config_key' => $config_key ), array('%s', '%s') ) !== false; } // Eliminar todas las configuraciones del componente return $wpdb->delete( $table_name, array('component_name' => $component_name), array('%s') ) !== false; } /** * Listar todos los componentes con configuraciones * * @return array Lista de nombres de componentes */ public function list_components() { global $wpdb; $table_name = $this->get_table_name(); return $wpdb->get_col( "SELECT DISTINCT component_name FROM $table_name ORDER BY component_name" ); } }