# InstaRank WordPress Plugin - Implementation Guide

## Current Status

✅ **Completed:**
- Main plugin file (`instarank.php`)
- SEO Plugin Detector (`class-seo-detector.php`)
- Directory structure created
- Database schema defined

⏳ **Remaining Files to Create:**

See the complete list below with code templates.

---

## Directory Structure

```
wordpress-plugin/instarank-seo/
├── instarank.php                    ✅ DONE
├── readme.txt                            ⏳ TODO
├── includes/
│   ├── class-api-handler.php             ⏳ TODO
│   ├── class-auth-manager.php            ⏳ TODO
│   ├── class-seo-detector.php            ✅ DONE
│   ├── class-change-manager.php          ⏳ TODO
│   └── class-webhook-sender.php          ⏳ TODO
├── admin/
│   ├── dashboard.php                     ⏳ TODO
│   ├── changes.php                       ⏳ TODO
│   └── settings.php                      ⏳ TODO
├── api/
│   └── endpoints.php                     ⏳ TODO
└── assets/
    ├── css/
    │   └── admin.css                     ⏳ TODO
    └── js/
        └── admin.js                      ⏳ TODO
```

---

## Installation Instructions

### 1. Copy Plugin to WordPress

```bash
# Copy the plugin folder to your WordPress plugins directory
cp -r wordpress-plugin/instarank-seo /path/to/wordpress/wp-content/plugins/

# Or create a ZIP for upload
cd wordpress-plugin
zip -r instarank-seo.zip instarank-seo/
```

### 2. Activate in WordPress

```
WordPress Admin → Plugins → InstaRank SEO → Activate
```

### 3. Get API Key

```
WordPress Admin → InstaRank SEO → Dashboard
→ Copy the API Key shown
```

### 4. Connect to InstaRank Platform

Use the API key to connect from your InstaRank platform.

---

## Remaining Implementation

I've created the foundation. Here are the remaining files you need to create:

### Priority 1: Core Functionality

#### 1. `api/endpoints.php` - REST API Endpoints

This file registers all custom WordPress REST API endpoints that InstaRank will call.

**Key endpoints needed:**
- `GET /wp-json/instarank/v1/site-info` - Get site information
- `GET /wp-json/instarank/v1/posts` - Get all posts for mapping
- `POST /wp-json/instarank/v1/apply-changes` - Apply SEO changes
- `POST /wp-json/instarank/v1/rollback/{id}` - Rollback a change
- `GET /wp-json/instarank/v1/changes` - Get change history

#### 2. `includes/class-change-manager.php` - Change Management

Handles applying and rolling back SEO changes.

**Key methods:**
- `apply_change()` - Apply a change to WordPress
- `rollback_change()` - Revert a change
- `get_changes()` - Get change history
- `validate_change()` - Validate change data

#### 3. `includes/class-auth-manager.php` - Authentication

Manages API key generation and validation.

**Key methods:**
- `generate_api_key()` - Generate new API key
- `verify_api_key()` - Validate incoming requests
- `regenerate_key()` - Regenerate API key

### Priority 2: Admin UI

#### 4. `admin/dashboard.php` - Main Dashboard

Shows connection status, statistics, recent changes.

**Displays:**
- Connection status
- API key (with copy button)
- Connected InstaRank project
- Recent changes count
- Quick actions

#### 5. `admin/changes.php` - Changes Page

Lists all pending and applied changes with approve/reject buttons.

**Features:**
- Filter by status (pending/applied/rolled_back)
- Approve/reject individual changes
- Bulk approve
- View change details
- One-click rollback

#### 6. `admin/settings.php` - Settings Page

Configuration options for the plugin.

**Settings:**
- Auto-approve changes (yes/no)
- Allowed change types (checkboxes)
- Webhook URL
- Rollback retention days

### Priority 3: Supporting Files

#### 7. `includes/class-webhook-sender.php` - Webhooks

Sends notifications back to InstaRank platform.

**Events to send:**
- Plugin activated
- Plugin deactivated
- Changes applied
- Change rolled back
- Settings updated

#### 8. `assets/css/admin.css` - Admin Styles

Styling for admin pages.

#### 9. `assets/js/admin.js` - Admin JavaScript

Interactive functionality for admin pages.

**Features:**
- Copy API key to clipboard
- Approve/reject changes via AJAX
- Auto-refresh change status
- Connection test

---

