# SEO Analytics Dashboard - Setup Guide

## Overview
This modular SEO analytics system integrates seamlessly with your existing PHP website without disrupting current functionality.

## Architecture

```
/helpers/seo_analytics/
  ├── config.php                 (API keys and settings)
  ├── BaseAnalytics.php          (Core base class)
  ├── GoogleSearchConsoleAPI.php  (GSC integration)
  ├── GoogleAnalytics4API.php     (GA4 integration)
  ├── BacklinkAnalyzerAPI.php     (SEMrush/Ahrefs)
  └── SiteAuditAPI.php            (Site audit module)

/admin/seo_analytics/
  ├── dashboard.php               (Main dashboard)
  └── sections/
      ├── overview.php            (Overview section)
      ├── search_performance.php
      ├── realtime_activity.php
      ├── backlinks.php
      ├── site_audit.php
      ├── keywords.php
      └── settings.php

/api/seo_analytics/
  ├── search_performance.php
  ├── realtime_users.php
  ├── top_pages.php
  ├── traffic_trends.php
  ├── backlinks.php
  └── site_audit.php

/assets/seo_analytics/
  ├── dashboard.css
  └── dashboard.js
```

## Setup Instructions

### 1. Configure API Keys

Edit `/helpers/seo_analytics/config.php` and add your API keys:

```php
// Using environment variables (RECOMMENDED)
GSC_ENABLED=true
GSC_CLIENT_ID=your_client_id
GSC_CLIENT_SECRET=your_client_secret
GSC_REFRESH_TOKEN=your_refresh_token
GSC_PROPERTY_URL=https://www.yoursite.com

GA4_ENABLED=true
GA4_CLIENT_ID=your_client_id
GA4_CLIENT_SECRET=your_client_secret
GA4_REFRESH_TOKEN=your_refresh_token
GA4_PROPERTY_ID=your_property_id

SEMRUSH_API_KEY=your_semrush_key
AHREFS_API_KEY=your_ahrefs_key
BING_API_KEY=your_bing_key
```

### 2. Get Google OAuth Tokens

1. Go to [Google Cloud Console](https://console.cloud.google.com)
2. Create a new project
3. Enable "Google Search Console API" and "Google Analytics Data API"
4. Create OAuth 2.0 credentials (Desktop application)
5. Generate refresh token using the provided client ID/secret

### 3. Access the Dashboard

Navigate to: `/admin/seo_analytics/dashboard.php`

Requires admin authentication (checks `$_SESSION['admin_id']` and `admin_role`)

## Features

### 1. Search Performance Module
- Track clicks, impressions, CTR, position from Google Search Console
- Filter by query, page, device, country
- 30+ day historical data
- Real-time data updates

**API Endpoint:** `/api/seo_analytics/search_performance.php?days=30&dimensions=query`

### 2. Realtime User Activity
- Active users by device (desktop/mobile/tablet)
- Per-minute traffic trends
- Session and pageview metrics
- 5-second auto-refresh

**API Endpoint:** `/api/seo_analytics/realtime_users.php`

### 3. Backlink Analysis
- Total backlinks and referring domains
- Domain authority metrics
- Dofollow/nofollow ratio
- Top referring domains

**Requires:** SEMrush or Ahrefs API key

### 4. Site Audit & Health
- HTTPS validation
- robots.txt and sitemap.xml checks
- Meta tags validation
- Mobile friendliness check
- Core Web Vitals from PageSpeed Insights
- Crawl error detection

**API Endpoint:** `/api/seo_analytics/site_audit.php`

### 5. Keyword & Organic Traffic
- Top landing pages by traffic
- Search queries performance
- Organic vs paid traffic comparison
- Keyword ranking trends

### 6. Admin Panel
- Secure authentication required
- Multiple view options (mobile/desktop)
- CSV/PDF report export
- Auto-refresh every 5 minutes
- Rate limiting (100 requests/hour)

## API Usage

### From PHP Code

```php
<?php
require_once 'helpers/seo_analytics/GoogleSearchConsoleAPI.php';

$config = include 'helpers/seo_analytics/config.php';
$gsc = new GoogleSearchConsoleAPI($config);

$result = $gsc->getSearchPerformance(30, ['query', 'page']);

if ($result['status'] === 'success') {
    foreach ($result['data'] as $row) {
        echo $row['query'] . ': ' . $row['clicks'] . ' clicks';
    }
}
?>
```

### From JavaScript (AJAX)

```javascript
fetch('/api/seo_analytics/search_performance.php?days=30')
    .then(r => r.json())
    .then(data => {
        if (data.status === 'success') {
            console.log(data.data);
        }
    });
```

## Security Features

- ✅ Session-based authentication
- ✅ Rate limiting (configurable)
- ✅ Environment variable support for secrets
- ✅ HTTPS-only data transmission
- ✅ Request logging and monitoring
- ✅ Cache management (1-24 hour TTL)
- ✅ CORS headers support

## Caching Strategy

- **Search Console data:** 1 hour cache
- **GA4 realtime:** 60 seconds cache
- **Site audit:** 1 hour cache
- **Backlinks:** 24 hour cache
- **Top pages:** 1 hour cache

Cache files stored in `/cache/seo_analytics/`

## Database (Optional)

To store historical data for comparison and reports:

```sql
CREATE TABLE seo_analytics_gsc_data (
    id INT PRIMARY KEY AUTO_INCREMENT,
    query VARCHAR(255),
    page VARCHAR(255),
    clicks INT,
    impressions INT,
    ctr DECIMAL(5,2),
    position DECIMAL(5,2),
    recorded_date DATE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE seo_analytics_ga4_data (
    id INT PRIMARY KEY AUTO_INCREMENT,
    page_path VARCHAR(255),
    pageviews INT,
    sessions INT,
    engagement_rate DECIMAL(5,2),
    recorded_date DATE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

## Extending the System

### Add New Module

1. Create class extending `SEOAnalyticsBase`
2. Implement API integration methods
3. Create API endpoint file in `/api/seo_analytics/`
4. Add section file in `/admin/seo_analytics/sections/`
5. Link in dashboard navigation

### Example:
```php
class MyCustomAnalytics extends SEOAnalyticsBase {
    public function getData() {
        // Implementation
    }
}
```

## Troubleshooting

### API Connection Errors
- Verify API keys in config
- Check environment variables are loaded
- Ensure HTTPS connection
- Check rate limits

### Chart Not Rendering
- Ensure ApexCharts is loaded
- Check console for JavaScript errors
- Verify data format from API

### Cache Issues
- Check `/cache/seo_analytics/` permissions
- Manually clear cache: `rm -rf cache/seo_analytics/*`
- Verify TTL settings in config

### Authentication Failed
- Ensure admin session is active
- Check `$_SESSION['admin_id']` is set
- Verify user has admin role

## Performance Optimization

- Implements request caching to reduce API calls
- Uses passive FTP mode for stability
- Lazy loads charts on demand
- Implements rate limiting
- Database indexing recommended for reports

## Support & Monitoring

- All requests logged to `/logs/seo_analytics.log`
- Error handling with try-catch blocks
- JSON API responses with status codes
- Debug mode available in config

## License

This module integrates with your existing system and is provided as-is for SEO analytics enhancement.

---

**Last Updated:** January 25, 2026
**Version:** 1.0.0
**Status:** Fully Modular - No Disruption to Existing SEO
