# StyleScore Publish Server Setup Guide

## Overview
The StyleScore Publish Server system allows you to automatically publish live scoring data to remote FTP servers. This enables real-time updates to external websites, scoreboards, and data feeds.

## Features
- Multiple FTP server support per event
- Automatic publishing at configurable intervals
- Multiple data formats (HTML Dashboard, JSON, PDF, CSV)
- Background daemon for continuous operation
- Manual publishing with immediate updates
- Connection testing and validation
- Comprehensive logging and monitoring

## Installation Steps

### 1. Database Setup
First, run the SQL setup script to create the required tables:

```sql
-- Run this in your MySQL/MariaDB database
-- File: admin/setup_publish_servers.sql
```

You can execute this either:
- Through phpMyAdmin by importing the SQL file
- Through command line: `mysql -u username -p database_name < admin/setup_publish_servers.sql`
- Through the web interface at `admin/setup_database.php` (if available)

### 2. Configure PHP Requirements
Ensure your PHP installation has the following extensions:
- `ftp` - For FTP connections
- `json` - For JSON data handling
- `zip` - For file compression (optional)
- `pcntl` - For daemon signal handling (Linux/Unix only)

### 3. Set Directory Permissions
Create and set proper permissions for log directories:

**Windows:**
```cmd
mkdir admin\logs
icacls admin\logs /grant Users:F
```

**Linux/Unix:**
```bash
mkdir -p admin/logs
chmod 755 admin/logs
chown www-data:www-data admin/logs
```

## Configuration

### 1. Access the Admin Interface
Navigate to: `http://yoursite.com/admin/publish_servers.php`

### 2. Add Your First Publish Server
1. Click "Add New Server"
2. Fill in the FTP connection details:
   - **Name**: Descriptive name for the server
   - **Host**: FTP server hostname or IP
   - **Port**: FTP port (usually 21)
   - **Username**: FTP username
   - **Password**: FTP password
   - **Remote Path**: Directory path on FTP server
   - **Event**: Select the event to publish
   - **Data Types**: Choose what to publish (HTML, JSON, PDF, CSV)
   - **Update Interval**: How often to update (in seconds)

3. Click "Test Connection" to verify FTP settings
4. Save the server configuration

### 3. Configure Data Types

#### HTML Dashboard
- Creates a complete HTML dashboard similar to your local public dashboard
- Includes CSS, JavaScript, and all styling
- Files generated: `index.html`, `assets/style.css`, `assets/script.js`

#### JSON Data
- Exports live scoring data in JSON format
- Useful for API integration
- Files generated: `data.json`, `scores.json`, `participants.json`

#### PDF Results
- Generates formatted PDF result sheets
- Professional presentation format
- Files generated: `results.pdf`, `heat_results.pdf`

#### CSV Data
- Exports data in CSV format for spreadsheet applications
- Multiple files for different data types
- Files generated: `scores.csv`, `participants.csv`, `results.csv`

## Running the Publish System

### Option 1: Manual Publishing
1. Go to `admin/publish_servers.php`
2. Find your server in the list
3. Click "Publish Now" to immediately publish current data

### Option 2: Automatic Publishing (Daemon)

#### Windows
Use the provided batch script:
```cmd
# Navigate to admin directory
cd admin

# Start the daemon
daemon.bat start

# Check status
daemon.bat status

# View logs
daemon.bat logs

# Stop daemon
daemon.bat stop
```

#### Linux/Unix
Use the PHP script directly:
```bash
# Start daemon (runs continuously)
php publish_daemon.php start

# Test publishing
php publish_daemon.php test

# Check status
php publish_daemon.php status

# Run in background
nohup php publish_daemon.php start > /dev/null 2>&1 &
```

### Option 3: Cron Job (Linux/Unix)
Add to crontab for periodic checks:
```bash
# Edit crontab
crontab -e

# Add this line to check every minute
* * * * * /usr/bin/php /path/to/admin/publish_daemon.php start
```

## Monitoring and Troubleshooting

### 1. Check Server Status
- Go to `admin/publish_servers.php`
- View the "Last Published" column
- Check success/error counts
- Review recent log entries