## InstaRank Platform Integration

You also need to build the InstaRank side of the integration:

### 1. Database Migration

Create a Supabase migration for WordPress integration tables:

```sql
-- wordpress_integrations table
CREATE TABLE wordpress_integrations (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    site_url TEXT NOT NULL,
    api_key TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'connected',
    last_synced_at TIMESTAMPTZ,
    plugin_version TEXT,
    seo_plugin TEXT,
    config JSONB DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(project_id)
);

-- wordpress_mappings table
CREATE TABLE wordpress_mappings (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    integration_id UUID NOT NULL REFERENCES wordpress_integrations(id) ON DELETE CASCADE,
    crawled_url TEXT NOT NULL,
    wordpress_url TEXT NOT NULL,
    post_id INTEGER NOT NULL,
    post_type TEXT NOT NULL,
    post_title TEXT,
    last_synced_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(integration_id, post_id)
);

-- wordpress_changes table
CREATE TABLE wordpress_changes (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    integration_id UUID NOT NULL REFERENCES wordpress_integrations(id) ON DELETE CASCADE,
    mapping_id UUID REFERENCES wordpress_mappings(id),
    fix_id UUID REFERENCES ai_fixes(id),
    change_type TEXT NOT NULL,
    field_name TEXT,
    old_value TEXT,
    new_value TEXT,
    status TEXT NOT NULL DEFAULT 'pending',
    applied_at TIMESTAMPTZ,
    error_message TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);
```

### 2. API Endpoints (InstaRank Platform)

```typescript
// POST /api/integrations/wordpress/connect
// Connect a WordPress site

// POST /api/integrations/wordpress/sync
// Sync posts from WordPress

// POST /api/integrations/wordpress/push-changes
// Push SEO fixes to WordPress

// GET /api/integrations/wordpress/{id}/changes
// Get change history
```

### 3. Integration UI (InstaRank Platform)

Add WordPress to your integrations page:

Location: `app/integrations/page.tsx`

Add WordPress to the integrations list alongside Google and AI integrations.

---

## Quick Start Development Workflow

### Step 1: Complete the Plugin

1. Create remaining PHP files (use templates from `docs/wordpress-plugin-integration.md`)
2. Test plugin activation in WordPress
3. Verify API key generation
4. Test REST API endpoints with Postman/curl

### Step 2: Build InstaRank Integration

1. Run database migration
2. Create API endpoints
3. Add WordPress to integrations UI
4. Test connection flow

### Step 3: End-to-End Testing

1. Install plugin in WordPress
2. Connect from InstaRank platform
3. Run a crawl
4. Generate AI fixes
5. Push changes to WordPress
6. Verify changes applied
7. Test rollback

---

## Testing the Plugin

### Manual Testing

```bash
# Test API key generation
curl https://your-wordpress-site.com/wp-admin/admin-ajax.php?action=instarank_get_api_key

# Test site info endpoint
curl -H "X-InstaRank-API-Key: your-api-key" \
     https://your-wordpress-site.com/wp-json/instarank/v1/site-info

# Test getting posts
curl -H "X-InstaRank-API-Key: your-api-key" \
     https://your-wordpress-site.com/wp-json/instarank/v1/posts

# Test applying a change
curl -X POST \
     -H "X-InstaRank-API-Key: your-api-key" \
     -H "Content-Type: application/json" \
     -d '{"changes":[{"post_id":1,"type":"meta_description","value":"New description"}]}' \
     https://your-wordpress-site.com/wp-json/instarank/v1/apply-changes
```

---

## Distribution

### Option 1: Direct Download

Host the ZIP file on InstaRank website:
```
https://instarank.com/downloads/instarank-seo.zip
```

### Option 2: WordPress.org Repository

Submit to WordPress plugin repository:
1. Create `readme.txt` (see template in docs)
2. Add screenshots
3. Submit at https://wordpress.org/plugins/developers/add/

### Option 3: GitHub Releases

Host on GitHub and use automatic updates via GitHub Updater plugin.

---

## Next Steps

1. **Complete the remaining PHP files** using the code from `docs/wordpress-plugin-integration.md`
2. **Create the database migration** for InstaRank platform
3. **Build the InstaRank integration UI**
4. **Test end-to-end workflow**
5. **Package and distribute the plugin**

Would you like me to continue creating the remaining files, or would you prefer to handle them yourself using the templates in the documentation?
