# CDN Upload Setup for WordWeb Software Website

This document explains how to set up automatic CDN uploads for CSS and JS files
when code is pushed to the master branch.

## Overview

The system provides automatic CDN deployment and smart local/CDN file detection:

**CDN Upload (Master Branch Only):** When code is pushed to the `master` branch,
the webhook automatically:

1. Pulls the latest changes from GitHub
2. Minifies CSS and JS files (removes comments and whitespace for faster loading)
3. Uploads the minified files to IBM Cloud Object Storage
4. Purges and prefetches the files in CDN77 cache
5. Logs all activities including minification savings for monitoring

**Note:** Source files in the repository remain unchanged - only the uploaded CDN versions are minified.

**Smart File Detection:** The system automatically detects whether to use local
files or CDN based on directory path:

- **Production**: Uses CDN URLs
  (https://uk.wordwebsoftware.com/wordweb/css|js/)
- **Testing**: Uses local files in root when directory contains "test."

Use "wordweb" directory (rather than wordwebsoftware).

## Files Uploaded to CDN

The following files are automatically uploaded to the CDN when changes are pushed to the master branch:

### CSS Files
- `modern-styles.css` → `/wordweb/css/modern-styles.css`
- `wordweb-essential.css` → `/wordweb/css/wordweb-essential.css`

### JavaScript Files
- `ordering.js` → `/wordweb/js/ordering.js`

## Setup Instructions

### 1. Configure CDN Credentials

1. Copy the template file:
   ```bash
   cp webhook-cdn-config.php.template webhook-cdn-config.php
   ```

2. Edit `webhook-cdn-config.php` and add your actual credentials:
   ```php
   // IBM Cloud Object Storage API Key
   define('COS_API_KEY_ID', 'your-actual-api-key-here');

   // CDN77 API Key
   define('CDN77_API_KEY', 'your-actual-cdn77-api-key-here');
   ```

3. **Important**: Never commit `webhook-cdn-config.php` to the repository for security.

### 2. IBM Cloud Object Storage Setup

1. **Create API Key:**
   - Go to IBM Cloud Console > Manage > Access (IAM) > API keys
   - Create a new API key with Cloud Object Storage access
   - Copy the API key to `webhook-cdn-config.php`

2. **Bucket Configuration:**
   - Bucket name: `wordwebsoftware-cdn`
   - Region: `eu-gb` (UK South)
   - Endpoint: `https://s3.eu-gb.cloud-object-storage.appdomain.cloud`

### 3. CDN77 Setup

1. **Get API Key:**
   - Go to CDN77 Dashboard > Account > API
   - Generate a new API key
   - Copy the API key to `webhook-cdn-config.php`

2. **Repository Configuration:**
   - Repository ID: `1782728235` (uk.wordwebsoftware.com)
   - Origin: IBM Cloud Object Storage bucket

### 4. Webhook Configuration

The webhook is already configured to:
- Only upload files when pushing to the `master` branch
- Upload files to the `/wordweb/` directory structure
- Purge and prefetch CDN cache after uploads
- Log all activities for monitoring

## File Structure

```
Repository Root/
├── webhook.php                 # Main webhook handler
├── webhook-config.php          # Public configuration
├── webhook-cdn-config.php      # Private credentials (not in repo)
├── modern-styles.css           # → /wordweb/css/modern-styles.css
├── wordweb-essential.css       # → /wordweb/css/wordweb-essential.css
└── ordering.js                 # → /wordweb/js/ordering.js
```

## CDN URLs

Once uploaded, files are available at:
- CSS: `https://uk.wordwebsoftware.com/wordweb/css/{filename}`
- JS: `https://uk.wordwebsoftware.com/wordweb/js/{filename}`

## File Minification

The system automatically minifies CSS and JS files before uploading to the CDN using the professional `matthiasmullie/minify` library:

### CSS Minification
- Removes all comments and unnecessary whitespace
- Optimizes CSS syntax and structure
- Combines and optimizes selectors where possible
- Removes redundant rules and properties
- Preserves functionality while maximizing compression

### JavaScript Minification
- Removes comments and unnecessary whitespace
- Optimizes variable names and function declarations
- Combines statements where safe
- Preserves string literals and code functionality
- Uses advanced parsing to ensure safe minification

### Technical Details
- **Library**: Uses `matthiasmullie/minify` (https://github.com/matthiasmullie/minify)
- **Safety**: Professional-grade parser ensures code functionality is preserved
- **Error Handling**: Falls back to original files if minification fails
- **Logging**: Detailed statistics show compression savings

### Benefits
- **Faster Loading**: Smaller files download faster
- **Bandwidth Savings**: Reduced data transfer costs
- **Better Performance**: Improved page load times
- **Source Preservation**: Original files remain unchanged in repository
- **Reliability**: Battle-tested minification library used by thousands of projects

## Monitoring

### Log Files
- Webhook activities are logged to `logs/webhook-wordweb-{branch}.log`
- CDN upload activities include detailed success/failure information
- Minification savings are logged showing original vs. minified file sizes
- Log files are automatically rotated when they exceed 1MB

### Log Levels
- **INFO**: Successful operations (includes minification statistics)
- **WARNING**: Non-critical issues (e.g., CDN upload disabled)
- **ERROR**: Failed operations that need attention
- **DEBUG**: Detailed command execution information

## Troubleshooting

### Common Issues

1. **CDN Upload Disabled**
   - Check that `ENABLE_CDN_UPLOAD` is set to `true` in `webhook-config.php`
   - Verify you're pushing to the `master` branch

2. **Missing Credentials**
   - Ensure `webhook-cdn-config.php` exists and contains valid API keys
   - Check file permissions (should be readable by web server)

3. **IBM Cloud Authentication Errors**
   - Verify the API key has Cloud Object Storage access
   - Check that the bucket name and endpoint are correct

4. **CDN77 API Errors**
   - Verify the API key is valid and has repository access
   - Check that the repository ID is correct

### Manual Testing

To test CDN upload functionality:

1. Check webhook logs for any errors
2. Verify files exist in IBM Cloud Object Storage bucket
3. Test CDN URLs in browser
4. Check CDN77 dashboard for cache purge/prefetch jobs

## Security Notes

- Never commit `webhook-cdn-config.php` to the repository
- API keys should have minimal required permissions
- Consider using environment variables for production deployments
- Regularly rotate API keys for security

## Adding New Files

To add new files to CDN upload:

1. Edit `webhook-config.php`
2. Add files to the `$cdn_upload_files` array:
   ```php
   $cdn_upload_files = [
       'css' => [
           'modern-styles.css',
           'wordweb-essential.css',
           'new-styles.css'  // Add new CSS file
       ],
       'js' => [
           'ordering.js',
           'new-script.js'   // Add new JS file
       ]
   ];
   ```

Files will be automatically uploaded on the next push to master branch.
