# 🔧 Dynamic Configuration - How It Works

**Last Updated:** February 10, 2026  
**Status:** ✅ Fully Implemented

---

## 📋 Overview

The chatbot application now automatically generates a **production-ready** `config.php` file during installation with all critical fixes and error logging pre-configured.

---

## 🔄 Installation Flow

### 1. **Pre-Installation State**
- No `config.php` exists
- User visits `install.php` or `install1.php`
- Installation wizard starts

### 2. **Installation Process**
The installation wizard:
1. **Detects environment** (XAMPP, cPanel, localhost, production)
2. **Tests database connection** with provided credentials
3. **Creates database tables** (users, conversations, messages, settings, etc.)
4. **Generates config.php** dynamically with:
   - Database credentials
   - Application URL
   - Error logging configuration
   - All app integrations pre-enabled
5. **Creates logs directory** automatically
6. **Returns success** and redirects to admin panel

### 3. **Post-Installation State**
- `config.php` exists with full configuration
- `logs/` directory created and writable
- Error logging active (configurable via `SB_DEBUG`)
- Database connection fixes automatically applied

---

## 📝 What Gets Generated Automatically

### Config.php Template (from install.php lines 85-145)

```php
<?php
/* Plugin folder url - Production URL */
define('SB_URL', 'https://yoursite.com/chat');

/* Database Configuration */
define('SB_DB_NAME', 'your_database');
define('SB_DB_USER', 'your_username');
define('SB_DB_PASSWORD', 'your_password');
define('SB_DB_HOST', 'localhost');
define('SB_DB_PORT', '3306');

/* Cross domain */
define('SB_CROSS_DOMAIN', false);

/* Apps - Pre-enabled */
define('SB_DIALOGFLOW', '1.0.0');
define('SB_WHATSAPP', '1.0.0');
// ... all integrations enabled ...

/* Error Logging Configuration - AUTO-GENERATED */
if (!defined('SB_DEBUG')) {
    define('SB_DEBUG', true);
}

if (SB_DEBUG) {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    
    $log_dir = __DIR__ . '/logs';
    if (!is_dir($log_dir)) {
        @mkdir($log_dir, 0755, true);
    }
    
    ini_set('error_log', $log_dir . '/error.log');
    error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
} else {
    ini_set('display_errors', 0);
    ini_set('log_errors', 0);
    error_reporting(0);
}
?>
```

---

## 🛠️ Modified Installation Files

### 1. [install.php](install.php) (Lines 85-152)
**Function:** `create_config($url, $db_name, $db_user, $db_password, $db_host, $db_port)`

**Changes:**
- ✅ Added error logging configuration to config template
- ✅ Automatically creates `logs/` directory during installation
- ✅ Pre-configures `SB_DEBUG` constant
- ✅ Sets up error log file path

### 2. [install1.php](install1.php) (Lines 85-152)
**Function:** `create_config()` - Identical to install.php

**Changes:**
- ✅ Same modifications as install.php
- ✅ Ensures consistency across installation methods

### 3. [resources/config-source.php](resources/config-source.php)
**Purpose:** Template for manual configuration

**Changes:**
- ✅ Added error logging section
- ✅ Documents configuration options
- ✅ Can be used for manual setup

---

## 🎯 Core Database Fixes (Already Applied)

### [include/functions.php](include/functions.php)

These fixes are **permanent** and work with **any** config.php:

#### Fix #1: Connection Failure Handling (Lines 122-138)
```php
if (!$SB_CONNECTION->real_connect(...)) {
    // CRITICAL FIX: Clear invalid connection
    $SB_CONNECTION = null;
    return false;
}
catch (Exception $exception) {
    // CRITICAL FIX: Clear on exception
    $SB_CONNECTION = null;
    error_log('Chat DB Connection Exception: ' . $exception->getMessage());
    return false;
}
```

#### Fix #2: Connection Validation (Lines 265-285)
```php
function sb_db_init_settings() {
    global $SB_CONNECTION;
    
    // CRITICAL FIX: Validate before use
    if (!$SB_CONNECTION || !($SB_CONNECTION instanceof mysqli) || $SB_CONNECTION->connect_error) {
        return false;
    }
    
    if (!@$SB_CONNECTION->ping()) {
        $SB_CONNECTION = null;
        return false;
    }
    
    // Safe to use now
    $SB_CONNECTION->set_charset('utf8mb4');
    $SB_CONNECTION->query("SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");
    return true;
}
```

