=== Website Analytics by YEB ===
Contributors: yebto
Tags: analytics, statistics, pageviews, website analytics
Requires at least: 6.0
Tested up to: 6.9
Requires PHP: 8.0
Stable tag: 1.0.2
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

WordPress analytics: pageviews & sessions with interactions, verified bots, GeoIP, CSV export. Privacy-first.

== Description ==
Google Analytics alternative for WordPress: clean stats, interactions, verified bots, UTM, GeoIP, CSV export. Privacy-first.

=== What you get ===
- **At-a-glance KPIs**: pageviews, sessions, unique visitors, pages per session.
- **Interactions (sessions)**: session explorer with landing, referrer, per-session timeline (page history), avg. load, distinct pages, pageviews, expand/collapse.
- **Content insights**: top URLs, titles, post IDs.
- **Acquisition**: referrers (root domains) and UTM (source/medium/campaign).
- **Audience**: countries, regions, cities, languages, common screen sizes.
- **Tech**: device type, OS, browser.
- **Bots (with verification)**: separate verified search engine hits (Google, Bing, etc.).
- **Networks**: major networks/ISPs and their CIDR ranges.
- **CSV export**: exports exactly what your current filters show.
- **SPA-friendly & IPv6-ready**.

=== Why people choose it ===
- **Clear and calm**: focused reports, no maze of menus.
- **Actionable filters**: time window, path, title, country/city, referrer, device, OS, browser, language, UTM, bot type.
- **You stay in control**: richer info (city, device brand/model, verified bot checks) is optional — enable only what you want.

=== Setup (optional extras) ===
Want richer details like city/region, device brand/model, or verified bot checks?

1. Sign in at **https://yeb.to** and create an API key (free test credits).
2. In WordPress, open **Analytics (YEB) → Settings**, paste your key.
3. Toggle the extras you want (Geo, Network/ASN, Device details, Bot verification).

Nothing is sent to YEB until you add a key **and** turn on a feature — you choose.

=== Usage ===
- Go to **Analytics (YEB) → Dashboard** for your reports.
- Use the tabs to dive into **Overview, Interactions, Content, Acquisition, Audience, Tech, Bots, Networks**.
- Click **Export CSV** to download exactly what you’re viewing.

=== Shortcode (public mini-stats) ===
Show small, public counters anywhere (pages, posts, widgets, site editor).

**Basic:**
```

[waby_visits_stats]                         ; whole site, last 7 days
[waby_visits_stats period="30d"]            ; whole site, last 30 days
[waby_visits_stats period="1d" bots="only"] ; bots only, yesterday
[waby_visits_stats page="/pricing"]         ; just /pricing page, last 7 days

```

**Auto-detect current page:**
```

[waby_visits_stats current_page]

```
If `page=""` isn’t provided, `current_page` uses the current request path.

**Show exactly what you want:**
```

[waby_visits_stats show="visits"]  ; only total visits (pageviews)
[waby_visits_stats show="uniques"] ; only unique visitors
[waby_visits_stats show="both"]    ; both (default)

```

**Bot filter:**
- `bots="exclude"` (default) — show human traffic and unverified bot-like traffic treated as human
- `bots="only"` — bot traffic only
- `bots="include"` — include everything

