post_type, ['page', 'post'], true)) { return false; } $snapshots = get_post_meta($post_id, '_aiwest_undo_snapshots', true); if (!is_array($snapshots)) $snapshots = []; $snapshots[] = [ 'time' => current_time('mysql'), 'source' => sanitize_key($source), 'note' => sanitize_text_field($note), 'post_title' => $post->post_title, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_status' => $post->post_status, ]; if (count($snapshots) > 10) { $snapshots = array_slice($snapshots, -10); } update_post_meta($post_id, '_aiwest_undo_snapshots', $snapshots); update_post_meta($post_id, '_aiwest_last_snapshot_at', current_time('mysql')); return true; } public static function can_undo($post_id) { $snapshots = get_post_meta(intval($post_id), '_aiwest_undo_snapshots', true); return is_array($snapshots) && !empty($snapshots); } public static function restore_last($post_id) { $post_id = intval($post_id); $post = get_post($post_id); if (!$post || !in_array($post->post_type, ['page', 'post'], true)) { return new WP_Error('aiwest_undo_no_post', __('The page or post to restore was not found.', 'ai-webmaster-studio')); } $snapshots = get_post_meta($post_id, '_aiwest_undo_snapshots', true); if (!is_array($snapshots) || empty($snapshots)) { return new WP_Error('aiwest_undo_no_snapshot', __('No saved snapshot is available to restore.', 'ai-webmaster-studio')); } $snapshot = array_pop($snapshots); $result = wp_update_post([ 'ID' => $post_id, 'post_title' => sanitize_text_field($snapshot['post_title'] ?? $post->post_title), 'post_content' => $snapshot['post_content'] ?? $post->post_content, 'post_excerpt' => sanitize_textarea_field($snapshot['post_excerpt'] ?? $post->post_excerpt), 'post_status' => sanitize_key($snapshot['post_status'] ?? $post->post_status), ], true); if (is_wp_error($result)) return $result; update_post_meta($post_id, '_aiwest_undo_snapshots', $snapshots); update_post_meta($post_id, '_aiwest_last_undo_at', current_time('mysql')); if (class_exists('AIWEST_Logger')) { AIWEST_Logger::info('AI Webmaster Studio undo restored last snapshot.', [ 'post_id' => $post_id, 'snapshot_time' => $snapshot['time'] ?? '', 'source' => $snapshot['source'] ?? '', ]); } return [ 'post_id' => $post_id, 'snapshot_time' => $snapshot['time'] ?? '', 'source' => $snapshot['source'] ?? '', ]; } }