#### Fix #3: Connection Reuse (Lines 106-121)
```php
function sb_db_connect() {
    global $SB_CONNECTION;
    
    // IMPORTANT FIX: Verify connection is alive
    if ($SB_CONNECTION && ($SB_CONNECTION instanceof mysqli) && !$SB_CONNECTION->connect_error) {
        if (@$SB_CONNECTION->ping()) {
            sb_db_init_settings();
            return true;
        } else {
            // Connection lost, clear and reconnect
            $SB_CONNECTION = null;
        }
    }
    // ... proceed with new connection
}
```

---

## 🚀 Deployment Scenarios

### Scenario 1: Fresh Installation on New Website

**Steps:**
1. Upload chatbot folder to server
2. Visit: `https://yoursite.com/chat/install.php`
3. Enter database credentials in wizard
4. Click "Install"

**What Happens Automatically:**
- ✅ Creates `config.php` with error logging
- ✅ Creates `logs/` directory
- ✅ Tests database connection
- ✅ Creates all required tables
- ✅ Enables all app integrations
- ✅ Ready to use immediately

**Result:** Fully functional chatbot with all fixes applied

---

### Scenario 2: Existing Installation (Already Configured)

**Current State:**
- `config.php` already exists
- Database tables present
- Application working

**What to Do:**
1. Keep existing `config.php` (don't delete)
2. Database fixes in `functions.php` work automatically
3. Optionally add error logging to existing `config.php`:
   ```php
   // Add at end of existing config.php
   if (!defined('SB_DEBUG')) {
       define('SB_DEBUG', true);
   }
   if (SB_DEBUG) {
       ini_set('log_errors', 1);
       $log_dir = __DIR__ . '/logs';
       if (!is_dir($log_dir)) @mkdir($log_dir, 0755, true);
       ini_set('error_log', $log_dir . '/error.log');
   }
   ```

**Result:** Existing installation enhanced with fixes

---

### Scenario 3: Re-Installation (Reset Configuration)

**When Needed:**
- Database credentials changed
- Moving to different server
- Corrupted configuration

**Steps:**
1. Backup database: `mysqldump -u root -p your_db > backup.sql`
2. Delete `config.php`
3. Visit `install.php`
4. Re-enter database credentials
5. Tables already exist (will be reused)

**Result:** Fresh config with all fixes, existing data preserved

---

## 🔐 SB_DEBUG Configuration

### Development Mode (Default)
```php
define('SB_DEBUG', true);
```
- Logs all errors to `logs/error.log`
- Hides errors from users (security)
- Detailed error reporting
- Connection exceptions logged

### Production Mode
```php
define('SB_DEBUG', false);
```
- Disables all error logging
- Maximum security
- No performance impact
- Recommended for live sites

### Changing After Installation

**Option 1: Edit config.php manually**
```php
// Change from true to false
define('SB_DEBUG', false);
```

**Option 2: Use admin settings** (if available)
- Settings → Advanced → Debug Mode

---

## 📊 Directory Structure After Installation

```
Chatbot/
├── config.php                 ✅ AUTO-GENERATED
├── install.php                (delete after install)
├── install1.php               (delete after install)
├── admin.php
├── health-check.php
├── test-connection.php        (delete in production)
├── logs/                      ✅ AUTO-CREATED
│   └── error.log              ✅ AUTO-POPULATED
├── uploads/                   (writable)
├── include/
│   ├── functions.php          ✅ FIXED (permanent)
│   └── ...
├── resources/
│   ├── config-source.php      ✅ UPDATED (template)
│   └── database-setup.sql
└── ...
```

---

## ✅ Verification Checklist

After installation, verify:

### 1. Config File Generated
```bash
ls -la config.php
# Should exist with proper permissions
```

### 2. Logs Directory Created
```bash
ls -la logs/
# Should exist and be writable
```

### 3. Error Logging Active
```bash
# Visit any page, then check:
cat logs/error.log
# Should log any PHP errors
```

### 4. Database Connection Working
```php
# Visit: http://localhost/Chatbot/test-connection.php
# Should show: "🎉 ALL TESTS PASSED!"
```

### 5. Health Check Passing
```php
# Visit: http://localhost/Chatbot/health-check.php
# Should return: {"status": "ok"}
```

---

## 🎓 For Developers

### Understanding the Installation Process

**File:** `install.php` or `install1.php`

**Key Function:** `create_config()`

```php
function create_config($url, $db_name, $db_user, $db_password, $db_host, $db_port) {
    // 1. Define config template with placeholders
    $config_template = <<<'PHP'
    // ... full config with [URL], [DB_NAME], etc.
    PHP;
    
    // 2. Replace placeholders with actual values
    $config = str_replace(
        ['[URL]', '[DB_NAME]', '[DB_USER]', '[DB_PASSWORD]', '[DB_HOST]', '[DB_PORT]'],
        [$url, $db_name, $db_user, $db_password, $db_host, $db_port],
        $config_template
    );
    
    // 3. Create logs directory
    $log_dir = SB_PATH . '/logs';
    if (!is_dir($log_dir)) {
        @mkdir($log_dir, 0755, true);
    }
    
    // 4. Write config.php file
    return file_put_contents(SB_PATH . '/config.php', $config);
}
```

### Why This Approach?

✅ **Dynamic:** Adapts to any environment  
✅ **Secure:** No hardcoded credentials  
✅ **Automated:** Zero manual configuration  
✅ **Portable:** Works on any hosting  
✅ **Maintainable:** Single source of truth  
✅ **Future-proof:** Easy to update template

---

## 🔄 Updating the Template

### To Add New Configuration Options:

1. **Edit install.php** (lines 85-145):
   ```php
   // Add to $config_template
   define('NEW_OPTION', 'value');
   ```

2. **Edit install1.php** (same lines):
   ```php
   // Keep in sync with install.php
   define('NEW_OPTION', 'value');
   ```

3. **Edit resources/config-source.php**:
   ```php
   // Update template for manual installs
   define('NEW_OPTION', 'value');
   ```

4. **Test fresh installation:**
   ```bash
   rm config.php
   # Visit install.php
   # Verify NEW_OPTION in generated config.php
   ```

---

## 🆘 Troubleshooting

### Problem: config.php Not Generated

**Check:**
1. Directory writable? `chmod 755 /path/to/Chatbot/`
2. PHP has write permissions?
3. SELinux blocking? (Linux servers)

**Solution:**
```bash
# Make directory writable
chmod 755 /path/to/Chatbot/
# Or create manually from template
cp resources/config-source.php config.php
# Then edit values manually
```

---

### Problem: logs/ Directory Not Created

**Check:**
1. Directory permissions
2. PHP `mkdir()` allowed
3. Safe mode restrictions

**Solution:**
```bash
# Create manually
mkdir logs
chmod 755 logs
# Or 777 if permission issues persist
chmod 777 logs
```

---

### Problem: Error Logging Not Working

**Check:**
1. `logs/error.log` exists?
2. File writable?
3. `SB_DEBUG` set to true?

**Solution:**
```bash
# Create log file manually
touch logs/error.log
chmod 666 logs/error.log

# Or in config.php, ensure:
define('SB_DEBUG', true);
```

---

## 📚 Related Documentation

- [FIXES_APPLIED.md](FIXES_APPLIED.md) - Summary of all fixes
- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Complete troubleshooting guide
- [health-check.php](health-check.php) - Diagnostic endpoint
- [test-connection.php](test-connection.php) - Connection testing tool
- [resources/database-setup.sql](resources/database-setup.sql) - Database creation script

---

## 🎉 Summary

### What's Dynamic:
✅ Database credentials  
✅ Application URL  
✅ Error logging configuration  
✅ Logs directory creation  
✅ Environment detection

### What's Fixed (Permanent):
✅ Database connection handling  
✅ Connection validation logic  
✅ Error recovery mechanisms  
✅ Connection reuse strategy  
✅ Exception handling

### Result:
🚀 **Universal chatbot application that works on ANY website with ANY configuration, automatically!**

---

**Last Updated:** February 10, 2026  
**Installation Scripts:** install.php, install1.php  
**Core Fixes:** include/functions.php  
**Status:** Production Ready ✅