**Labels, layout & CSS hooks (for custom styling):**
```

[waby_visits_stats
current_page
show="both"
label_visits="Views"
label_uniques="Visitors"
layout="inline"      ; inline | stack
sep=" • "
wrap_tag="div"       ; div | span | p
item_tag="span"      ; span | div
wrapper_class="stats stats--mini"
item_class="stats__item"
label_class="stats__label"
value_class="stats__value"
]

````

**All attributes:**
- `period`: `1d`, `7d` (default), `30d`
- `page`: limit to a path (e.g. `/pricing`)
- `current_page`: presence-only flag to use the current URL path
- `bots`: `exclude` (default), `only`, `include`
- `show`: `visits`, `uniques`, `both` (default)
- `label_visits` (default `Visits`), `label_uniques` (default `Unique`)
- `layout`: `inline` (default) or `stack`
- `sep`: separator when `layout="inline"` (default ` | `)
- `wrap_tag`: `div` (default), `span`, `p`
- `item_tag`: `span` (default), `div`
- `wrapper_class`, `item_class`, `label_class`, `value_class`: extra CSS classes

=== Styling the shortcode ===
Paste this CSS into **Appearance → Customize → Additional CSS** (or your theme stylesheet):
```css
/* YEB Visits – public stats */
.yeb-visits-stats {
  display: inline-flex;
  gap: .75rem;
  align-items: baseline;
  font: 500 14px/1.3 system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
}
.yeb-visits-stats.yeb--layout-stack {
  display: inline-grid;
  gap: .35rem;
}
.yeb-visits-stats .yeb-metric {
  display: inline-flex;
  gap: .35rem;
  align-items: baseline;
  white-space: nowrap;
}
.yeb-visits-stats .yeb-metric__label { opacity: .7; }
.yeb-visits-stats .yeb-metric__value { font-weight: 700; }
.yeb-visits-stats .yeb-sep { opacity: .35; }
````

=== Privacy, Cookies & Data Flow ===
You choose which extras to enable (location, device details, bot verification). IPs are stored in a way that groups them by network (not exact address). You can limit how often extras are called and how much data is kept.

=== External Service & Data Flow (Guideline 6) ===
This plugin can optionally call the YEB API to enrich your local analytics. Nothing is sent to YEB until you add an API key in **Analytics (YEB) → Settings** and enable the related toggle.

**Endpoints (HTTPS):**

* GeoIP: `{base}/country`, `{base}/city`, `{base}/asn` (default base: `https://api.yeb.to/v1/geoip`)
* Device analyze: `{endpoint}` (default: `https://api.yeb.to/v1/device-analyze`)
* Bot verification: `{base}` or `{base}/{vendor}` (default base: `https://api.yeb.to/v1/bot/detect/detect`)

**What is sent and when:**

* GeoIP Country — IP address; only if API key set and “Country” enabled (purpose: country lookup)
* GeoIP City/Region — IP address; only if API key set and “Region & City” enabled (purpose: city/region)
* ASN/Network — IP address; only if API key set and “ASN & Network” enabled (purpose: ASN/CIDR)
* Device analyze — User-Agent; only if API key set and “Parse user-agent strings” enabled (purpose: browser/OS/device parsing, bot type)
* Bot verification — IP + User-Agent; only if API key set and “Bot-Detect” enabled and UA looks like a bot (purpose: verify known crawlers)

All requests use HTTPS. The plugin stores analytics locally; enrichment results are cached locally.

**YEB policies:**

