# MaplePress Plugin - Getting Started Guide

This guide will walk you through setting up the MaplePress plugin for both local development and production release. No prior WordPress experience required!

---

## Table of Contents

1. [What is WordPress?](#what-is-wordpress)
2. [Local Development Setup](#local-development-setup)
3. [Production Release Workflow](#production-release-workflow)
4. [Common Tasks](#common-tasks)
5. [Troubleshooting](#troubleshooting)

---

## What is WordPress?

**WordPress** is a content management system (CMS) written in PHP. It powers over 40% of websites on the internet.

**WordPress Plugin** = A piece of software that adds specific functionality to a WordPress site. Our MaplePress plugin adds cloud-powered search functionality.

**Key WordPress Concepts:**
- **wp-admin** = WordPress admin dashboard (where you configure plugins)
- **wp-config.php** = WordPress configuration file (like a .env file for WordPress)
- **wp-content/plugins/** = Directory where all plugins are stored
- **Activation** = Turning on a plugin in WordPress
- **Settings Page** = Admin interface where users configure your plugin

---

## Local Development Setup

### Prerequisites

Make sure you have:
- Docker running
- Task (taskfile.dev) installed
- MaplePress backend running

### Step 1: Start WordPress

```bash
# From the infrastructure directory
cd cloud/infrastructure/development

# Start all services (includes WordPress)
task dev:start

# OR if using docker-compose directly:
docker-compose -f docker-compose.dev.yml up -d
```

**What this does:**
- Starts MariaDB (WordPress database) on port 3306
- Starts WordPress on port 8081
- Starts Cassandra cluster (3 nodes) for backend
- Starts Redis for caching
- Starts Meilisearch for search indexing
- Starts SeaweedFS for object storage
- Mounts your plugin directory into WordPress

**Note:** This starts the entire infrastructure, not just WordPress. The `task dev:start` command will:
1. Start all Docker containers
2. Wait for services to be healthy (this can take 1-2 minutes)
3. Initialize Cassandra keyspaces
4. Show you the status of all running services

**Access WordPress:**
- Frontend: http://localhost:8081
- Admin: http://localhost:8081/wp-admin

**Other Services (for backend development):**
- Backend API: http://localhost:8000 (when you start maplepress-backend)
- Meilisearch: http://localhost:7700
- SeaweedFS: http://localhost:9333

### Step 2: Initial WordPress Setup (First Time Only)

If this is your first time, WordPress will ask you to set it up:

1. Open http://localhost:8081 in your browser
2. Select language (English)
3. Click "Let's go!"
4. Database settings are already configured (from docker-compose.dev.yml):
   - Database Name: `wordpress`
   - Username: `wordpress`
   - Password: `wordpress`
   - Database Host: `mariadb` (the container name)
   - Table Prefix: `wp_` (leave default)
5. Click "Submit" then "Run the installation"
6. Create admin user:
   - Site Title: "MaplePress Development"
   - Username: `admin` (or your choice)
   - Password: (choose a strong password)
   - Email: your email
7. Click "Install WordPress"
8. Login with your admin credentials

**You only need to do this once.** WordPress saves everything in the database.

### Step 3: Configure Plugin for Local Development

```bash
# From the plugin directory
cd native/wordpress/maplepress-plugin

# Run the setup command
task dev:setup
```

**What this does:**
1. Creates `wp-config.local.php` with `MAPLEPRESS_API_URL` set to `http://localhost:8000`
2. Modifies WordPress `wp-config.php` to load your local config
3. Pre-configures the plugin to connect to your local backend

**Output:**
```
Created wp-config.local.php
Added loader to wp-config.php
Local development environment configured
API URL pre-configured to http://localhost:8000
Go to Settings > MaplePress to enter your API key
```

### Step 4: Activate the Plugin in WordPress

1. Go to http://localhost:8081/wp-admin/plugins.php
2. Find "MaplePress" in the plugin list
3. Click "Activate"
4. You'll be redirected to Settings → MaplePress

### Step 5: Enter Your API Key

1. You should now be on the MaplePress settings page
2. You'll see:
   - **API URL** - Pre-filled with `http://localhost:8000` ✓
   - **API Key** - Empty (you need to enter this)
3. Get your API key:
   - If you don't have one yet, follow the backend setup guide:
     - See `cloud/maplepress-backend/GETTING-STARTED.md` → "Create Test Data"
     - Or use the quick commands below:

   ```bash
   # Register a user and create a site (returns API key)
   # See backend GETTING-STARTED.md for detailed instructions
   curl -X POST http://localhost:8000/api/v1/register \
     -H "Content-Type: application/json" \
     -d '{"email":"test@example.com","password":"TestPassword123!","name":"Test User","tenant_name":"Test Org","tenant_slug":"test-org"}'

   # Then create a site (save the API key from response)
   curl -X POST http://localhost:8000/api/v1/sites \
     -H "Authorization: JWT YOUR_TOKEN_HERE" \
     -H "Content-Type: application/json" \
     -d '{"domain":"localhost:8081","site_url":"http://localhost:8081","plan_tier":"free"}'
   ```
4. Paste the API key
5. Click "Save Settings & Verify Connection"

**If successful:**
- Green message: "✓ API connection verified successfully!"
- You'll see your site details (Site ID, Tenant ID, Domain, Plan)
- Status shows "Active"

**If it fails:**
- Red error message explaining what went wrong
- Check that backend is running: `curl http://localhost:8000/health`
- Check API key is valid
- See backend docs: `cloud/maplepress-backend/GETTING-STARTED.md`

### Step 6: Start Developing

Your local development environment is now ready!

**Making code changes:**

Option 1: Auto-sync (Recommended)
```bash
cd native/wordpress/maplepress-plugin

# Watch for changes and auto-sync
task watch
```
This will automatically copy changes to WordPress whenever you save a file.

Option 2: Manual sync
```bash
# After making changes, sync manually
task sync
```

Option 3: Direct editing (Advanced)
- Plugin is mounted as a volume, so changes are usually reflected immediately
- Just refresh your browser after editing PHP files
- Some changes require plugin reactivation

**Viewing logs:**
```bash
# See WordPress debug logs
task logs

# Access WordPress container shell
task shell
```

---

## Production Release Workflow

### Understanding Production vs Development

**Development:**
- API URL: `http://localhost:8000` (your local backend)
- API Key: Your test API key
- Config file: `wp-config.local.php` (git-ignored)

**Production:**
- API URL: `https://getmaplepress.ca` (production backend)
- API Key: User enters their own API key from dashboard
- Config file: None (users configure via settings)

### Step 1: Prepare for Release

**Clean up local config:**
```bash
cd native/wordpress/maplepress-plugin

# Remove local development settings
task dev:reset
```

This removes:
- `wp-config.local.php` (local config file)
- Loader code from WordPress `wp-config.php`

**Verify production behavior:**
1. Deactivate the plugin in WordPress
2. Delete plugin options: Settings → MaplePress → Delete (if there's an option)
3. Reactivate the plugin
4. Go to Settings → MaplePress
5. Both API URL and API Key should be **empty** ✓

This is what users will see when they install your plugin.

### Step 2: Build Production Zip

```bash
cd native/wordpress/maplepress-plugin

# Build the distribution package
task build
```

**What this does:**
1. Creates `dist/` directory
2. Copies all plugin files EXCEPT:
   - `wp-config.local.php` (local dev config)
   - `.git/` (version control)
   - `node_modules/` (dependencies)
   - `Taskfile.yml` (development tool)
   - `composer.json/lock` (PHP dependencies)
   - `.gitignore` (git config)
   - `dist/` (avoid nested builds)
3. Creates `dist/maplepress-plugin.zip`

**Output:**
```
Plugin built at dist/maplepress-plugin.zip
Local dev files excluded from build
```

### Step 3: Test Production Build Locally (Optional but Recommended)

Before releasing, test the production build:

```bash
# Extract and verify contents
cd dist
unzip -l maplepress-plugin.zip

# Should NOT contain:
# - wp-config.local.php
# - Taskfile.yml
# - composer.json
# - .gitignore
# - .git/

# Should contain:
# - maplepress-plugin.php (main file)
# - includes/ (PHP classes)
# - assets/ (CSS/JS)
# - readme.txt (WordPress.org readme)
# - CHANGELOG.md, TESTING.md, etc.
```

**Test installation:**
1. Copy the zip to a clean WordPress install (or delete current plugin)
2. Go to Plugins → Add New → Upload Plugin
3. Choose `dist/maplepress-plugin.zip`
4. Click "Install Now"
5. Activate the plugin
6. Verify settings page shows:
   - Empty API URL field ✓
   - Empty API Key field ✓
   - Placeholder: `https://getmaplepress.ca` ✓

### Step 4: Release to WordPress.org

**WordPress Plugin Directory Submission:**

1. **Create WordPress.org Account**
   - Go to https://wordpress.org/support/register.php
   - Create an account (you'll need this to submit plugins)

2. **Submit Plugin for Review**
   - Go to https://wordpress.org/plugins/developers/add/
   - Upload your `dist/maplepress-plugin.zip`
   - Wait for manual review (can take 2-14 days)
   - You'll receive an email with SVN repository access

3. **Using SVN (Subversion)**

   WordPress.org uses SVN, not Git:

   ```bash
   # Checkout your plugin's SVN repository
   # (URL provided in approval email)
   svn co https://plugins.svn.wordpress.org/maplepress YOUR_LOCAL_DIR
   cd YOUR_LOCAL_DIR

   # Directory structure:
   # /trunk/      - Development version
   # /tags/       - Released versions (1.0.0, 1.0.1, etc.)
   # /assets/     - Screenshots, banners, icons
   ```

4. **Initial Release (Version 1.0.0)**

   ```bash
   # Extract your plugin to /trunk/
   cd trunk
   unzip ../../dist/maplepress-plugin.zip
   mv maplepress-plugin/* .
   rmdir maplepress-plugin

   # Add files to SVN
   svn add --force * --auto-props --parents --depth infinity -q

   # Commit to trunk
   svn ci -m "Initial release v1.0.0"

   # Create a tag for this version
   cd ..
   svn cp trunk tags/1.0.0
   svn ci -m "Tagging version 1.0.0"
   ```

5. **Add Screenshots and Assets**

   ```bash
   # Add to /assets/ directory
   cd assets

   # Required files:
   # - icon-128x128.png (plugin icon)
   # - icon-256x256.png (retina icon)
   # - screenshot-1.png (settings page)
   # - screenshot-2.png (search widget)
   # - banner-772x250.png (plugin page banner)
   # - banner-1544x500.png (retina banner)

   svn add *.png
   svn ci -m "Add plugin assets"
   ```

### Step 5: Version Updates

When releasing a new version:

```bash
# 1. Update version in plugin files
# Edit maplepress-plugin.php:
# Version: 1.0.1

# Edit readme.txt:
# Stable tag: 1.0.1

# 2. Build new release
cd native/wordpress/maplepress-plugin
task build

# 3. Update SVN trunk
cd YOUR_SVN_DIR/trunk
# Replace files with new build
unzip ../../dist/maplepress-plugin.zip
mv maplepress-plugin/* .

# Commit to trunk
svn stat  # See what changed
svn ci -m "Update to version 1.0.1"

# 4. Create new tag
cd ..
svn cp trunk tags/1.0.1
svn ci -m "Tagging version 1.0.1"
```

WordPress.org will automatically update users' plugins within 24 hours.

---

## Common Tasks

### Switch Between Local Dev and Production Testing

**Enable local development:**
```bash
task dev:setup
# Restart WordPress
docker-compose -f ../../cloud/infrastructure/development/docker-compose.dev.yml restart wordpress
```

**Test production behavior:**
```bash
task dev:reset
# Deactivate/reactivate plugin in WordPress
```

### View Plugin in WordPress

- **Plugins page:** http://localhost:8081/wp-admin/plugins.php
- **Settings page:** http://localhost:8081/wp-admin/options-general.php?page=maplepress

### Check If Plugin Is Active

```bash
# From container
docker exec mapleopentech-wordpress-dev wp plugin list

# Should show:
# name         status
# maplepress   active
```

### Manually Inspect Database

```bash
# Connect to MariaDB
docker exec -it mapleopentech-mariadb-dev mysql -u wordpress -pwordpress wordpress

# Check plugin options
SELECT * FROM wp_options WHERE option_name = 'maplepress_settings';

# Exit
exit
```

### Reset WordPress Completely

```bash
# Stop containers
docker-compose -f docker-compose.dev.yml down

# Delete volumes (WARNING: Deletes all data)
docker volume rm mapleopentech-wordpress-dev
docker volume rm mapleopentech-mariadb-dev

# Start fresh
docker-compose -f docker-compose.dev.yml up -d

# You'll need to go through WordPress setup again
```

### Check Plugin Files in Container

```bash
# Access container shell
task shell

# Inside container:
cd /var/www/html/wp-content/plugins/maplepress-plugin
ls -la

# Check if wp-config.local.php exists
cat wp-config.local.php  # Should show MAPLEPRESS_API_URL

# Check WordPress config has loader
grep -A2 "MaplePress local" /var/www/html/wp-config.php
```

---

## Troubleshooting

### "Task does not exist" Error

**Error:** `task: Task "dev" does not exist`

**Solution:** The correct command is `task dev:start` (not `task dev`)

```bash
cd cloud/infrastructure/development
task dev:start  # ✓ Correct
# NOT: task dev  # ✗ Wrong
```

**Available infrastructure tasks:**
- `task dev:start` - Start all services
- `task dev:stop` - Stop all services
- `task dev:status` - Show service status
- `task dev:restart` - Restart all services
- `task dev:logs` - View logs
- `task dev:clean` - Remove all data (destructive)

### "Cannot connect to API" Error

**Possible causes:**

1. **Backend not running**
   ```bash
   # Check if backend is up
   curl http://localhost:8000/health

   # Should return: {"status":"healthy"}
   # If not, start backend:
   cd cloud/maplepress-backend
   task dev

   # For detailed setup, see: cloud/maplepress-backend/GETTING-STARTED.md
   ```

2. **Wrong API URL**
   - Check Settings → MaplePress
   - For local dev, should be: `http://localhost:8000`
   - Not `localhost:8081` (that's WordPress)
   - Not `https://` (local dev is http)

3. **Invalid API Key**
   - API key must exist in backend database
   - Check backend logs for authentication errors

### "Plugin not showing up"

1. **Check plugin directory:**
   ```bash
   docker exec mapleopentech-wordpress-dev ls -la /var/www/html/wp-content/plugins/
   ```
   Should see `maplepress-plugin/`

2. **Check main plugin file exists:**
   ```bash
   docker exec mapleopentech-wordpress-dev ls -la /var/www/html/wp-content/plugins/maplepress-plugin/maplepress-plugin.php
   ```

3. **Check plugin header:**
   ```bash
   docker exec mapleopentech-wordpress-dev head -n 15 /var/www/html/wp-content/plugins/maplepress-plugin/maplepress-plugin.php
   ```
   Should show "Plugin Name: MaplePress"

4. **Restart WordPress:**
   ```bash
   docker-compose -f docker-compose.dev.yml restart wordpress
   ```

### "API URL not pre-filled" in Local Dev

1. **Check local config exists:**
   ```bash
   cat wp-config.local.php
   ```
   Should show `define('MAPLEPRESS_API_URL', 'http://localhost:8000');`

2. **Check WordPress config has loader:**
   ```bash
   docker exec mapleopentech-wordpress-dev grep -A2 "MaplePress" /var/www/html/wp-config.php
   ```
   Should show loader code

3. **Re-run setup:**
   ```bash
   task dev:reset
   task dev:setup
   ```

4. **Deactivate and reactivate plugin:**
   - Go to http://localhost:8081/wp-admin/plugins.php
   - Click "Deactivate" under MaplePress
   - Click "Activate"
   - Check settings page again

### "Changes not showing up"

**For PHP changes:**
1. **Deactivate and reactivate plugin**
   - WordPress caches plugin code

2. **Or sync manually:**
   ```bash
   task sync
   ```

3. **Or restart WordPress:**
   ```bash
   docker-compose -f ../../cloud/infrastructure/development/docker-compose.dev.yml restart wordpress
   ```

**For CSS/JS changes:**
- Hard refresh browser: Cmd+Shift+R (Mac) or Ctrl+Shift+R (Windows)
- Or clear browser cache

### "Permission denied" Errors

```bash
# Fix plugin directory permissions
docker exec mapleopentech-wordpress-dev chown -R www-data:www-data /var/www/html/wp-content/plugins/maplepress-plugin

# Restart WordPress
docker-compose -f docker-compose.dev.yml restart wordpress
```

### WordPress Shows "Fatal Error"

**Check PHP error log:**
```bash
docker exec mapleopentech-wordpress-dev tail -f /var/www/html/wp-content/debug.log
```

**Enable WordPress debug mode:**
```bash
docker exec mapleopentech-wordpress-dev bash -c "
grep -q 'WP_DEBUG' /var/www/html/wp-config.php ||
sed -i \"/That's all, stop editing/i define('WP_DEBUG', true);\ndefine('WP_DEBUG_LOG', true);\ndefine('WP_DEBUG_DISPLAY', false);\" /var/www/html/wp-config.php
"
```

**Syntax error in PHP:**
- Check PHP syntax: `php -l includes/class-maplepress-admin.php`
- Look for missing semicolons, quotes, or brackets

### "Can't access wp-admin"

```bash
# Reset admin password
docker exec mapleopentech-wordpress-dev wp user update admin --user_pass=newpassword
```

### Build Includes Local Dev Files

**Verify build excludes:**
```bash
cd dist
unzip -l maplepress-plugin.zip | grep "wp-config.local"
# Should return nothing

unzip -l maplepress-plugin.zip | grep "Taskfile"
# Should return nothing
```

**If they're included, rebuild:**
```bash
task clean
task build
```

---

## Quick Reference

### Commands Cheat Sheet

```bash
# Infrastructure
cd cloud/infrastructure/development
task dev:start              # Start all services
task dev:stop               # Stop all services
task dev:status             # Show service status
task dev:logs               # View logs

# Plugin Development
cd native/wordpress/maplepress-plugin
task dev:setup              # Set up local dev (first time)
task dev:reset              # Reset to production config
task sync                   # Sync changes to WordPress
task watch                  # Auto-sync on file changes
task logs                   # View WordPress logs
task shell                  # Access WordPress container

# Production Release
task build                  # Build distribution zip
task clean                  # Clean build artifacts

# Testing
task lint                   # Check code style
task test                   # Run tests
```

### URLs

- WordPress Frontend: http://localhost:8081
- WordPress Admin: http://localhost:8081/wp-admin
- Plugin Settings: http://localhost:8081/wp-admin/options-general.php?page=maplepress
- Backend API: http://localhost:8000

### WordPress CLI (inside container)

```bash
# Access container
docker exec -it mapleopentech-wordpress-dev /bin/bash

# WordPress CLI commands
wp plugin list              # List plugins
wp plugin activate maplepress
wp plugin deactivate maplepress
wp option get maplepress_settings
wp option delete maplepress_settings
wp user list                # List users
wp db query "SELECT * FROM wp_options WHERE option_name LIKE 'maplepress%'"
```

---

## Next Steps

1. **For Development:**
   - Follow "Local Development Setup"
   - Run `task dev:setup`
   - Start coding!

2. **For First Release:**
   - Follow "Production Release Workflow"
   - Build with `task build`
   - Submit to WordPress.org

3. **Learn More:**
   - WordPress Plugin Handbook: https://developer.wordpress.org/plugins/
   - WordPress Coding Standards: https://developer.wordpress.org/coding-standards/
   - Plugin Directory Guidelines: https://developer.wordpress.org/plugins/wordpress-org/

---

**Still stuck? Check:**
- `TESTING.md` - Testing scenarios and checklist
- `CHANGELOG.md` - Recent changes and updates
- Backend docs: `cloud/maplepress-backend/GETTING-STARTED.md` and `API.md`
