# EasyStream Settings System - Complete Guide

**Configure your entire platform through the admin panel - no code changes required!**

---

## Table of Contents

1. [Quick Installation](#quick-installation)
2. [Accessing Settings](#accessing-settings)
3. [Settings Categories](#settings-categories)
4. [Usage Examples](#usage-examples)
5. [Settings Reference](#settings-reference)
6. [Advanced Features](#advanced-features)
7. [Troubleshooting](#troubleshooting)

---

## Quick Installation

### Step 1: Run the SQL Migration

**Using Docker:**
```bash
docker exec -i easystream-db mysql -u easystream -peasystream easystream < __install/install_settings_system.sql
```

**Using MySQL directly:**
```bash
mysql -u easystream -p easystream < __install/install_settings_system.sql
```

### Step 2: Access the Settings Panel

1. Log in to admin panel: `http://yoursite.com/admin_login.php`
2. Navigate to **Settings** in the sidebar
3. Or go directly to: `http://yoursite.com/admin_settings.php`

### Step 3: Start Configuring

Choose from 8 comprehensive categories and configure your platform without touching any code!

---

## Accessing Settings

### Admin Panel UI

The settings panel provides a beautiful, organized interface with:

- **8 Tabbed Categories** - General, Modules, Branding, Payments, Email, Payouts, SEO, Security
- **Live Search** - Press `Ctrl+K` (or `Cmd+K` on Mac) to instantly search settings
- **Category Filtering** - Filter by category to focus on specific configuration areas
- **Visual Feedback** - Color-coded inputs, helpful descriptions, validation messages
- **Bulk Save** - Save multiple settings at once with a single click

### Search & Filter Features

- **Keyboard Shortcuts:**
  - `Ctrl+K` or `Cmd+K` - Focus search box
  - `Escape` - Clear search

- **Search Capabilities:**
  - Search by setting name
  - Search by label text
  - Search by help text
  - Real-time highlighting of matches
  - Result count display

---

## Settings Categories

### 1. General Settings
Configure your site's basic identity and system settings.

**Key Settings:**
- Site name and title
- Admin email address
- Main website URL
- Debug mode toggle
- Maintenance mode

**Example:**
```php
$settings = new Settings($pdo);
$settings->set('website_shortname', 'MyTube');
$settings->set('head_title', 'MyTube - Video Sharing Platform');
```

---

### 2. Modules Management
Enable or disable platform features with visual toggle switches.

**Available Modules:**
- Video uploads
- Live streaming
- Shorts (TikTok-style)
- Images
- Audio
- Documents
- Blogs
- Paid memberships
- Token economy

**Example:**
```php
$settings = new Settings($pdo);

// Disable blogs and documents
$settings->setModuleEnabled('blog', false);
$settings->setModuleEnabled('document', false);

// Check if a module is enabled
if ($settings->isModuleEnabled('video')) {
    // Show video upload interface
}
```

---

### 3. Branding & Appearance
Customize your platform's look and feel.

**Customizable Elements:**
- Primary color (buttons, links, accents)
- Secondary color (highlights, hover states)
- Logo URL
- Favicon URL
- Custom footer text

**Example:**
```php
$settings = new Settings($pdo);
$settings->setMultiple([
    'branding_primary_color' => '#FF0000',
    'branding_secondary_color' => '#282828',
    'branding_logo_url' => 'https://mysite.com/logo.png',
    'branding_favicon_url' => 'https://mysite.com/favicon.ico'
]);
```

**Live Color Picker:** The admin UI includes a built-in color picker for instant visual feedback.

---

### 4. Payment Gateways
Configure PayPal and Stripe for payments.

**PayPal Settings:**
- PayPal email
- Client ID
- Secret key
- Test mode toggle

**Stripe Settings:**
- Publishable key
- Secret key
- Webhook secret
- Enable/disable toggle

**Example:**
```php
$settings = new Settings($pdo);

// Enable Stripe payments
$settings->setMultiple([
    'stripe_enabled' => '1',
    'stripe_publishable_key' => 'pk_live_xxxxx',
    'stripe_secret_key' => 'sk_live_xxxxx',
    'stripe_webhook_secret' => 'whsec_xxxxx',
    'payment_methods' => 'Paypal,Stripe'
]);

// Access payment config in your code
$paymentConfig = $settings->getPaymentConfig();
if ($paymentConfig['stripe']['enabled']) {
    // Initialize Stripe SDK
    \Stripe\Stripe::setApiKey($paymentConfig['stripe']['secret_key']);
}
```

---

### 5. Email Configuration
Set up SMTP for transactional emails.

**SMTP Settings:**
- Host (e.g., smtp.gmail.com)
- Port (587 for TLS, 465 for SSL)
- Username
- Password
- Encryption type (TLS/SSL)
- Authentication enabled

**Example:**
```php
$settings = new Settings($pdo);

// Configure SendGrid SMTP
$settings->setMultiple([
    'mail_type' => 'smtp',
    'mail_smtp_host' => 'smtp.sendgrid.net',
    'mail_smtp_port' => '587',
    'mail_smtp_username' => 'apikey',
    'mail_smtp_password' => 'your-sendgrid-api-key',
    'mail_smtp_auth' => 'true',
    'mail_smtp_prefix' => 'tls',
    'backend_email' => 'noreply@mysite.com',
    'backend_email_fromname' => 'MyTube Team'
]);

// Access email config
$emailConfig = $settings->getEmailConfig();
```

---

### 6. Creator Payouts
Configure revenue sharing with content creators.

**Payout Settings:**
- Enable/disable payout system
- Revenue share percentage (0-100%)
- Minimum payout amount
- Payout schedule (weekly, monthly, quarterly, manual)
- Default payout method (PayPal, Stripe, bank transfer)

**Example:**
```php
$settings = new Settings($pdo);

// Enable creator payouts with 80% revenue share
$settings->setMultiple([
    'creator_payout_enabled' => '1',
    'creator_payout_percentage' => '80',
    'minimum_payout_amount' => '100.00',
    'payout_schedule' => 'monthly',
    'payout_method' => 'paypal'
]);
```

---

### 7. SEO & Marketing
Optimize your site for search engines.

**SEO Settings:**
- Meta description
- Meta keywords
- Site title optimization

**Example:**
```php
$settings = new Settings($pdo);
$settings->setMultiple([
    'head_title' => 'MyTube - Best Video Sharing Platform',
    'metaname_description' => 'Upload, share, and watch videos on MyTube. Join millions of creators.',
    'metaname_keywords' => 'video sharing, streaming, upload videos, watch videos'
]);
```

---

### 8. Security Settings
Configure user registration and authentication requirements.

**Security Controls:**
- Minimum/maximum age for signup
- Username length requirements
- Password length requirements
- Username format (strict/relaxed)
- Remember me feature

**Example:**
```php
$settings = new Settings($pdo);
$settings->setMultiple([
    'signup_min_age' => '13',
    'signup_max_age' => '120',
    'signup_min_username' => '3',
    'signup_max_username' => '20',
    'signup_min_password' => '8',
    'signup_max_password' => '50',
    'username_format' => 'relaxed'
]);
```

---

## Usage Examples

### Method 1: Using the Settings Class (Recommended)

```php
<?php
require_once 'f_core/f_classes/class.settings.php';

// Initialize
$settings = new Settings($pdo);

// Get a single setting
$siteName = $settings->get('website_shortname', 'EasyStream');

// Set a single setting
$settings->set('website_shortname', 'My Awesome Site');

// Get multiple settings at once
$emailConfig = $settings->getEmailConfig();
$paymentConfig = $settings->getPaymentConfig();

// Set multiple settings at once (bulk operation)
$settings->setMultiple([
    'website_shortname' => 'My Site',
    'head_title' => 'My Site - Video Platform',
    'branding_primary_color' => '#FF0000'
]);

// Get all settings in a category
$brandingSettings = $settings->getByPrefix('branding_');

// Check if a module is enabled
if ($settings->isModuleEnabled('video')) {
    // Show video upload interface
}

// Set module status
$settings->setModuleEnabled('blog', false);
```

### Method 2: Using Data Providers (Admin Panel)

```php
<?php
require_once 'admin/includes/data_providers.php';

// Get a single setting
$siteName = admin_get_setting($pdo, 'website_shortname');

// Save a setting
admin_save_setting($pdo, 'website_shortname', 'New Site Name');

// Save multiple settings
admin_save_multiple_settings($pdo, [
    'website_shortname' => 'New Site',
    'head_title' => 'New Title'
]);

// Get module status
$modules = admin_fetch_module_status($pdo);

// Toggle a module
admin_toggle_module($pdo, 'video_module', true);
```

### Method 3: Legacy Database Class

```php
<?php
global $class_database;

// Load specific settings
$class_database->getConfigurations('website_shortname,head_title,backend_email');

// Access via $cfg array
global $cfg;
echo $cfg['website_shortname']; // Site name
```

---

## Settings Reference

### Complete Settings List

| Category | Setting Name | Description | Type | Default |
|----------|--------------|-------------|------|---------|
| **General** | `website_shortname` | Short site name | text | EasyStream |
| | `head_title` | Browser tab title | text | EasyStream |
| | `backend_email` | Admin email | email | admin@example.com |
| | `main_url` | Main website URL | url | http://localhost:8083 |
| | `debug_mode` | Enable debug mode | boolean | 0 |
| **Modules** | `video_module` | Enable videos | boolean | 1 |
| | `live_module` | Enable live streaming | boolean | 1 |
| | `short_module` | Enable shorts | boolean | 1 |
| | `image_module` | Enable images | boolean | 1 |
| | `audio_module` | Enable audio | boolean | 1 |
| | `document_module` | Enable documents | boolean | 1 |
| | `blog_module` | Enable blogs | boolean | 1 |
| | `paid_memberships` | Enable memberships | boolean | 0 |
| | `token_system_enabled` | Enable tokens | boolean | 1 |
| **Branding** | `branding_primary_color` | Primary UI color | color | #1a73e8 |
| | `branding_secondary_color` | Secondary UI color | color | #34a853 |
| | `branding_logo_url` | Logo URL | url | (empty) |
| | `branding_favicon_url` | Favicon URL | url | (empty) |
| | `branding_footer_text` | Custom footer | text | (empty) |
| **Payments** | `paypal_email` | PayPal email | email | (empty) |
| | `paypal_test` | PayPal test mode | boolean | 1 |
| | `paypal_client_id` | PayPal client ID | text | (empty) |
| | `paypal_secret` | PayPal secret (encrypted) | password | (empty) |
| | `stripe_enabled` | Enable Stripe | boolean | 0 |
| | `stripe_publishable_key` | Stripe public key | text | (empty) |
| | `stripe_secret_key` | Stripe secret (encrypted) | password | (empty) |
| | `stripe_webhook_secret` | Webhook secret (encrypted) | password | (empty) |
| **Email** | `mail_type` | Mailer type | select | smtp |
| | `mail_smtp_host` | SMTP hostname | text | smtp.gmail.com |
| | `mail_smtp_port` | SMTP port | number | 587 |
| | `mail_smtp_username` | SMTP username | text | (empty) |
| | `mail_smtp_password` | SMTP password (encrypted) | password | (empty) |
| | `mail_smtp_auth` | SMTP authentication | boolean | true |
| | `mail_smtp_prefix` | Encryption type | select | tls |
| **Payouts** | `creator_payout_enabled` | Enable payouts | boolean | 0 |
| | `creator_payout_percentage` | Revenue share % | number | 70 |
| | `minimum_payout_amount` | Minimum payout | decimal | 50.00 |
| | `payout_schedule` | Payout frequency | select | monthly |
| | `payout_method` | Default method | select | paypal |
| **SEO** | `metaname_description` | Meta description | textarea | (empty) |
| | `metaname_keywords` | Meta keywords | textarea | (empty) |
| **Security** | `signup_min_age` | Minimum age | number | 18 |
| | `signup_max_age` | Maximum age | number | 70 |
| | `signup_min_username` | Min username length | number | 5 |
| | `signup_max_username` | Max username length | number | 15 |
| | `signup_min_password` | Min password length | number | 5 |
| | `signup_max_password` | Max password length | number | 15 |
| | `username_format` | Username format | select | strict |
| | `login_remember` | Enable remember me | boolean | 1 |

---

## Advanced Features

### 1. Redis Caching (10-100x Faster)

The Settings class automatically uses Redis when available:

```php
$settings = new Settings($pdo);

// First call - queries database
$siteName = $settings->get('website_shortname');

// Subsequent calls - served from Redis cache (milliseconds instead of seconds)
$siteName = $settings->get('website_shortname');

// Cache is automatically cleared when settings are updated
$settings->set('website_shortname', 'New Name'); // Invalidates cache
```

**Cache Details:**
- TTL: 1 hour (3600 seconds)
- Automatic invalidation on updates
- Uses existing `VRedis` singleton
- Falls back to database if Redis unavailable

---

### 2. Input Validation

All settings are validated before being saved:

```php
$settings = new Settings($pdo);

try {
    // Valid email required
    $settings->set('backend_email', 'admin@example.com'); // ✅ Valid

    // Invalid email throws exception
    $settings->set('backend_email', 'not-an-email'); // ❌ Throws exception

    // Port must be 1-65535
    $settings->set('mail_smtp_port', 587); // ✅ Valid
    $settings->set('mail_smtp_port', 99999); // ❌ Throws exception

    // Colors must be valid hex
    $settings->set('branding_primary_color', '#FF0000'); // ✅ Valid
    $settings->set('branding_primary_color', 'red'); // ❌ Throws exception

} catch (InvalidArgumentException $e) {
    echo "Validation error: " . $e->getMessage();
}
```

**Validation Rules:**
- `email` - Valid email format
- `url` - Valid URL format
- `color` - Valid hex color (#RRGGBB)
- `int` - Integer with optional min/max
- `float` - Decimal number with optional min/max
- `bool` - Boolean (0/1, true/false, yes/no)
- `string` - Text with optional min/max length

---

### 3. Encryption for Sensitive Data

Sensitive settings are automatically encrypted:

```php
$settings = new Settings($pdo);

// These are automatically encrypted in the database:
$settings->set('paypal_secret', 'secret_key_here');
$settings->set('stripe_secret_key', 'sk_live_xxxxx');
$settings->set('mail_smtp_password', 'smtp_password');
$settings->set('google_client_secret', 'oauth_secret');

// When you retrieve them, they're automatically decrypted:
$secret = $settings->get('paypal_secret'); // Returns decrypted value
```

**Encrypted Settings:**
- PayPal secret
- Stripe secret key
- Stripe webhook secret
- SMTP password
- Google client secret
- Facebook app secret
- Twitter API secret

**Encryption Method:** AES-256-CBC using keys from `config.define.php` (ENC_FIRSTKEY, ENC_SECONDKEY)

---

### 4. Audit Trail & Change History

Every settings change is tracked with complete audit trail:

```php
$settings = new Settings($pdo);

// Change a setting
$settings->set('website_shortname', 'New Site Name');

// View change history (last 20 changes)
$history = $settings->getHistory('website_shortname');
foreach ($history as $change) {
    echo "Changed on: " . $change['changed_at'] . "\n";
    echo "Changed by: User #" . $change['changed_by'] . "\n";
    echo "Old value: " . $change['old_value'] . "\n";
    echo "New value: " . $change['new_value'] . "\n";
    echo "IP address: " . $change['ip_address'] . "\n";
}

// Rollback to a previous value
$settings->rollback('website_shortname', $historyId);
```

**Tracked Information:**
- Setting name
- Old value
- New value
- User who made the change
- Timestamp
- IP address
- User agent
- Optional change reason

---

### 5. Bulk Operations

Efficiently update multiple settings at once:

```php
$settings = new Settings($pdo);

// Atomic transaction - all or nothing
$settings->setMultiple([
    'website_shortname' => 'MyTube',
    'head_title' => 'MyTube - Video Platform',
    'branding_primary_color' => '#FF0000',
    'branding_secondary_color' => '#282828',
    'backend_email' => 'admin@mytube.com'
]);

// If any setting fails validation, the entire operation is rolled back
```

---

### 6. Export & Import

Backup and restore your configuration:

```php
$settings = new Settings($pdo);

// Export all settings to JSON
$backup = $settings->exportJSON();
file_put_contents('settings_backup.json', $backup);

// Import settings from JSON
$json = file_get_contents('settings_backup.json');
$settings->importJSON($json);
```

**Use Cases:**
- Backup before major changes
- Duplicate configuration across environments
- Version control your settings
- Disaster recovery

---

## Troubleshooting

### Settings Not Saving

**Symptoms:** Changes don't persist after clicking Save

**Solutions:**
1. Check database connection in `f_core/config.database.php`
2. Verify PDO is initialized in `admin/includes/bootstrap.php`
3. Check error logs: `f_data/data_logs/log_error/`
4. Ensure `db_settings` table exists
5. Check file permissions on log directories

---

### Settings Not Loading

**Symptoms:** Settings page shows errors or empty values

**Solutions:**
1. Clear Redis cache (if using Redis)
2. Verify `db_settings` table exists
3. Run the installation script: `__install/install_settings_system.sql`
4. Check that settings were inserted: `SELECT COUNT(*) FROM db_settings;`
5. Review PHP error logs

---

### Validation Errors

**Symptoms:** "Invalid value" errors when saving

**Solutions:**
1. Check the error message for specific validation requirements
2. Ensure email addresses are properly formatted
3. Verify URLs include protocol (http:// or https://)
4. Check number ranges (e.g., SMTP port must be 1-65535)
5. Use hex color codes for color settings (#RRGGBB)

---

### PayPal/Stripe Not Working

**Symptoms:** Payments fail or aren't processed

**Solutions:**
1. Verify API keys are correct (check for spaces/typos)
2. Ensure test mode is disabled for production
3. Check webhook URLs are configured in payment gateway dashboard
4. Review payment gateway API documentation
5. Test API keys using gateway's test tools
6. Check error logs for detailed error messages

---

### Email Not Sending

**Symptoms:** No emails received from the platform

**Solutions:**
1. Test SMTP connection manually
2. Verify SMTP credentials are correct
3. Check firewall allows outbound connections on port 587 (TLS) or 465 (SSL)
4. Try a different SMTP provider (SendGrid, Mailgun, etc.)
5. Review email logs in `f_data/data_logs/`
6. Test with a simple mail client first
7. Check spam/junk folders

---

### Search Not Working

**Symptoms:** Settings search doesn't filter results

**Solutions:**
1. Clear browser cache
2. Check JavaScript console for errors (F12)
3. Ensure `admin/includes/settings_search.php` is included
4. Verify settings have `data-setting-*` attributes
5. Try a different browser

---

## Security Best Practices

### 1. Protect Sensitive Settings

```php
// ✅ Good - Use environment variables for production secrets
$settings->set('stripe_secret_key', getenv('STRIPE_SECRET_KEY'));

// ❌ Bad - Don't hardcode secrets
$settings->set('stripe_secret_key', 'sk_live_abc123');
```

### 2. Regular Backups

```php
// Backup before major changes
$backup = $settings->exportJSON();
file_put_contents("backup_" . date('Y-m-d') . ".json", $backup);
```

### 3. Access Control

- Settings page requires admin authentication
- Regular users cannot access `/admin_settings.php`
- Use role-based access control (RBAC)

### 4. Audit Review

Regularly review change history:
```php
$history = $settings->getHistory('stripe_secret_key', 50);
// Review who changed sensitive settings and when
```

---

## File Reference

### Core Files
- [admin_settings.php](admin_settings.php) - Main settings UI
- [f_core/f_classes/class.settings.php](f_core/f_classes/class.settings.php) - Settings management class
- [admin/includes/data_providers.php](admin/includes/data_providers.php) - Settings data providers (lines 759-1041)
- [admin/includes/settings_search.php](admin/includes/settings_search.php) - Search & filter UI component
- [admin/includes/layout.php](admin/includes/layout.php) - Shared UI with sidebar navigation
- [__install/install_settings_system.sql](__install/install_settings_system.sql) - Complete installation script

---

## License

This settings system is part of EasyStream and subject to the EasyStream Proprietary License Agreement.

Copyright (c) 2025 Sami Ahmed. All rights reserved.