* Privacy Policy: [https://yeb.to/privacy](https://yeb.to/privacy)
* Terms of Service: [https://yeb.to/terms](https://yeb.to/terms)

=== Cookies ===
Two first-party cookies (pseudonymous GUIDs):

* `yeb_sid` — session id, 30 minutes; groups pageviews into sessions.
* `yeb_vid` — visitor id, 1 year; counts returning unique visitors.

=== Consent & Opt-Out (Guidelines 7 & 9) ===
By default, the beacon loads for visitors (logged-in admins excluded unless you enable **Track logged-in admins**). If your jurisdiction or policy requires consent before placing analytics cookies, gate the beacon with your consent tool.

**Example (dequeue until consent):**

```php
/**
 * Stop the YEB beacon until a custom consent flag is set.
 * Replace the condition with your CMP’s check.
 */
add_action('wp_enqueue_scripts', function () {
    $consent_given = isset($_COOKIE['my_consent_flag']) && $_COOKIE['my_consent_flag'] === 'yes';
    if ( ! $consent_given ) {
        wp_dequeue_script('waby-visits-beacon');
        wp_deregister_script('waby-visits-beacon');
    }
}, 100);
```

=== Public REST Endpoint ===
The plugin exposes an intentionally public ingest endpoint used by the front-end beacon:

```
POST /wp-json/waby/v1/visit
Alias: POST /wp-json/yeb/v1/visit
```

It accepts sanitized visit metadata (URL, path, referrer, UTM, screen, language, etc.) and stores it in your site’s database. It does not expose private data or modify content.

=== Data Retention & IP Handling ===

* A salted hash of the visitor IP is stored to group traffic by network.
* The raw IP is not stored by default. If you enable **Store raw IP (packed)**, it is retained only for the number of days you set (default **7 days**) and is visible to admins only.
* During enrichment, the raw IP may be encrypted temporarily and then cleared automatically once enrichment is done or after a short fallback window.
* You can limit daily external calls and sampling in **Analytics (YEB) → Settings**.

=== Uninstall ===

* If you enable **Delete all data on uninstall** in settings, uninstalling the plugin will remove its custom tables and options.
* Leave it off if you want to keep your analytics data.

=== Filters & Extensibility ===

* `waby_visits_stats_output` — filter the final HTML of the public stats shortcode.
* `waby_visits_cache_ttl` — filter select-query cache TTL (seconds) used by the dashboard and shortcode.

== Installation ==

1. Upload the `website-analytics-by-yeb` folder to `/wp-content/plugins/`, or install it via **Plugins → Add New**.
2. Activate **Website Analytics by YEB**.

== Frequently Asked Questions ==
= Does it track logged-in admins? =
Not unless you turn it on in settings.

= Can I use it alongside Google Analytics? =
Yes. Many sites keep GA for marketing funnels and use YEB for a clean on-site dashboard, verified bot accounting, and exports.

= Will this help explain sudden traffic spikes? =
Yes — the Bots tab separates verified search engine hits (e.g., Googlebot) from everything else, so you can quickly see what’s real.

= Does it support IPv6? =
Yes, end-to-end.

= Can I export data? =
Yes. Export CSV downloads exactly what your current filters show.

== Screenshots ==

1. Overview with KPIs and top lists
2. Interactions (sessions with expandable visit history)
3. Content & Acquisition (pages, titles, UTM, referrers)
4. Audience & Tech (countries, regions, devices, OS, browsers)
5. Bots & Networks (verified bots, ASN/CIDR)
6. Export CSV

== Changelog ==
= 1.0.2 =
* Fix: sid/vid no longer embedded in page HTML — they are fetched from a non-cached REST endpoint (/waby/v1/init) so visitors of cached pages receive unique IDs.
* Fix: SPA history changes that only modify the URL fragment (e.g. AdSense `#google_vignette` pushState) no longer record a second visit.
* Fix: When `sendBeacon` accepts the payload, the fallback `fetch` request is skipped to avoid double-counting.

= 1.0.1 =
* Fix: visitor/session IDs now managed client-side (cookies) to work with page cache plugins.
* Fix: Cost Estimator shows estimated credits when API does not return credits_spent.
* New: Refresh Costs button fetches live per-call pricing from YEB API.
* New: Quick date presets (Today, Last 7, Last 30, This Month, etc.).
* New: Period comparison with delta indicators across all tabs.
* New: Percentage columns in all data tables.
* New: Acquisition tab splits referrers into Search / Social / Other with search landing pages.
* New: Context-relevant KPI cards per tab.
* Improvement: Tabs and filter sections auto-hide when corresponding APIs are disabled.
* Improvement: Filter panel layout with grouped rows and labels.
* Improvement: Modern SaaS-style CSS redesign (indigo accent).

= 1.0.0 =
Initial release.

== Upgrade Notice ==
= 1.0.0 =
A simple, fast WordPress analytics dashboard with clear KPIs, session interactions up front, verified bot breakdowns, flexible filters, and CSV export — works great with SPAs and IPv6.
