=== RVS Database Doctor ===
Contributors: rberet
Tags: database, optimization, cleanup, backup, performance
Requires at least: 6.2
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 2.5.7
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Safely analyze and optimize your WordPress and WooCommerce database with backups, restore, schedules, and a built-in health advisor.

== Description ==

**RVS Database Doctor** is a professional database administration tool. It gives you insight into the current state, safely cleans and optimizes, and shows exactly how much you saved - with full support for large databases.

= Key features =

* **Dashboard** with health score and one-click **Optimize Now**.
* **Time-based job runner** (default batch 1000, auto-adapts to `max_execution_time`) - works smoothly on databases with 100k+ rows.
* **Background queue** (WP-Cron drain every minute, Action Scheduler when available) - you can close the tab and the job continues.
* **Before / After snapshots** with SVG charts and per-table delta (no external dependencies).
* **Guided Safe Cleanup Wizard** with recommended selections, CARE confirmations, before/after snapshots, and cleanup result deltas.
* **Smart Advisor v2** - health score (0-100, grade A-F), actionable tips, and EXPLAIN query-plan hints for slow queries.
* **Bulk actions** for Table Sizes, Autoload Options, Index Analysis, and Cleanup tabs.
* **Manual full database backup** with a user-selectable table list and **manifest.json** metadata. Choose PHP chunked dump (works anywhere) or native **mysqldump** (fast).
* **Full database restore** from plugin-created backups - automatic pre-restore backup, streaming SQL import, progress tracking, and mandatory confirmation (type RESTORE).
* **Micro-backup of affected tables** before destructive operations (gzip when available, retention by days and count).
* **Scheduled optimizations** - hourly / daily / weekly / monthly.
* **Scheduled health digest emails** - daily, weekly, or monthly summaries sent to the configured notification email.
* **MyISAM → InnoDB** conversion (batched with progress bar).
* **Autoload analysis** with severity levels, segmentation, search, filter, pagination, and bulk update - no longer limited to 50 options.
* **Index analysis** - missing expected, composite suggestions, sys redundant / unused.
* **WooCommerce / HPOS** detection and specific suggestions.
* **Cleanup**: expired transients, revisions, auto-drafts, old trash, spam / trash comments, orphan postmeta / commentmeta / term_relationships, expired WC sessions, Action Scheduler old actions / logs, duplicate postmeta, stale session tokens, `_edit_lock` / `_edit_last`.
* **Actions log** - every attempt is recorded (success / error / dry-run).
* **WP-CLI** commands for every action including `backup create --all`, `backup validate <uid>`, and `backup restore <uid> --confirm=RESTORE` (`wp rvs-database-doctor …`; `wp rvs-db-doctor …` is also supported).

= Safety rules =

* All destructive actions require the `manage_options` capability + nonce + explicit confirmation checkbox.
* Table names are validated against `information_schema` before any `ALTER / ANALYZE / OPTIMIZE / DELETE`.
* Auto-backup of affected tables before destructive operations (enabled by default).
* The plugin never deletes anything automatically; **Optimize Now** runs safe categories only by default.

== Installation ==

1. Upload the `rvs-database-doctor` folder to `wp-content/plugins/`.
2. Activate the plugin from the Plugins screen.
3. Open **Tools → RVS Database Doctor** and start on the Dashboard.
4. (Optional) Visit the **Settings** tab to configure batch size, time budget, and retention.

== Frequently Asked Questions ==

= Does the plugin delete anything automatically? =

No. Every action requires an explicit click and confirmation. Schedules (if you create any) only run the job type you selected.

= Does it require WooCommerce? =

No. WooCommerce is optional. The plugin auto-detects it and surfaces WC-specific options (HPOS, sessions, Action Scheduler) when available.

= What if I have 100k+ rows to clean up? =

The plugin uses a time-based runner: each AJAX request processes batches until the time budget (~25s by default) is exhausted, then the browser (or WP-Cron in background mode) triggers the next tick. You can raise the batch size in Settings (up to 50000) or run the job in the background and close the tab.

= Is this a replacement for UpdraftPlus / BackupBuddy? =

Partly. RVS Database Doctor performs **database-only** backups: a micro-backup before destructive actions and a manual full database backup (you pick the tables). For complete site backups including files / media, keep using a dedicated backup plugin.

= Can I use mysqldump? =

Yes, if your host allows `shell_exec()` and provides the `mysqldump` binary. The Backups tab detects availability and lets you pick the method per backup.

= Multisite? =

The plugin works at the site level (not network-aware in 2.0). Activate per-site.

== Changelog ==

= 2.5.7 =
* Removed WordPress.org directory assets from the plugin package.
* Hardened database queries by preparing table identifiers and values with `$wpdb->prepare()` placeholders.
* Replaced dynamic collation repair SQL with a prepared table conversion query.
* Fixed plugin-cache cleanup placeholder generation to avoid PHPCS replacement-count warnings.

