prefix . 'ai_seo_log'; } /** * Creates or upgrades the log table. */ public static function install(): void { global $wpdb; $table = self::table(); $charset = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$table} ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, created_at DATETIME NOT NULL, module VARCHAR(40) NOT NULL DEFAULT '', action VARCHAR(40) NOT NULL DEFAULT '', object_id BIGINT UNSIGNED NOT NULL DEFAULT 0, provider VARCHAR(20) NOT NULL DEFAULT '', model VARCHAR(80) NOT NULL DEFAULT '', input_tokens INT UNSIGNED NOT NULL DEFAULT 0, output_tokens INT UNSIGNED NOT NULL DEFAULT 0, cost DECIMAL(12,6) NOT NULL DEFAULT 0, status VARCHAR(20) NOT NULL DEFAULT 'ok', message TEXT NULL, undo_meta LONGTEXT NULL, PRIMARY KEY (id), KEY created_at (created_at), KEY module_action (module, action), KEY object_id (object_id) ) {$charset};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); update_option( 'ai_seo_tools_db_version', self::DB_VERSION, false ); } /** * Makes sure the table exists (cheap option check, no query). */ public static function maybe_install(): void { if ( get_option( 'ai_seo_tools_db_version' ) !== self::DB_VERSION ) { self::install(); } } /** * Writes a row. * * @param array $row Row data. * @return int Inserted row id, 0 on failure. */ public static function record( array $row ): int { global $wpdb; $defaults = array( 'created_at' => current_time( 'mysql' ), 'module' => '', 'action' => '', 'object_id' => 0, 'provider' => '', 'model' => '', 'input_tokens' => 0, 'output_tokens' => 0, 'cost' => 0, 'status' => 'ok', 'message' => null, 'undo_meta' => null, ); $row = wp_parse_args( $row, $defaults ); if ( is_array( $row['undo_meta'] ) ) { $row['undo_meta'] = wp_json_encode( $row['undo_meta'] ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom plugin table, no caching applicable. $ok = $wpdb->insert( self::table(), $row ); return $ok ? (int) $wpdb->insert_id : 0; } /** * Returns aggregated usage for a period. * * @param string $since MySQL datetime lower bound. * @return array{calls:int,input_tokens:int,output_tokens:int,cost:float} */ public static function totals( string $since = '' ): array { global $wpdb; $table = self::table(); $since = $since ?: gmdate( 'Y-m-01 00:00:00' ); $cache_key = 'ai_seo_totals_' . md5( $since ); $cached = wp_cache_get( $cache_key, 'ai-seo-tools' ); if ( false !== $cached ) { return $cached; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) AS calls, COALESCE(SUM(input_tokens),0) AS input_tokens, COALESCE(SUM(output_tokens),0) AS output_tokens, COALESCE(SUM(cost),0) AS cost FROM {$table} WHERE created_at >= %s AND provider <> ''", $since ), ARRAY_A ); $out = array( 'calls' => (int) ( $row['calls'] ?? 0 ), 'input_tokens' => (int) ( $row['input_tokens'] ?? 0 ), 'output_tokens' => (int) ( $row['output_tokens'] ?? 0 ), 'cost' => round( (float) ( $row['cost'] ?? 0 ), 4 ), ); wp_cache_set( $cache_key, $out, 'ai-seo-tools', 60 ); return $out; } /** * Formats a USD amount, keeping enough precision that small runs do not * all collapse to $0.00. */ public static function format_cost( float $amount ): string { if ( $amount <= 0 ) { return '0.00'; } if ( $amount < 0.01 ) { return number_format( $amount, 4 ); } return number_format( $amount, 2 ); } /** * Spend for the current calendar month, in USD. */ public static function month_spend(): float { $totals = self::totals( gmdate( 'Y-m-01 00:00:00' ) ); return (float) $totals['cost']; } /** * Per-module breakdown for a period. */ public static function by_module( string $since = '' ): array { global $wpdb; $table = self::table(); $since = $since ?: gmdate( 'Y-m-01 00:00:00' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT module, COUNT(*) AS calls, COALESCE(SUM(input_tokens),0) AS input_tokens, COALESCE(SUM(output_tokens),0) AS output_tokens, COALESCE(SUM(cost),0) AS cost FROM {$table} WHERE created_at >= %s AND provider <> '' GROUP BY module ORDER BY cost DESC", $since ), ARRAY_A ); return $rows ?: array(); } /** * Recent activity rows. * * @param int $limit Max rows. * @param string $module Optional module filter. */ public static function recent( int $limit = 50, string $module = '' ): array { global $wpdb; $table = self::table(); $limit = max( 1, min( 500, $limit ) ); if ( $module ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE module = %s ORDER BY id DESC LIMIT %d", $module, $limit ), ARRAY_A ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} ORDER BY id DESC LIMIT %d", $limit ), ARRAY_A ); } return $rows ?: array(); } /** * Fetches a single row. */ public static function get( int $id ): ?array { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A ); return $row ?: null; } /** * Marks a row as reverted so the UI stops offering undo. */ public static function mark_undone( int $id ): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->update( self::table(), array( 'status' => 'undone' ), array( 'id' => $id ) ); } /** * Trims the log to the configured retention window. */ public static function prune( int $days = 90 ): int { global $wpdb; $table = self::table(); $cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE created_at < %s", $cutoff ) ); } /** * Drops the table (uninstall only). */ public static function drop(): void { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query( "DROP TABLE IF EXISTS {$table}" ); } } }