### 2. Log Files
The system creates several log files:
- `admin/logs/daemon.log` - Daemon startup/shutdown logs
- `admin/logs/publish_daemon.log` - Publishing activity logs
- Database `publish_logs` table - Detailed publish history

### 3. Common Issues

#### Connection Failed
- Verify FTP credentials
- Check firewall settings
- Ensure FTP server supports passive mode
- Test with FTP client software

#### Files Not Uploading
- Check remote directory permissions
- Verify available disk space
- Review FTP server logs
- Test with smaller files first

#### Daemon Not Running
- Check PHP CLI is available
- Verify script permissions
- Review error logs
- Ensure no port conflicts

### 4. Testing Checklist
1. ✅ FTP connection test passes
2. ✅ Manual publish works
3. ✅ Files appear on remote server
4. ✅ Data is current and accurate
5. ✅ Automatic updates are working
6. ✅ Logs show successful publishes

## Security Considerations

### 1. FTP Credentials
- Use strong passwords
- Consider SFTP if available
- Limit FTP user permissions
- Regular password rotation

### 2. File Permissions
- Restrict access to admin directory
- Secure log files
- Protect configuration files
- Use HTTPS for admin interface

### 3. Server Access
- Whitelist IP addresses if possible
- Monitor connection logs
- Set up alerts for failures
- Regular security updates

## Advanced Configuration

### 1. Custom Data Formats
You can extend the system by adding new generators in `publish_generators.php`:

```php
function generateCustomFormat($event_id, $temp_dir, $pdo) {
    // Your custom generation logic here
    return [
        ['local' => $temp_dir . '/custom.xml', 'remote' => 'custom.xml']
    ];
}
```

### 2. Multiple Remote Paths
Set up different servers for different purposes:
- Production website: `/public_html/scores/`
- Backup server: `/backup/scores/`
- Mobile app API: `/api/v1/`

### 3. Conditional Publishing
Modify the daemon to publish only when scores change:
- Track data checksums
- Compare with previous publish
- Skip if no changes detected

## Performance Optimization

### 1. Reduce Data Size
- Compress files before upload
- Send only changed data
- Use incremental updates
- Optimize image sizes

### 2. Connection Efficiency
- Reuse FTP connections
- Batch file uploads
- Use compression if supported
- Parallel uploads for multiple servers

### 3. System Resources
- Monitor CPU and memory usage
- Adjust update intervals based on load
- Use efficient database queries
- Clean old log entries regularly

## Support and Maintenance

### 1. Regular Tasks
- Review publish logs weekly
- Test FTP connections monthly
- Update credentials as needed
- Monitor disk space usage

### 2. Backup Strategy
- Backup publish server configurations
- Export log data regularly
- Test restore procedures
- Document server setups

### 3. Updates and Changes
- Test changes on staging first
- Backup before modifications
- Update documentation
- Notify users of changes

## Troubleshooting Commands

### Windows
```cmd
# Check if PHP is working
php --version

# Test FTP connection manually
# Use Windows FTP client or FileZilla

# Check running processes
tasklist | findstr php

# View recent files
dir admin\logs /od
```

### Linux/Unix
```bash
# Check PHP FTP extension
php -m | grep ftp

# Test FTP connection
ftp your-server.com

# Check running daemon
ps aux | grep publish_daemon

# Monitor logs in real-time
tail -f admin/logs/publish_daemon.log
```

## Example Configurations

### Basic Website Publishing
- **Data Types**: HTML Dashboard
- **Update Interval**: 30 seconds
- **Remote Path**: `/public_html/live/`
- **Use Case**: Live scoring website

### API Data Feed
- **Data Types**: JSON Data
- **Update Interval**: 10 seconds
- **Remote Path**: `/api/v1/scores/`
- **Use Case**: Mobile app backend

### Results Archive
- **Data Types**: PDF Results, CSV Data
- **Update Interval**: 300 seconds (5 minutes)
- **Remote Path**: `/results/archive/`
- **Use Case**: Historical results storage

---

For additional support or custom configurations, please refer to the StyleScore documentation or contact your system administrator.