= 2.5.6 =
* Fixed duplicate changelog entries for version 2.4.5.

= 2.5.5 =
* Fixed stale cache issue where MyISAM tables continued to be displayed in the Table Engines tab after a successful conversion.

= 2.5.4 =
* Fixed selector mismatch in MyISAM to InnoDB conversion where checked tables were not detected.
* Resolved Action Scheduler database bloat by cleaning legacy hooks and optimizing queries.
* Fixed false positive unused taxonomies candidates list.

= 2.4.5 =
* **Horizontal tabs navigation** replaces the grouped sidebar so the main content area uses full width. Tabs are grouped with labels (Overview, Optimize, Safety, Operations, Configuration) and use design tokens for consistent styling.
* Active tab has a top border that visually merges with the content area; hover/focus states use primary color with keyboard-visible focus ring.
* Mobile select fallback remains unchanged for narrow viewports (≤960px). All `?tab=` URLs continue to work unchanged.

= 2.4.4 =
* **GitHub Actions CI**: a new `.github/workflows/ci.yml` lints every PHP file under PHP 7.4 / 8.0 / 8.1 / 8.2 / 8.3 and runs the PHPUnit suite on every push and pull request. Tagged pushes (`v*`) also stage a release zip artifact.
* **Expanded PHPUnit suite**: three new test files covering ETA formatting (5 cases), the grouped sidebar navigation contract (legacy `?tab=` URLs and `render_tab_*` method coverage), and additional `RVSDADO_Actions::validate_job_params()` branches (uid sanitizer, mode default, unknown type, runner-vs-admin context, table list filtering).
* `RVSDADO_Admin_Helpers_Trait::format_eta()` promoted to public so external callers (CLI, REST, tests) can reuse the same formatter used in the active jobs table.

= 2.4.3 =
* **Orphan table analyzer is dramatically faster on busy sites**: the plugin owner registry is now cached in-memory for the duration of the request, and the per-plugin code scan (up to 80 PHP files per plugin) is cached as a transient keyed by the plugin's directory `mtime` so it self-invalidates on plugin updates. First detection pass is unchanged; subsequent passes within 12 hours are near-instant.

= 2.4.2 =
* **Grouped sidebar navigation** replaces the flat horizontal tab strip: 5 logical groups (Overview, Optimize, Safety, Operations, Configuration). All `?tab=` URLs from previous versions continue to work unchanged.
* Sticky sidebar that scrolls independently, plus a breadcrumb trail at the top of every section.
* Narrow viewports (≤960px) get a responsive `<select>` group fallback instead of the sidebar.
* `aria-current="page"`, `aria-label`, and focus-visible outlines for full keyboard / screen-reader navigation.

= 2.4.1 =
* Added a design-token CSS system (colors, spacing, radius, shadows, typography) as the single source of truth for all admin styling.
* Added a **Dark mode** for the plugin admin pages with Auto (follow OS), Light, and Dark options under Settings → Color theme. The theme attribute is applied before paint to avoid flash of unstyled content.
* Refined component theming for cards, panels, intro boxes, wizard, help boxes, and the v2 accessible modal under dark mode.
* **Sticky table headers** on all plugin `.widefat` tables -column titles stay visible while scrolling large datasets.
* **Sortable columns** with click or keyboard (Enter/Space) toggling asc/desc; numeric / date / text is auto-detected; tables driven by background polling opt out automatically.

= 2.4.0 =
* Accessible toast notifications replace blocking `alert()` calls (aria-live, dismissible, auto-timeout).
* Accessible confirm/prompt modal v2 with focus trap, Escape-to-close, and tip-to-confirm validation (RESTORE / DROP / QUARANTINE / DELETE).
* Adaptive job polling: respects Page Visibility, throttles when idle, kicks back to fast cadence when work appears.
* New running-jobs indicator in the WordPress admin bar (visible on every wp-admin page, capability-gated).
* Pause / Resume jobs from the active jobs table (new `pause()` / `resume()` runner methods and AJAX endpoints).
* ETA shown next to each active job's processed/total count, derived from runner throughput.

= 2.3.2 =
* Renamed internal prefixes to `rvsdado_` / `RVSDADO_` across classes, constants, options, transients, hooks, AJAX actions, and asset handles for stronger isolation.
* Stored data and transient keys now use the unique `rvsdado_` prefix in explicit string literals.
* Migrated destructive DDL paths (DROP TABLE / RENAME TABLE) and other identifier-bound SQL to `$wpdb->prepare()` with the `%i` placeholder.
* Added a stricter whitelist that requires tables to be currently detected as orphans (or sourced from the quarantine registry) before any destructive DDL runs.
* Replaced the dynamic `IN ({$ids_csv})` SQL clause with prepared `%d` placeholders.
* Removed the residual `ini_set('display_errors', '0')` call from the AJAX core.
* Raised the minimum WordPress requirement to 6.2 to support the `%i` identifier placeholder.

