# Backup Controller Documentation

**File**: `/controllers/backupController.php`  
**Purpose**: Manages database backup creation, restoration, and database switching  
**Last Updated**: December 19, 2024  
**Total Functions**: 5  
**Lines of Code**: ~169

---

## 📋 Overview

The Backup Controller is a critical system administration component for managing database backups and multi-database environments in the ERP system. It handles:
- Creating complete database backups
- Database structure and data duplication
- Multi-database environment management
- Database switching and restoration
- Backup naming and organization
- Historical backup tracking
- Production/development environment switching

### Primary Functions
- [x] Create full database backups
- [x] Duplicate database structure and data
- [x] Switch between databases
- [x] Backup naming and tracking
- [x] Multi-environment management
- [x] Historical backup listing
- [x] Database restoration capabilities

### Related Controllers
- [userController.php](userController.md) - User management and authentication
- [usergroupController.php](usergroupController.md) - User permissions for backup operations
- [programsettingsController.php](programsettingsController.md) - System configuration
- [manualBackup.php](#) - Manual backup operations
- [restoreDayBackup.php](#) - Daily backup restoration

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **newdbbackup** | Backup metadata | newdbbackupid, backupname, backupdate |

### Backup Environment Structure
| Environment Type | Purpose | Database Pattern |
|------------------|---------|------------------|
| **Production** | Live system | Original database name |
| **Backup Copies** | Historical data | `erp{backupId}` pattern |
| **Development** | Testing environment | `storesdb{backupId}` pattern |

---

## 🔧 Key Functions

### 1. **add()** - Create New Backup
**Location**: Line 112  
**Purpose**: Create a complete database backup with metadata tracking

**Function Signature**:
```php
function add()
```

**Parameters** (via $_POST):
- `backupname` - User-defined backup name/description

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Validate Input  │───▶│ Create Metadata  │───▶│ Get Backup ID   │
│ (Backup Name)   │    │ Record           │    │ (Auto-increment)│
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                         │
┌─────────────────┐    ┌──────────────────┐             │
│ Success         │◀───│ Duplicate Tables │◀────────────┘
│ Response        │    │ (Structure+Data) │
└─────────────────┘    └──────────────────┘
```

**Key Features**:
- Automatic timestamp recording
- Sequential backup ID generation
- Complete database duplication

### 2. **duplicateTables()** - Database Replication Engine
**Location**: Line 128  
**Purpose**: Create complete copy of database including structure and data

**Function Signature**:
```php
function duplicateTables($sourceDB = NULL, $targetDB = NULL)
```

**Parameters**:
- `$sourceDB` - Source database name
- `$targetDB` - Target database name (format: erp{backupId})

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Connect MySQL   │───▶│ Create Target    │───▶│ Get Table List  │
│ (Admin Level)   │    │ Database         │    │ from Source     │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                         │
                              ┌─────────────────────────────┐
                              │ For Each Table:             │
                              │ 1. Drop if exists          │
                              │ 2. Create structure        │
                              │ 3. Copy all data          │
                              │ 4. Optimize table         │
                              └─────────────────────────────┘
```

**SQL Operations Performed**:
```sql
-- 1. Create backup database
CREATE DATABASE erp{backupId}

-- 2. For each table:
DROP TABLE IF EXISTS `erp{backupId}`.`tablename`
CREATE TABLE `erp{backupId}`.`tablename` LIKE `sourceDB`.`tablename`
INSERT INTO `erp{backupId}`.`tablename` SELECT * FROM `sourceDB`.`tablename`
OPTIMIZE TABLE `erp{backupId}`.`tablename`
```

### 3. **loadDatabase()** - List Available Backups
**Location**: Line 152  
**Purpose**: Retrieve all available backup databases for selection

**Returns**: Array of backup metadata for display

### 4. **changedb()** - Switch Database Environment
**Location**: Line 160  
**Purpose**: Switch the active database environment

**Parameters** (via $_POST):
- `backupid` - Target backup ID (-2 for production, positive for backup)

**Logic Flow**:
```
┌─────────────────┐
│ Backup ID       │
│ Selection       │
└─────────┬───────┘
          │
    ┌─────▼─────┐
    │ ID = -2?  │──Yes──┐
    └───────────┘       │
          │No           │
┌─────────▼───────┐     │    ┌─────────────────┐
│ Set Session     │     │───▶│ Clear Session   │
│ dbname =        │          │ dbname          │
│ "storesdb{ID}"  │          │ (Production)    │
└─────────────────┘          └─────────────────┘
```

### 5. **Default Display** - Backup Management Interface
**Location**: Line 52  
**Purpose**: Display backup creation interface with authentication

---

## 🔄 Business Logic Flow

### Backup Creation Workflow
```
┌─────────────────┐
│ User Initiates  │
│ Backup Request  │
└─────────┬───────┘
          │
┌─────────▼───────┐    ┌──────────────────┐
│ Authentication  │───▶│ Input Validation │
│ Check           │    │ (Backup Name)    │
└─────────────────┘    └──────────────────┘
          │                       │
┌─────────▼───────┐    ┌──────────▼──────┐
│ Create Metadata │───▶│ Database        │
│ Record          │    │ Duplication     │
└─────────────────┘    └─────────────────┘
          │                       │
┌─────────▼───────┐               │
│ Generate        │◀──────────────┘
│ Success Message │
└─────────────────┘
```

### Database Environment Architecture
```
                    ┌─────────────────┐
                    │ Production      │
                    │ Database        │
                    └─────────┬───────┘
                              │
      ┌───────────────────────┼───────────────────────┐
      │                       │                       │
┌─────▼─────┐      ┌─────────▼────────┐      ┌─────▼─────┐
│ Backup 1  │      │ Backup 2         │      │ Backup N  │
│ erp1      │      │ erp2             │      │ erpN      │
└───────────┘      └──────────────────┘      └───────────┘
      │                       │                       │
┌─────▼─────┐      ┌─────────▼────────┐      ┌─────▼─────┐
│ Dev Env 1 │      │ Dev Env 2        │      │ Dev Env N │
│storesdb1  │      │ storesdb2        │      │ storesdbN │
└───────────┘      └──────────────────┘      └───────────┘
```

---

## ⚠️ Common Issues

### MySQL Version Compatibility
**Issue**: Code uses deprecated mysql_* functions
```php
// ⚠️ DEPRECATED: Lines 129-147 use old MySQL extension
$link = mysql_connect(ConnectionProperty::getHost(), ConnectionProperty::getUser(), ConnectionProperty::getPassword());
```

**Recommendation**: Upgrade to MySQLi or PDO for PHP 8.2 compatibility

### Memory and Performance
**Issue**: Large database duplication can exhaust memory/time limits
- **Solution**: Consider chunked data copying for large tables
- **Monitor**: Execution time for timeout prevention
- **Optimize**: Table-by-table processing with progress tracking

### Security Considerations
**Issue**: Direct database creation requires elevated privileges
- **Admin Rights**: Requires CREATE DATABASE privileges
- **Authentication**: Protected by session authentication
- **Access Control**: Should be limited to system administrators

### Session Management
**Issue**: Database switching affects all subsequent operations
```php
// ✅ IMPLEMENTED: Line 166 - Session-based database switching
$_SESSION['dbname'] = "storesdb" . $backupId;
```

---

## 🔗 Dependencies

### Required DAOs
- `NewdbbackupMySqlDAO` - Backup metadata operations
- `ConnectionProperty` - Database connection parameters

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/authentication.php` - Access control
- `../public/config.php` - Configuration

### System Requirements
- **MySQL Privileges**: CREATE DATABASE, SELECT, INSERT, CREATE TABLE
- **File System**: Adequate storage for database copies
- **Memory**: Sufficient RAM for data copying operations
- **Time Limits**: Extended execution time for large databases

### Security Model
- Session-based authentication required
- Administrative privileges needed
- Protected routes with authentication checks
- Backup operations logged with timestamps

---

## 🚀 Performance Notes

- **Database Size Impact**: Backup time scales with database size
- **Table Optimization**: OPTIMIZE TABLE improves backup performance
- **Connection Management**: Single connection for all operations
- **Memory Usage**: MySQL handles data copying internally
- **Storage Requirements**: Backups require 100% additional space

### Backup Strategy Recommendations
1. **Regular Backups**: Schedule during low-usage periods
2. **Retention Policy**: Implement backup rotation/cleanup
3. **Monitoring**: Track backup completion and file sizes
4. **Testing**: Regular restore testing for backup validation
5. **Documentation**: Maintain backup/restore procedures

The Backup Controller is essential for data protection and system recovery, providing robust database management capabilities for enterprise environments.