=== RLabs Search Performance Advisor ===
Contributors: kazn0317
Tags: seo, analytics, search console, ai, reports
Requires at least: 7.0
Tested up to: 7.0
Stable tag: 0.1.3
Requires PHP: 7.4
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Pulls Google Search Console and GA4 data, then asks an AI to summarize the site's current state and answer your follow-up questions.

== Description ==

RLabs Search Performance Advisor is a WordPress admin tool that:

* Connects directly to Google Search Console and Google Analytics 4 through your own Google Cloud OAuth client.
* Generates an AI overview of the selected period (sessions, channels, top pages, top queries, goal-page progress, notable changes), based on the actual numbers, not on guesses.
* Lets you ask follow-up questions in plain language ("How did /pricing do yesterday?", "Which queries dropped this week?"). The AI calls Search Console / GA4 with the period you are currently viewing.
* Produces a printable HTML report (use your browser's "Print → Save as PDF") that bundles site info, AI overview, key tables, and a factual summary of your Q&A.
* Supports a plain-language tone (no jargon — "click-through rate" instead of "CTR", "visits" instead of "sessions") or an expert tone for users comfortable with SEO / analytics vocabulary.
* Caches results per period for 24 hours; refetch on demand.
* Available in Japanese (source language) and English (en_US). UI strings follow WordPress's locale; AI replies follow the same locale.

= External services this plugin uses =

This plugin sends data to the following external services on your behalf. Please review before installing.

1. Google APIs (oauth2.googleapis.com, searchconsole.googleapis.com, analyticsdata.googleapis.com, analyticsadmin.googleapis.com)
    * What is sent: OAuth tokens, the Search Console site URL or GA4 property ID you connect, and query parameters (date ranges, dimensions, metrics).
    * When: When you click "Connect to Google", "Refetch data", "Generate overview", "Ask AI", or open a report.
    * Terms / privacy: <https://policies.google.com/terms> / <https://policies.google.com/privacy>.

2. AI provider configured via the WordPress AI plugin. Depending on which provider you connected under Settings → Connectors, this plugin's "Generate overview" / "Ask AI" actions will cause the WordPress AI Client to call one of the following endpoints on your behalf:
    * Anthropic Claude API — host `api.anthropic.com`. Terms: <https://www.anthropic.com/legal/consumer-terms>. Privacy: <https://www.anthropic.com/legal/privacy>.
    * OpenAI API — host `api.openai.com`. Terms: <https://openai.com/policies/row-terms-of-use/>. Privacy: <https://openai.com/policies/row-privacy-policy/>.
    * Google Generative Language API — host `generativelanguage.googleapis.com`. Terms: <https://policies.google.com/terms>. Privacy: <https://policies.google.com/privacy>.
    * What is sent: a system instruction (your site URL, the purpose / goal pages / monthly goal you configured in Site Settings, your selected period, audience tone setting), your question or the overview prompt, prior conversation turns in the same session, and tool-call results pulled from Search Console / GA4.
    * When: every time "Generate overview" or "Ask AI" is invoked.

You must enable the relevant Google APIs (Search Console API, Google Analytics Data API, Google Analytics Admin API) and set up your own OAuth 2.0 client in your own Google Cloud project. API usage, quotas, and billing remain under your control.

== Installation ==

= Step A. Install and activate the plugin =

1. Download the plugin .zip and go to "Plugins → Add New → Upload Plugin" in your WordPress admin, or copy the plugin folder into /wp-content/plugins/.
2. Activate "RLabs Search Performance Advisor" from the Plugins screen.

= Step B. Make sure an AI provider is available =

This plugin relies on the WordPress AI Client (the function wp_ai_client_prompt() and its tool-use API) and at least one configured AI connector.

1. Install and activate the official "AI" plugin (slug: ai, https://wordpress.org/plugins/ai/) if the AI Client is not already bundled in your WordPress build.
2. Open "Settings → Connectors" and add at least one provider (Anthropic, OpenAI, or Google), supplying that provider's own API key.
3. Confirm the connector shows as healthy. Without a working connector, "Generate overview" and "Ask AI" will not run.

= Step C. Create your own Google Cloud project and OAuth client =

The plugin talks to Google APIs using credentials in your own Google Cloud project. Nothing is proxied through a third party.

1. Go to https://console.cloud.google.com/ and create a new project (or select an existing one).
2. In "APIs & Services → Library", enable the following APIs for that project:
   * Search Console API
   * Google Analytics Data API
   * Google Analytics Admin API (optional — needed only if you want the GA4 property dropdown inside the plugin)
3. Configure the OAuth consent screen at "APIs & Services → OAuth consent screen":
   * User type: External (or Internal, if your domain is on Google Workspace).
   * Add at least one test user — the Google account that has access to your Search Console property and your GA4 property.
   * Verification is not required while the app stays in "Testing" mode and only listed test users connect.
4. Create an OAuth 2.0 Client ID at "APIs & Services → Credentials → Create credentials → OAuth client ID":
   * Application type: Web application.
   * Authorized JavaScript origins: leave blank.
   * Authorized redirect URIs: paste the exact URI shown in "RLabs Search Performance Advisor → Connection Settings → Step 2" inside your WordPress admin. A single-character mismatch causes a redirect_uri_mismatch error.

= Step D. Connect WordPress to Google =

1. In WordPress admin, open "RLabs Search Performance Advisor → Connection Settings".
2. In Step 3 of that screen, paste the Client ID and Client Secret from Google Cloud Console, then save.
3. In Step 4, click "Connect to Google", sign in with the Google account that has access to your Search Console property and GA4 property, and approve the read-only scopes (analytics.readonly, webmasters.readonly).
4. You should be redirected back to the plugin with "Connected" shown. If you see "redirect_uri_mismatch", recheck Step C-4.

= Step E. Pick the GA4 property and the Search Console site =

1. In "RLabs Search Performance Advisor → Connection Settings", scroll to "Data source selection (GA4 / Search Console)".
2. Choose the GA4 property (numeric ID) for this site. If the dropdown is empty, enable the Google Analytics Admin API (see Step C-2) and reload after a few minutes, or enter the property ID manually (you can find it under GA4 Admin → Property Settings).
3. Choose the Search Console property (URL-prefix property or Domain property) for this site. The auto-detect option matches the WordPress site host against your available Search Console properties.
4. Save. Saving discards any cached analysis results so the next page load refetches under the new property / site.

= Step F. Configure site goals =

1. Open "RLabs Search Performance Advisor → Site Settings".
2. Primary purpose of this site: describe what the site is for in your own words (e.g. "Get renovation quote requests; the top priority is increasing inquiries from organic search."). This is injected into the AI system instruction.
3. Goal pages: one path per line. Pages that count as a conversion when reached (e.g. /contact/thanks, /quote/done). A leading slash is added automatically if missing.
4. Monthly goal: how many goal-page hits you want per month. 0 means the goal is unset.
5. Explanation level: pick "Explain in plain language" for jargon-free output, or "Jargon OK, concise" for SEO-savvy users. This affects both Overview and Ask AI replies.
6. Save.

= Step G. Run an analysis =

1. Open "RLabs Search Performance Advisor → Site Analysis".
2. Pick a date range from the picker (Past 7 / 28 / 30 / 90 days, This / Last month, This / Last week, This quarter, This / Last year, or Custom). The dashboard widget is fixed to the past 28 days.
3. Search Console and GA4 summary tables are fetched automatically and cached for 10 minutes. Click "Refetch data" to force a refresh.
4. Click "Generate overview" to have the AI produce a six-section summary for the selected period (traffic, channels, top pages, top queries, goal-page status, notable changes). Results are cached per period for 24 hours.
5. Use "Ask AI" to ask follow-up questions in natural language. The AI remembers the conversation within the session, so follow-ups like "What about yesterday?" or "Show me the #3 page in more detail" work as-is. Click "Reset conversation" to clear it.
6. Click "Open report (print to save as PDF)" to open a printable, single-page report. Use your browser's Print → Save as PDF.

== Frequently Asked Questions ==

= Why do I need to create my own Google Cloud OAuth client? =

So that API usage, quotas, billing, and permissions remain under the site owner's control. The plugin never proxies your data through a third party — your WordPress site talks to Google APIs directly using your own credentials.

= What data leaves my site? =

Two things:

1. Google API calls (date ranges, dimensions, metrics, the configured property / site URL) signed with your OAuth tokens.
2. AI provider calls — your question text, prior turns in the same Ask-AI session, the system instruction (your site URL, your Site Settings values, your selected period and tone), and the Search Console / GA4 numbers fetched to answer the question.

See "External services this plugin uses" in the Description for details.

= Which AI model is used? =

Whichever model you configured in Settings → Connectors via the WordPress AI plugin. This plugin does not bundle or call any AI provider directly.

= Is the plugin free? =

Yes. You may incur costs at your own Google Cloud project (the Search Console / GA4 APIs have a generous free quota for typical sites) and at your AI provider depending on its pricing.

= What languages are supported? =

The plugin source language is Japanese. An English (en_US) translation is bundled. The AI replies in the same language as your active WordPress locale.

= My report shows "no data" for a section. What does that mean? =

The plugin refuses to guess. If Google APIs returned no rows for that section in the selected period, the AI marks it as "no data" rather than inventing numbers.

= Why do I need to re-authorize after some time? =

Google access tokens are short-lived. The plugin stores a refresh token and renews access tokens automatically. If the refresh token is revoked (e.g. you change Google Cloud project, withdraw scope grants, or hit Google's inactivity policy), the plugin will ask you to reconnect.

== Changelog ==

= 0.1.3 =
* Fix: Replaced legacy `ai_improvement_advisor_*` filter hook names (left over from the original plugin name) with the current `rlspa_*` prefix to align all internal identifiers with the plugin's unique prefix and avoid the reserved/common-word prefix `ai`.

= 0.1.2 =
* Improve: Search Console table titles now show "(Search Console)" as a smaller subtitle so users can tell at a glance which data source each table reflects.
* Improve: "上位クエリ" renamed to "上位クエリ（キーワード）" for clarity.
* Add: GA4 "Users by city" table (city dimension) showing user count, sessions, page views, and engagement rate.
* Fix: GA4 top-pages table now includes the user count column (was missing because totalUsers metric was not requested).
* Fix: GA4 channel breakdown table now includes the page views column (was missing because screenPageViews metric was not requested).

= 0.1.1 =
* Fix: Page URLs containing multibyte characters (Japanese, Chinese, Korean, etc.) were corrupted in the Search Console top-pages list because percent-encoded octets were stripped during row normalization. Page URLs are now preserved with `esc_url_raw()`, so the displayed URLs and the data passed to the AI match the actual pages.
* Improve: Top-pages tables now display URLs decoded (e.g. Japanese paths shown as Japanese characters instead of "%E3%81%8C..."), as clickable links, and wrap properly within the cell.

= 0.1.0 =
* Initial release.
* Direct Google OAuth integration with Search Console API and GA4 Data API (no Site Kit dependency).
* AI overview generation (period-aware, no recommendations — facts only).
* Ask AI question form with multi-turn conversation memory.
* Date range picker (Past 7 / 28 / 30 / 90 days, This / Last month, This / Last week, This quarter, This / Last year, custom).
* Printable HTML report (browser-native print → PDF).
* GA4 property and Search Console site selectors.
* Site Settings: purpose, goal pages, monthly goal, explanation level (plain-language / expert).
* Japanese (source) and English (en_US) UI and AI replies.

== Upgrade Notice ==

= 0.1.3 =
Internal-only: standardizes all filter hook names under the `rlspa_` prefix. No behavioral changes.

= 0.1.2 =
Adds GA4 user-by-city table; fixes missing user-count column on GA4 top pages and missing page-views column on GA4 channel breakdown; clearer table titles distinguishing Search Console vs GA4.

= 0.1.1 =
Fixes corrupted page URLs in the Search Console top-pages list when URLs contain non-ASCII characters (Japanese, Chinese, Korean, etc.). Upgrade recommended for accurate AI input and reports.

= 0.1.0 =
Initial release.
