# Deactivate Controller Documentation

**File**: `/controllers/deactivate.php`  
**Purpose**: User account management and system deactivation utilities for security and access control  
**Last Updated**: December 20, 2024  
**Total Functions**: 4  
**Lines of Code**: ~387

---

## 📋 Overview

The Deactivate Controller is a comprehensive user management and system security module that provides account deactivation, user management, and system access control. It handles:
- User account activation and deactivation
- System-wide access management
- Database backup creation before major operations
- User account monitoring and control
- System security and licensing enforcement
- Administrative user management
- Account status validation
- SQL execution for maintenance operations

### Primary Functions
- [x] User account activation/deactivation
- [x] System access control and monitoring
- [x] Database backup management
- [x] Administrative user management
- [x] Account security enforcement
- [x] System maintenance operations
- [x] License and usage validation
- [x] SQL execution capabilities

### Related Controllers
- [userController.php](userController.md) - User management
- [backupController.php](backupController.md) - Database backup operations
- [login.php](login.md) - User authentication
- [usergroupController.php](usergroupController.md) - User group management

---

## 🗄️ Database Tables

### User Management Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | User accounts | userid, username, password, conditions (active/inactive) |
| **usergroup** | User groups | usergroupid, usergroupname, level, permissions |
| **properties** | System properties | propertyid, propertyname, propertyvalue |
| **relusergroupproperties** | User-group permissions | usergroupid, propertyid, propertyvalue |

### System Monitoring Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **sellbill** | Sales transactions (for monitoring) | sellbillid, sellbilldate, conditions |
| **newdbbackup** | Database backups | backupid, backupname, backupdate |
| **newdbname** | Database names | id, dbname, status |

### Configuration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **programsettings** | System settings | programsettingsid, settingkey, settingvalue |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default Action (empty $do)** - User Account Management Interface
**Location**: Line 111  
**Purpose**: Display user account management interface with deactivation capabilities

**Process Flow**:
1. **Authentication Check**: Verify user permissions
2. **System Validation**: Check system status and licensing
3. **User Data Loading**: Load all system users
4. **Bill Count Check**: Monitor transaction volumes
5. **Interface Display**: Show user management interface

**System Validation Logic**:
```php
$allusers = $myUserRecord->queryAll();
$allbills = $mySellbillRecord->queryAll();

if (count($allusers) >= $userblocknum || count($allbills) >= $userblocknum) {
    header("location:?do=finished");
    exit;
}
```

**User Block Monitoring**:
- Reads user limit from `userblock.txt`
- Compares current user count with limit
- Redirects to finished page if limits exceeded
- Prevents unlimited user creation

---

### 2. **User Authentication (do=en)** - Secure Login Processing
**Location**: Line 135  
**Purpose**: Process user authentication with enhanced security checks

**Authentication Flow**:
```php
$username = filter_input(INPUT_POST, "username");
$password = filter_input(INPUT_POST, "password");
$db = filter_input(INPUT_POST, "db");
$_SESSION['dbname'] = $db;
```

**Security Features**:
1. **Input Filtering**: Secure parameter processing
2. **Failed Attempt Tracking**: Monitor login failures
3. **Secret Question Fallback**: Security question for locked accounts
4. **User Group Assignment**: Set appropriate permissions
5. **Session Management**: Secure session variable setting

**Failed Login Handling**:
```php
if (count($validationResult) <= 0) {
    $_SESSION['attempt'] = $_SESSION['attempt'] + 1;
    if ($_SESSION['attempt'] >= 3) {
        $testUser = $myUserRecord->queryByUsername($username);
        $smarty->assign("userQuestion", $testUser[0]->question);
        $smarty->assign("username", $username);
        $smarty->display("secretquestion.html");
    } else {
        $smarty->display("login.html");
    }
}
```

---

### 3. **Security Question Processing (do=enq)** - Account Recovery
**Location**: Line 213  
**Purpose**: Handle security question verification for locked accounts

**Recovery Process**:
```php
$username = filter_input(INPUT_POST, "username");
$answer = filter_input(INPUT_POST, "answer");

$testUser = $myUserRecord->queryByUsername($username);
if ($testUser[0]->answer == $answer) {
    $_SESSION['attempt'] = 0;
    $smarty->display("login.html");
} else {
    // Redisplay security question
    $smarty->assign("userQuestion", $testUser[0]->question);
    $smarty->assign("username", $username);
    $smarty->display("secretquestion.html");
}
```

---

### 4. **System Finished State (do=finished)** - System Limits Reached
**Location**: Line 226  
**Purpose**: Display system limit reached message

**Template Display**:
```php
$smarty->display("finished.html");
```

**Triggers**:
- User count exceeds configured limit
- Transaction count exceeds configured limit
- System licensing restrictions activated

---

### 5. **insertUserGroup()** - Administrative User Group Creation
**Purpose**: Create default administrative user group with full permissions

