# Wishlist Analytics — Developer Guide

This guide explains the code architecture, class responsibilities, and how to extend the analytics feature.

---

## Architecture Overview

The analytics feature follows the same patterns used in the rest of the Bizzwishlist plugin:

- **PSR-4 autoloading** via `Bizzwishlist\Admin\Analytics` namespace
- **Repository pattern** for database queries (`AnalyticsRepository`)
- **MVC-like separation** — data logic in repository, page rendering in views, AJAX in separate handler
- **WordPress hooks** for menu registration, asset loading, and AJAX endpoints

---

## Class Reference

### `Bizzwishlist\Admin\Analytics\AnalyticsRepository`

**File:** `includes/Admin/Analytics/AnalyticsRepository.php`

The data layer for all analytics queries. All methods return sanitized, typed results.

| Method | Return Type | Description |
|--------|-------------|-------------|
| `get_total_items()` | `int` | Total wishlist rows |
| `get_total_users()` | `int` | Distinct users/sessions |
| `get_total_unique_products()` | `int` | Distinct product IDs |
| `get_most_wishlisted($limit)` | `array` | Top products by wishlist count |
| `get_daily_trend($days)` | `array` | Daily item counts for last N days |
| `get_monthly_trend($months)` | `array` | Monthly item counts for last N months |
| `get_conversion_rate()` | `array` | Rate with totals (`rate`, `total_wishlist_items`, `total_added_to_cart`) |
| `get_user_wishlist_data($limit)` | `array` | Top registered users by item count |
| `get_recent_activity($limit)` | `array` | Most recent wishlist additions with user info |
| `log_event($event_type, $product_id, $user_id, $variation_id)` | `int\|false` | Insert an analytics event |
| `get_conversion_trend($days)` | `array` | Daily conversion counts for last N days |
| `get_user_type_split()` | `array` | Registered vs guest counts |

### `Bizzwishlist\Admin\Analytics\AnalyticsPage`

**File:** `includes/Admin/Analytics/AnalyticsPage.php`

Handles admin submenu registration, asset enqueuing, and page rendering.

| Method | Description |
|--------|-------------|
| `register()` | Registers `admin_menu` and `admin_enqueue_scripts` hooks |
| `add_submenu()` | Adds "Analytics" submenu under "Bizz Wishlist" |
| `enqueue_assets($hook)` | Loads CSS, Chart.js, and analytics JS only on the analytics page |
| `render_page()` | Fetches all data from repository and includes the dashboard view |

**Admin Page Hook:** `bizz-wishlist_page_bizzwishlist-analytics`

### `Bizzwishlist\Admin\Analytics\AnalyticsAjax`

**File:** `includes/Admin/Analytics/AnalyticsAjax.php`

AJAX handler for dynamic chart updates.

| Method | AJAX Action | Description |
|--------|-------------|-------------|
| `get_trend_data()` | `bizzwishlist_analytics_trend` | Returns trend data for the requested period (daily/monthly) |

**Nonce:** `bizzwishlist_analytics_nonce`
**Capability:** `manage_options`

---

## Database Table: `{prefix}_bizzwishlist_events`

Created in `Installer::create_events_table()` during plugin activation.

```sql
CREATE TABLE {prefix}_bizzwishlist_events (
    id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    event_type varchar(50) NOT NULL,
    product_id bigint(20) UNSIGNED NOT NULL,
    variation_id bigint(20) UNSIGNED DEFAULT 0,
    user_id bigint(20) UNSIGNED DEFAULT NULL,
    created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY event_type (event_type),
    KEY product_id (product_id),
    KEY created_at (created_at)
);
```

### Event Types

| Event Type | Triggered When |
|------------|---------------|
| `add_to_cart` | User adds a wishlist item to the WooCommerce cart |

---

## Conversion Tracking Integration

Conversion events are logged in `WishlistAjax` at three points:

1. **`add_all_to_cart()`** — When user clicks "Add All to Cart"
2. **`add_to_cart_single()`** — When user adds a single item from wishlist/popup
3. **`add_selected_to_cart()`** — When user adds selected items to cart

Each successful cart addition triggers:
```php
$this->analytics->log_event( 'add_to_cart', $product_id, $owner['user_id'], $variation_id );
```

---

## Frontend JavaScript

**File:** `assets/js/admin-analytics.js`

| Function | Description |
|----------|-------------|
| `parseData(id)` | Parses JSON from `<script type="application/json">` tags embedded in the dashboard |
| `initTrendChart()` | Creates the line chart with wishlist trend + conversion overlay |
| `initUserTypeChart()` | Creates the doughnut chart for user type distribution |
| `updateTrendChart(period)` | AJAX call to fetch and update trend data for daily/monthly toggle |
| `bindEvents()` | Binds click handlers for period toggle buttons |

**Localized Data Object:** `bizzwishlistAnalytics`

| Property | Description |
|----------|-------------|
| `ajaxUrl` | WordPress AJAX URL |
| `nonce` | Security nonce |
| `i18n` | Translatable strings for chart labels |

---

## How to Extend

### Adding a New Metric

1. Add a new method to `AnalyticsRepository`:
```php
public function get_my_metric() {
    global $wpdb;
    // Your query here
    return $wpdb->get_var( ... );
}
```

2. Call it in `AnalyticsPage::render_page()`:
```php
$my_metric = $this->repository->get_my_metric();
```

3. Display it in `views/dashboard.php`.

### Adding a New Event Type

1. Call `log_event()` with your custom event type:
```php
$this->analytics->log_event( 'my_custom_event', $product_id, $user_id );
```

2. Query it in the repository:
```php
$wpdb->get_var( "SELECT COUNT(*) FROM {$this->events_table} WHERE event_type = 'my_custom_event'" );
```

### Adding a New Chart

1. Add a `<canvas>` element in `views/dashboard.php`
2. Add a `<script type="application/json">` tag with the data
3. Create an initialization function in `admin-analytics.js`
4. Call it in the `$(document).ready()` block

---

## Code Style

- PHP follows WordPress Coding Standards
- JavaScript follows WordPress JavaScript Coding Standards
- CSS follows the same naming conventions as existing admin styles (`bizzwishlist-` prefix)
- All database queries use `$wpdb->prepare()` for security
- All output is properly escaped

---

## Testing

Since this is a WordPress plugin without a test infrastructure in the repo, manual testing steps:

1. **Activate the plugin** on a WooCommerce-enabled WordPress site
2. **Deactivate and reactivate** to ensure the `bizzwishlist_events` table is created
3. **Add products to wishlist** to generate data
4. **Add wishlist items to cart** to generate conversion events
5. **Navigate to Bizz Wishlist → Analytics** to verify the dashboard
6. **Toggle Daily/Monthly** to verify AJAX chart updates
7. **Check browser console** for any JavaScript errors