= 2.3.1 =
* Addressed WordPress.org pre-review feedback for transient key naming, CLI report output storage, and AJAX output buffering.
* Restricted WP-CLI report file output to the plugin's uploads directory.

= 2.3.0 =
* Added the Guided Safe Cleanup Wizard with recommended selections, CARE confirmations, before/after snapshots, live runner progress, and cleanup result deltas.
* Added scheduled health digest emails with daily, weekly, or monthly frequency.
* Added lightweight QA scaffolding, a manual QA checklist, and a release build helper that excludes QA/dev-only artifacts.
* Fixed Action Scheduler drain registration timing and avoided early translation loading for the custom cron schedule label.

= 2.2.0 =
* Updated plugin metadata and release references for version 2.2.0.
* Addressed Plugin Check findings for translator comments and prepared SQL scanner warnings in database cleanup, runner, scheduler, and backup checks.

= 2.1.0 =
* Autoload tab: full pagination, search, filter (autoloaded/not/large/review/watch), sort, and segmentation - no longer limited to 50 options.
* Backup manifests: every new backup writes a `manifest.json` with method, DB name, WP prefix, tables, files, gzip flag, and version.
* Full database restore: restore plugin-created backups from UI or CLI (`wp rvs-database-doctor backup restore <uid> --confirm=RESTORE`). Automatic pre-restore backup, streaming SQL import, blocked dangerous statements, DB/prefix compatibility checks.
* Backup list now shows method, table count, and restore eligibility.
* WP-CLI: added `backup validate <uid>` and `backup restore <uid> --confirm=RESTORE`; `autoload` now supports `--per-page`, `--page`, `--filter`, `--search`, `--orderby`, `--order`.

= 2.0.0 =
* Time-based job runner with dynamic batch size (default 1000).
* Background queue (WP-Cron drain / Action Scheduler support).
* Before / After snapshots + SVG charts.
* Smart Advisor v2 with EXPLAIN hints.
* Bulk actions for Table Sizes, Autoload, Indexes and Cleanup.
* Manual full database backup (PHP dump or mysqldump), user-selectable tables.
* Micro-backup of affected tables with retention.
* Scheduled optimizations.
* One-click Optimize Now.
* Refactored UI: Dashboard as the default tab, Analytics, Schedules, Backups.
* Refactored WP-CLI with job / snapshot / backup subcommands.
* Fully translated to English (text domain `rvs-database-doctor`).

= 1.0.0 =
* Initial release.

== Upgrade Notice ==

= 2.4.5 =
Navigation redesign: grouped sidebar replaced with horizontal tabs so content uses full width. No data migration required; all bookmarks and `?tab=` URLs continue to work.

= 2.4.4 =
Quality release: GitHub Actions CI (lint + PHPUnit on PHP 7.4-8.3) and an expanded test suite. No runtime behavior changes beyond promoting `format_eta()` to public.

= 2.4.3 =
Performance: orphan-table analyzer caches the owner registry per-request and the per-plugin code scan as transients (12h, auto-invalidated by plugin updates). Drop-in upgrade, no migration required.

= 2.4.2 =
Navigation refactor: flat horizontal tabs become a grouped sticky sidebar (Overview / Optimize / Safety / Operations / Configuration). All bookmarks and `?tab=` URLs continue to work. No data migration required.

= 2.4.1 =
Introduces a design-token CSS system, an opt-in Dark mode for the plugin admin pages (Settings → Color theme), sticky table headers, and client-side sortable columns. No data migration required.

= 2.4.0 =
UX-focused release: accessible toasts and confirm/prompt modals, adaptive job polling, admin-bar running-jobs indicator, pause/resume jobs, and ETA in the active jobs table. No data migration required.

= 2.3.2 =
WordPress.org review compatibility release. Plugin prefixes were renamed to `rvsdado_` and destructive SQL now uses `$wpdb->prepare()` with `%i` placeholders. Requires WordPress 6.2 or later.

= 2.3.1 =
WordPress.org review compatibility release. CLI report output is now stored under uploads/rvs-database-doctor/.

= 2.3.0 =
Guided cleanup wizard, scheduled health digest emails, QA scaffolding, release packaging helper, and scheduler timing improvements.

= 2.2.0 =
Maintenance release with Plugin Check compatibility fixes and version metadata updates.

= 2.1.0 =
Autoload pagination, backup manifests, full database restore, backup validation, CLI restore. Backups created before 2.1.0 lack manifests and cannot be restored - create a new backup after upgrading.

= 2.0.0 =
Major upgrade: new job runner and background queue, dynamic batch size replaces fixed batch 50, added snapshots, advisor v2, scheduler, full database backup, and bulk actions. Compatible with existing data.