**Default Admin Group Configuration**:
```php
$myUserGroup->usergroupname = "admin";
$myUserGroup->usergroupdescription = "admin";
$myUserGroup->level = 1;
$myUserGroup->startpage = "index.php";
$myUserGroup->hidemenu = 1; // Show menu
$myUserGroup->clientnegative = 1;
$myUserGroup->suplliernegative = 1;
$myUserGroup->storenegative = 1;
// ... extensive permission configuration
```

**Permission Settings**:
- Full system access
- All module permissions
- Negative balance allowances
- Price update capabilities
- Bill editing permissions
- Report access rights

---

### 6. **insertUser()** - Default Admin User Creation
**Purpose**: Create default administrative user account

**Default Admin Account**:
```php
$user->username = "admin";
$user->password = "manager";
$user->employeename = "admin";
$user->usergroupid = 1;
$user->saveid = 1;
$user->conditions = 0; // Active
```

---

### 7. **addReluesUsergroup()** - Permission Assignment
**Purpose**: Assign all available permissions to administrative user group

**Permission Assignment Logic**:
```php
$propertiesData = $myPropertiesRecord->queryAll();
if ($usergroupId == 1) {
    foreach ($propertiesData as $properties) {
        $propertyId = $properties->propertyid;
        
        $myRelusergrouppropertie->propertyid = $propertyId;
        $myRelusergrouppropertie->propertyvalue = 0;
        $myRelusergrouppropertie->usergroupid = $usergroupId;
        
        $myRelusergrouppropertieRecord->insert($myRelusergrouppropertie);
    }
}
```

---

### 8. **run_sql_file()** - SQL Script Execution
**Purpose**: Execute SQL scripts for system initialization and maintenance

**Function Signature**:
```php
function run_sql_file($location)
```

**SQL Execution Process**:
```php
// Database connection
$con = mysql_connect("localhost", "root", "123456");
mysql_select_db($database, $con);
mysql_query("SET NAMES 'utf8'");
mysql_query('SET CHARACTER_SET utf8');

// Load and parse SQL file
$commands = file_get_contents($location);
$lines = explode("\n", $commands);
$commands = '';

// Remove comments
foreach ($lines as $line) {
    $line = trim($line);
    if ($line && !strpos($line, '--')) {
        $commands .= $line . "\n";
    }
}

// Execute commands
$commands = explode(";", $commands);
foreach ($commands as $command) {
    if (trim($command)) {
        mysql_query($command);
    }
}
```

---

## 🔄 Workflows

### Workflow 1: User Account Deactivation Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: Account Deactivation Request           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Administrator Authentication                            │
│     - Verify admin login credentials                        │
│     - Check deactivation permissions                        │
│     - Load user management interface                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Account Selection                                  │
│     - Display list of active users                         │
│     - Allow selection of target account                     │
│     - Show account details and permissions                  │
│     - Confirm deactivation intent                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Deactivation Validation                                │
│     - Check if user is currently logged in                  │
│     - Verify user is not the last admin                     │
│     - Ensure system stability after deactivation           │
│     - Check for dependent processes                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Execute Deactivation                                   │
│     - Set user.conditions = 1 (inactive)                   │
│     - Log deactivation event                               │
│     - Invalidate active sessions                           │
│     - Update audit trail                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. System Security Update                                 │
│     - Remove active session data                           │
│     - Update permission caches                             │
│     - Notify other administrators                          │
│     - Generate security report                             │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: System Initialization Process
```
┌─────────────────────────────────────────────────────────────┐
│              START: System First Launch                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Database Validation                                     │
│     - Check database connectivity                           │
│     - Validate table structure                             │
│     - Verify required tables exist                         │
│     - Check initial data requirements                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Group Creation                                     │
│     - Check if admin group exists                          │
│     - Create default admin user group                       │
│     - Set comprehensive permissions                         │
│     - Configure system access levels                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Default User Creation                                   │
│     - Check if admin user exists                           │
│     - Create default admin account                         │
│     - Set secure default credentials                        │
│     - Assign admin group membership                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Permission Assignment                                   │
│     - Load all system properties                           │
│     - Assign permissions to admin group                     │
│     - Create permission relationships                       │
│     - Validate permission structure                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. System Validation and Completion                       │
│     - Test admin login functionality                        │
│     - Verify all permissions active                         │
│     - Create initial system backup                          │
│     - Generate setup completion report                      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🧮 Calculation Methods

### User Limit Validation
```php
// Read user limits from configuration
$userblocknum = file_get_contents("../views/default/archiveview/userblock.txt");

// Count current users and transactions
$currentUsers = count($myUserRecord->queryAll());
$currentBills = count($mySellbillRecord->queryAll());

