# User Controller Documentation

**File**: `/controllers/userController.php`  
**Purpose**: Manages system users, accounts, permissions, and authentication  
**Last Updated**: December 19, 2024  
**Total Functions**: 12  
**Lines of Code**: ~940

---

## 📋 Overview

The User Controller is the core component for managing user accounts and access control in the ERP system. It handles:
- Creating and editing user accounts
- User authentication and session management
- User group assignments and permissions
- Store, branch, and save assignments
- Employee integration
- Security settings and access control
- Saudi electronic invoice settings
- Multi-factor authentication (questions/answers)
- License limitations and user blocking

### Primary Functions
- [x] Create new user accounts
- [x] Edit existing user accounts
- [x] Soft delete/activate users
- [x] View users by group or all users
- [x] Assign user groups and permissions
- [x] Manage store and branch access
- [x] Set save (cash register) access
- [x] Employee account integration
- [x] Project and bank account access
- [x] Security question/answer setup
- [x] File upload for user documents
- [x] Saudi electronic invoice configuration

### Related Controllers
- [usergroupController.php](usergroupController.md) - User group management
- [sellbillController.php](sellbillController.md) - Sales operations
- [buyBillController.php](buyBillController.md) - Purchase operations
- [storeController.php](storeController.md) - Store management
- [branchController.php](#) - Branch management
- [employeeController.php](#) - Employee management
- [bankController.php](#) - Bank management
- [projectController.php](#) - Project management
- [saveController.php](#) - Cash register management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | Main user accounts | userid, username, password, employeename, usergroupid, saveid, userstoreid, conditions |
| **usergroup** | User roles/groups | usergroupid, usergroupname, permissions |
| **esaudiusersetting** | Saudi e-invoice config | userid, licensetype, licensenumber, companytaxregistrationnumber |

### Access Control Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **save** | Cash registers/safes | user.saveid, user.saveids |
| **store** | Warehouses/branches | user.userstoreid, user.storeids |
| **branch** | System branches | user.branchid |
| **project** | Business projects | user.projectids |
| **bank** | Bank accounts | user.bankids |
| **charities** | Charity organizations | user.charityids |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employee** | Employee master data | empid, employeeName, salary |
| **programsettings** | System configuration | programsettingsid, saudielectronicinvoice |

---

## 🔧 Key Functions

### 1. **add()** - Create New User
**Location**: Line 388  
**Purpose**: Create a new user account with full permissions and settings

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

**Parameters** (via $_POST):
- `username` - Login username
- `password` - User password
- `employeename` - Display name
- `usergroupid` - User group/role ID
- `saveid` - Default cash register ID
- `userstoreid` - Allowed stores (comma-separated)
- `userstoreidDef` - Default store ID
- `awardrate` - Commission rate (float)
- `searchinonesave` - Search limitation flag
- `branchid` - Branch assignment
- `question` - Security question
- `answer` - Security answer
- `addEmployeeToo` - Create employee record flag
- `salary` - Employee salary
- `projectids` - Accessible projects array
- `bankids` - Accessible banks array
- `saveids` - Accessible cash registers array
- `storeids` - Accessible stores array
- `charityids` - Accessible charities array

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Validate Input  │───▶│ Check License    │───▶│ Create Employee │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                         │
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Save User Data  │◀───│ Process Arrays   │◀───│ Upload Files    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                │
                    ┌──────────────────┐
                    │ Saudi E-Invoice  │
                    │ Configuration    │
                    └──────────────────┘
```

**Key Features**:
- License limitation checking
- Employee account creation
- File upload handling
- Array processing for multi-select permissions
- Saudi electronic invoice setup

### 2. **showByUsergroupId()** - Display Users by Group
**Location**: Line 579  
**Purpose**: Show users filtered by user group

**Parameters**:
- `usergroupId` - Group ID to filter by

### 3. **showAll()** - Display All Users
**Location**: Line 596  
**Purpose**: Display all users except current session user

### 4. **delete()** - Soft Delete User
**Location**: Line 612  
**Purpose**: Temporarily disable/enable user accounts

**Parameters**:
- `conditions` - Current status (0=active, 1=disabled)
- `userid` - User ID to modify

### 5. **deleteFinaly()** - Permanent Delete
**Location**: Line 634  
**Purpose**: Permanently remove user from database

### 6. **edit()** - Load User for Editing
**Location**: Line 646  
**Purpose**: Load user data and prepare for editing

**Returns**: User object with exploded array fields

### 7. **update()** - Update User Account
**Location**: Line 676  
**Purpose**: Update existing user account with new settings

**Key Features**:
- Session update for current user
- Permission validation
- User login validation

### 8. **CURL_IT2()** - Internal API Call
**Location**: Line 904  
**Purpose**: Make internal cURL requests for employee creation

---

## 🔄 Business Logic Flow

### User Creation Workflow
```
┌─────────────────┐
│ User Form       │
│ Submission      │
└─────────┬───────┘
          │
┌─────────▼───────┐    ┌──────────────────┐
│ License Check   │───▶│ Under Limit?     │──No──┐
│ (User Count)    │    └──────────────────┘      │
└─────────────────┘                              │
          │Yes                                   │
┌─────────▼───────┐    ┌──────────────────┐      │
│ Employee        │───▶│ Create Employee  │      │
│ Creation?       │    │ Record (CURL)    │      │
└─────────────────┘    └──────────────────┘      │
          │                                      │
┌─────────▼───────┐    ┌──────────────────┐      │
│ Process Access  │───▶│ Format Arrays    │      │
│ Permissions     │    │ (Projects, Banks)│      │
└─────────────────┘    └──────────────────┘      │
          │                                      │
┌─────────▼───────┐    ┌──────────────────┐      │
│ File Upload     │───▶│ Save User Data   │      │
│ (PDF Documents) │    │ to Database      │      │
└─────────────────┘    └──────────────────┘      │
          │                                      │
┌─────────▼───────┐                              │
│ Saudi E-Invoice │                              │
│ Setup (Optional)│                              │
└─────────┬───────┘                              │
          │                                      │
          ▼                                      │
┌─────────────────┐                              │
│ Success         │◀─────────────────────────────┘
│ Response        │
└─────────────────┘
```

### Permission Management System
- **Store Access**: Primary store + additional stores
- **Save Access**: Default save + additional cash registers  
- **Project Access**: All projects (0) or specific projects
- **Bank Access**: All banks (0) or specific banks
- **Branch Access**: Single branch or all branches (-1)

---

## ⚠️ Common Issues

### PHP 8.2 Compatibility Issues
**Issue**: String concatenation in salary/employee creation
```php
// ✅ FIXED: Line 446 - Employee creation with proper type casting
$empid = (int) CURL_IT2(array('empName' => $userName, 'empSalary' => $salary), 'employeeController.php?do=add');
```

### Security Considerations
- **Password Storage**: Plain text passwords (consider hashing)
- **Session Management**: Updates session for current user edits
- **License Enforcement**: Blocks user creation beyond license limits
- **Access Control**: Multi-level permission system

### User Limitations
- Maximum users controlled by `$_SESSION['lic_userno']`
- Blocked users have `blockedByLimits = 1`
- Soft delete preserves data integrity

---

## 🔗 Dependencies

### Required DAOs
- `UserMySqlDAO` - User database operations
- `UserMySqlExtDAO` - Extended user queries
- `UsergroupMySqlDAO` - User group operations
- `SaveMySqlDAO` - Cash register operations
- `StoreMySqlDAO` - Store operations
- `BranchMySqlDAO` - Branch operations
- `BankMySqlDAO` - Bank operations
- `ProjectMySqlDAO` - Project operations
- `EmployeeMySqlDAO` - Employee operations

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/authentication.php` - Session validation
- `../library/uploadImages.php` - File upload handling
- `initiateStaticSessionCommingWithCurl.php` - cURL session management

### External Systems
- Employee management system (via CURL)
- Saudi ZATCA e-invoice system
- File storage system for user documents

---

## 🚀 Performance Notes

- License checking on every user creation
- Multi-table permission queries
- File upload processing
- Session validation on protected routes
- Array processing for comma-separated permissions

The User Controller is critical for system security and should be thoroughly tested for permission leaks and access control vulnerabilities.