# Site Builder - WHP Integration Guide

## Overview

This site builder integrates with WHP (Web Hosting Panel) to provide users with a visual site building interface. Users can create HTML pages using a drag-and-drop editor and save them directly to their web hosting account.

## Architecture

### Components

1. **Frontend (GrapesJS)**
   - Location: `/home/jknapp/code/site-builder/`
   - Visual drag-and-drop editor
   - Real-time preview
   - Device responsive design tools

2. **Backend API**
   - Location: `/home/jknapp/code/whp/web-files/api/site-builder.php`
   - Handles save/load/list/delete operations
   - Integrates with WHP authentication system
   - Stores sites in user's home directory

3. **WHP Integration Layer**
   - File: `js/whp-integration.js`
   - Connects frontend to backend API
   - Provides save/load UI
   - Auto-save functionality

## Installation

### 1. Deploy Backend API

Copy the site builder API to the WHP web files:

```bash
cp /home/jknapp/code/whp/web-files/api/site-builder.php /docker/whp/web/api/
```

Or run WHP update script to sync:

```bash
cd /home/jknapp/code/whp
./update.sh
```

### 2. Deploy Frontend

Copy the site builder files to the WHP web directory:

```bash
# Create site-builder directory in WHP
mkdir -p /docker/whp/web/site-builder

# Copy all files
cp -r /home/jknapp/code/site-builder/* /docker/whp/web/site-builder/
```

### 3. Configure Access

The site builder should be accessible to authenticated WHP users at:
```
https://your-whp-domain.com/site-builder/
```

## User Directory Structure

When a user saves a site, it creates the following structure:

```
/home/{username}/public_html/site-builder/
├── sites/
│   ├── site_abc123.json        # GrapesJS project data
│   ├── site_abc123.html        # Compiled HTML output
│   ├── site_xyz789.json
│   └── site_xyz789.html
```

### File Formats

**JSON File** (`.json`):
```json
{
  "id": "site_abc123",
  "name": "My Awesome Site",
  "created": 1708531200,
  "modified": 1708617600,
  "html": "<div>...</div>",
  "css": "body { ... }",
  "grapesjs": { ... }
}
```

**HTML File** (`.html`):
- Complete, standalone HTML file
- Includes embedded CSS
- Ready to publish/share
- Accessible via: `https://your-domain.com/~username/site-builder/sites/site_abc123.html`

## API Endpoints

All endpoints require WHP authentication (session-based).

### List Sites
```
GET /api/site-builder.php?action=list
```

Response:
```json
{
  "success": true,
  "sites": [
    {
      "id": "site_abc123",
      "name": "My Site",
      "created": 1708531200,
      "modified": 1708617600,
      "url": "/~username/site-builder/sites/site_abc123.html"
    }
  ]
}
```

### Load Site
```
GET /api/site-builder.php?action=load&id=site_abc123
```

Response:
```json
{
  "success": true,
  "site": {
    "id": "site_abc123",
    "name": "My Site",
    "html": "<div>...</div>",
    "css": "body { ... }",
    "grapesjs": { ... }
  }
}
```

### Save Site
```
POST /api/site-builder.php?action=save
Content-Type: application/json

{
  "id": "site_abc123",
  "name": "My Site",
  "html": "<div>...</div>",
  "css": "body { ... }",
  "grapesjs": { ... }
}
```

Response:
```json
{
  "success": true,
  "site": {
    "id": "site_abc123",
    "name": "My Site",
    "url": "/~username/site-builder/sites/site_abc123.html"
  }
}
```

### Delete Site
```
GET /api/site-builder.php?action=delete&id=site_abc123
```

Response:
```json
{
  "success": true,
  "message": "Site deleted successfully"
}
```

## Security

### Authentication
- Uses WHP's existing authentication system
- `AUTH_USER` constant provides current username
- `HOME_DIR` constant provides user's home directory path
- Session-based authentication (handled by `auto-prepend.php`)

### Path Security
- All user paths are validated and sanitized
- `basename()` used to prevent path traversal
- Files stored only in user's home directory
- No cross-user access possible

### File Permissions
- Site directories created with `0755` permissions
- Files inherit user's ownership
- Web server can read/serve files
- Users can only access their own sites

## Frontend Integration

### Adding WHP Integration to Index.html

Add this script tag before the closing `</body>`:

```html
<script src="js/whp-integration.js"></script>
```

The integration will automatically:
1. Add "Save" and "Load" buttons to the toolbar
2. Enable auto-save every 30 seconds
3. Provide site management dialog

### Custom API URL

If the API is hosted elsewhere:

```javascript
// In whp-integration.js or custom config
window.editor.onReady(() => {
    window.whpInt = new WHPIntegration(window.editor, 'https://custom-api.com/api/site-builder.php');
});
```

## Testing

### For AI Agents

You can test the API using curl (requires valid session):

```bash
# List sites
curl 'http://localhost/api/site-builder.php?action=list' \
  -H 'Cookie: PHPSESSID=your_session_id'

# Save a test site
curl 'http://localhost/api/site-builder.php?action=save' \
  -X POST \
  -H 'Cookie: PHPSESSID=your_session_id' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Test Site",
    "html": "<h1>Hello World</h1>",
    "css": "h1 { color: blue; }"
  }'
```

### Manual Testing

1. Log into WHP
2. Navigate to `/site-builder/`
3. Create a test page using the visual editor
4. Click "Save" and enter a site name
5. Verify the site appears in the load dialog
6. Check the generated HTML at `/~username/site-builder/sites/`

## Troubleshooting

### "Not authenticated" Error
- Ensure you're logged into WHP first
- Check that `auto-prepend.php` is running
- Verify session cookies are being sent

### Save/Load Fails
- Check PHP error logs: `/var/log/apache2/error.log`
- Verify directory permissions on `~/public_html/site-builder`
- Ensure API file is executable by PHP-FPM

### Sites Not Appearing
- Check ownership: `ls -la ~/public_html/site-builder/sites/`
- Verify files were created: `.json` and `.html` files should exist
- Check Apache access logs for 404s

## Future Enhancements

Potential improvements:
- Publishing workflow (move from `site-builder/` to production location)
- Template library
- Asset management (images, fonts)
- Multi-page site support
- Export to ZIP
- Collaboration features
- Version history

## Development

### Local Development Setup

For development without WHP authentication:

```javascript
// Add to whp-integration.js (development only)
const DEV_MODE = true;
if (DEV_MODE) {
    // Mock API responses for testing
    class MockAPI {
        async save(data) { console.log('Mock save:', data); }
        async load(id) { return { success: true, site: mockSite }; }
    }
}
```

### File Locations

**Development:**
- Frontend: `/home/jknapp/code/site-builder/`
- Backend: `/home/jknapp/code/whp/web-files/api/site-builder.php`

**Production:**
- Frontend: `/docker/whp/web/site-builder/`
- Backend: `/docker/whp/web/api/site-builder.php`
- User sites: `/home/{username}/public_html/site-builder/sites/`

## License

This integration follows the WHP project licensing.
