# How To Malaysia CMS - Configuration Management System

This document outlines the comprehensive configuration management system implemented to avoid hard-coding values and make maintenance easier.

## 🎯 Features Implemented

### 1. Centralized Configuration Management
- **Environment-aware settings** (development, testing, production)
- **Database-driven site settings** with admin interface
- **Type-safe configuration** (text, number, boolean, JSON)
- **Default fallback values** for all settings

### 5. Email Notification System
- **SMTP configuration** with multiple providers support
- **Automatic notifications** for comments, articles, user registration
- **System error alerts** to administrators
- **Weekly summary reports** with analytics
- **Customizable templates** and recipients

### 2. Database Connection Management
- **Singleton pattern** for consistent connections
- **Environment-specific** database credentials
- **Connection pooling** and error handling
- **Helper functions** for common database operations

### 3. Settings Administration Interface
- **Comprehensive admin panel** for all site settings
- **Live preview** of changes
- **Organized sections** (General, Content, SEO, Social, etc.)
- **Validation** and type checking
- **Export/Import** functionality (planned)

### 4. Helper Functions
- **Easy access** to settings via `getSetting()` and `setSetting()`
- **Formatting helpers** for currency, dates, etc.
- **Feature toggles** with `isFeatureEnabled()`
- **Upload limits** and file type restrictions

## 📁 File Structure

```
config/
├── Config.php          # Main configuration class
├── DB.php             # Database connection helper
├── database.php       # Database connection settings
├── environment.php    # Environment detection and settings
└── helpers.php        # Global helper functions

admin_bootstrap.php    # Common admin initialization
admin_settings_new.php # Enhanced settings management
setup_config.php      # Migration script for setup
```

## 🚀 Quick Start

### 1. Initial Setup
Run the setup script to create the configuration tables:

```bash
php setup_config.php
```

### 2. Using Configuration in Your Code

```php
// Load configuration system
require_once __DIR__ . '/admin_bootstrap.php';

// Get settings
$siteName = getSetting('site.site_name', 'Default Name');
$articlesPerPage = getArticlesPerPage();
$isCommentsEnabled = isFeatureEnabled('comments');

// Set settings
setSetting('site.maintenance_mode', true);

// Database operations
$articles = DB::fetchAll("SELECT * FROM articles WHERE status = ?", ['published']);
$article = DB::fetchOne("SELECT * FROM articles WHERE id = ?", [1]);
```

### 3. Environment Configuration

The system automatically detects environments:
- **Development**: localhost, xampp, .local domains
- **Testing**: staging, test subdomains
- **Production**: Everything else

Override with environment variable:
```bash
export ENVIRONMENT=development
```

## ⚙️ Configuration Categories

### General Settings
- Site name, tagline, description
- Contact and admin emails
- Timezone and localization

### Content Settings
- Articles per page
- Upload limits and file types
- Comments and ratings toggles

### SEO & Analytics
- Google Analytics ID
- Meta descriptions
- Social media URLs

### System Settings
- Maintenance mode
- User registration
- Debug settings
- Caching options

### Email & Notification Settings
- SMTP server configuration
- Notification preferences (comments, articles, errors)
- Additional email recipients
- Email templates and signatures

## 🔧 Advanced Usage

### Custom Settings
Add new settings through the admin interface or programmatically:

```php
// Add a new setting
setSetting('site.custom_feature_enabled', true);
setSetting('site.api_key', 'your-api-key');
setSetting('site.advanced_config', ['key1' => 'value1', 'key2' => 'value2']);
```

### Environment-Specific Overrides
Modify `config/environment.php` to set environment-specific values:

```php
'production' => [
    'database' => [
        'host' => getenv('DB_HOST') ?: 'production-server',
        'username' => getenv('DB_USER') ?: 'prod_user',
        'password' => getenv('DB_PASS') ?: 'secure_password',
    ],
    'mail' => [
        'driver' => 'smtp',
        'host' => 'smtp.gmail.com',
        // ... other mail settings
    ]
]
```

### Type Safety
Settings are automatically cast to appropriate types:

```php
// These will be properly typed
$articlesPerPage = getSetting('site.articles_per_page'); // Returns integer
$commentsEnabled = getSetting('site.enable_comments');  // Returns boolean
$socialUrls = getSetting('site.social_urls');           // Returns array if JSON
```

## 🛠️ Migration from Hard-coded Values

### Before (Hard-coded)
```php
// Old way - hard-coded values
$host = 'localhost';
$dbname = 'howtomalaysia';
$username = 'root';
$password = '';
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

$articlesPerPage = 12; // Hard-coded
$siteName = "How To Malaysia"; // Hard-coded
```

### After (Configurable)
```php
// New way - configurable
require_once __DIR__ . '/admin_bootstrap.php';

$pdo = getDB(); // Automatically configured
$articlesPerPage = getArticlesPerPage(); // From settings
$siteName = getSetting('site.site_name'); // From settings
```

## 📊 Benefits Achieved

1. **No Hard-coding**: All values are configurable through admin interface
2. **Environment Awareness**: Different settings for dev/test/production
3. **Type Safety**: Proper casting and validation of setting values
4. **Easy Maintenance**: Change settings without code modifications
5. **Consistent Access**: Standardized way to access configuration
6. **Database Optimization**: Singleton pattern prevents multiple connections
7. **Error Handling**: Graceful fallbacks and error logging
8. **Future-Proof**: Easy to add new settings and features
9. **Email Notifications**: Automated notifications for admin activities
10. **SMTP Integration**: Professional email delivery with multiple provider support

## 📧 Email Notification System

### Configuration
Configure email settings in the admin panel:
- **SMTP Settings**: Host, port, username, password, encryption
- **From Address**: Sender name and email address
- **Notification Types**: Toggle individual notification types
- **Recipients**: Admin email plus additional notification addresses

### Available Notifications
```php
// Automatic notifications
notifyNewComment($comment, $article);     // New comment posted
notifyNewArticle($article);               // Article published
notifyUserRegistration($user);            // New user registered
logEvent("Error message", 'error');       // System errors (automatic)

// Manual notifications
sendTestEmail('admin@example.com');       // Test email configuration
sendWeeklySummary();                      // Weekly analytics summary
```

### Email Templates
All emails include:
- Professional HTML formatting
- Site branding and contact information
- Configurable email signature
- Direct links to admin actions

## 🔍 Testing the System

1. **Admin Interface**: Visit `admin_settings_new.php` to modify settings
2. **Dashboard**: Check `admin_dashboard_new.php` for environment info
3. **Database**: Settings are stored in `site_settings` table
4. **Environment**: Check current environment in admin footer

## 🚦 Best Practices

1. **Always use helpers**: Use `getSetting()` instead of direct database queries
2. **Provide defaults**: Always specify default values in `getSetting()`
3. **Type checking**: Use appropriate setting types (boolean, number, etc.)
4. **Environment variables**: Use environment variables for sensitive data
5. **Documentation**: Document new settings in the admin interface
6. **Validation**: Validate user input in the settings form
7. **Caching**: Settings are automatically cached per request

## 🔄 Future Enhancements

- [ ] Settings import/export functionality
- [ ] Settings backup and restore
- [ ] Advanced validation rules
- [ ] Settings history and rollback
- [ ] Multi-language settings support
- [ ] API endpoint for settings management
- [ ] Settings templates for quick setup

This configuration system provides a solid foundation for maintaining and scaling the How To Malaysia CMS without the need for hard-coded values or complex manual updates.