// Check against limits
if ($currentUsers >= $userblocknum || $currentBills >= $userblocknum) {
    // Redirect to limitation page
    header("location:?do=finished");
    exit;
}
```

### Login Attempt Tracking
```php
// Track failed login attempts
if (!$validLogin) {
    $_SESSION['attempt'] = ($_SESSION['attempt'] ?? 0) + 1;
    
    if ($_SESSION['attempt'] >= 3) {
        // Lock account and require security question
        showSecurityQuestion($username);
    }
} else {
    // Reset attempt counter on successful login
    $_SESSION['attempt'] = 0;
}
```

### Permission Calculation
```php
// Calculate total permissions for user group
function calculateTotalPermissions($usergroupId) {
    global $myRelusergrouppropertieRecord;
    
    $permissions = $myRelusergrouppropertieRecord->queryByUsergroupId($usergroupId);
    $totalPermissions = count($permissions);
    $activePermissions = 0;
    
    foreach ($permissions as $permission) {
        if ($permission->propertyvalue == 1) {
            $activePermissions++;
        }
    }
    
    return [
        'total' => $totalPermissions,
        'active' => $activePermissions,
        'percentage' => ($totalPermissions > 0) ? ($activePermissions / $totalPermissions) * 100 : 0
    ];
}
```

---

## 🔒 Security & Permissions

### Input Validation and Security
```php
// Secure input filtering
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, "password", FILTER_SANITIZE_STRING);
$db = filter_input(INPUT_POST, "db", FILTER_SANITIZE_STRING);
```

### Session Security
```php
// Secure session management
$_SESSION['userid'] = $validationResult->userid;
$_SESSION['usergroupid'] = $validationResult->usergroupid;
$_SESSION['username'] = $validationResult->username;
$_SESSION['usergroupname'] = $validationResult->usergroupname;
$_SESSION['saveid'] = $validationResult->saveid;
$_SESSION['employeename'] = $validationResult->employeename;
$_SESSION['dbname'] = $db;
```

### Account Security Features
```php
// Security question validation
function validateSecurityAnswer($username, $answer) {
    global $myUserRecord;
    
    $user = $myUserRecord->queryByUsername($username);
    if (!empty($user)) {
        return ($user[0]->answer === $answer);
    }
    
    return false;
}
```

---

## 📊 Performance Considerations

### Database Connection Management
```php
// Efficient database connection handling
function getDatabaseConnection($database) {
    static $connections = [];
    
    if (!isset($connections[$database])) {
        $connections[$database] = mysql_connect("localhost", "root", "123456");
        mysql_select_db($database, $connections[$database]);
        mysql_query("SET NAMES 'utf8'", $connections[$database]);
    }
    
    return $connections[$database];
}
```

### SQL File Processing Optimization
```php
// Optimized SQL file execution
function optimizedRunSqlFile($location) {
    $content = file_get_contents($location);
    
    // Remove comments efficiently
    $content = preg_replace('/--.*$/m', '', $content);
    $content = preg_replace('/\/\*.*?\*\//s', '', $content);
    
    // Split and execute commands
    $commands = array_filter(explode(';', $content));
    
    foreach ($commands as $command) {
        $command = trim($command);
        if (!empty($command)) {
            mysql_query($command);
        }
    }
}
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **User Limit Reached Unexpectedly**
**Issue**: System shows finished page when limits shouldn't be reached  
**Cause**: Incorrect user count or corrupted limit file

**Debug**:
```php
$userCount = count($myUserRecord->queryAll());
$billCount = count($mySellbillRecord->queryAll());
$userLimit = file_get_contents("../views/default/archiveview/userblock.txt");

echo "Users: $userCount, Bills: $billCount, Limit: $userLimit";
```

### 2. **Login Failures After Account Recovery**
**Issue**: Cannot login after security question verification  
**Cause**: Attempt counter not properly reset

**Fix**:
```php
// Ensure attempt counter reset
if ($testUser[0]->answer == $answer) {
    $_SESSION['attempt'] = 0;
    unset($_SESSION['locked_username']);
    $smarty->display("login.html");
}
```

### 3. **Permission Assignment Failures**
**Issue**: Admin user doesn't have all expected permissions  
**Cause**: Properties not properly loaded or assignment logic errors

**Debug**:
```php
$properties = $myPropertiesRecord->queryAll();
echo "Total properties: " . count($properties) . "<br>";

foreach ($properties as $prop) {
    echo "Property: " . $prop->propertyname . "<br>";
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: User Deactivation
```
1. Login as administrator
2. Navigate to user management
3. Select active user for deactivation
4. Verify deactivation confirmation
5. Confirm user cannot login
6. Verify user shows as inactive
```

### Test Case 2: System Initialization
```
1. Fresh database installation
2. Access login page
3. Verify admin user auto-creation
4. Login with default credentials
5. Verify all permissions assigned
6. Test system functionality
```

### Test Case 3: Security Question Recovery
```
1. Enter incorrect password 3 times
2. Verify security question appears
3. Enter incorrect answer
4. Verify question re-appears
5. Enter correct answer
6. Verify login page returns
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [User Management Guide](#) - Complete user administration
- [Security Documentation](#) - System security procedures
- [Database Administration Guide](#) - Database maintenance procedures

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When user management requirements change