# Employee Controller Documentation

**File**: `/controllers/employeeController.php`  
**Purpose**: Manages employee records, personal data, attendance systems, and employee lifecycle  
**Last Updated**: December 19, 2024  
**Total Functions**: 4  
**Lines of Code**: ~986

---

## 📋 Overview

The Employee Controller is the core component for managing employee-related operations in the ERP system. It handles:
- Creating and editing employee profiles
- Managing employee personal information and documents
- Setting up employee attendance systems and schedules
- Tracking salary changes and employment history
- Handling employee groups and subgroups
- Managing employee documents and file uploads
- Calculating salary-related metrics (minute costs, absence costs)
- Branch-based employee access control

### Primary Functions
- [x] Create new employee profiles
- [x] Edit existing employee data
- [x] Delete employee records
- [x] View employee listings with search
- [x] Upload employee documents (contracts, ID cards, etc.)
- [x] Set up weekly attendance schedules
- [x] Calculate salary breakdowns and costs
- [x] Track salary change history
- [x] Manage employee groups and subgroups
- [x] Branch-based employee filtering

### Related Controllers
- [salaryReportController.php](salaryReportController.md) - Salary calculations and reports
- [EmployeeAttendanceController.php](EmployeeAttendanceController.md) - Daily attendance tracking
- [employeePersonalController.php](#) - Employee loans and advances
- [clientController.php](clientController.md) - Customer management
- [supplierController.php](supplierController.md) - Supplier management
- [dailyentry.php](dailyentry.md) - Accounting entries
- [accountstree.php](accountstree.md) - Chart of accounts

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `employee` | Main employee records | `employeeId`, `employeeName`, `employeeSalary`, `branchid` |
| `employeegroup` | Employee group categorization | `id`, `groupName`, `employeeattendancesystemid` |
| `employeesubgroup` | Employee sub-categorization | `id`, `subgroupName`, `employeegroupid` |
| `employeepersonnel` | Employee transactions/history | `employeeid`, `employeepersonneltype`, `employeepersonnelvalue` |
| `employeeattendancesystemweek` | Weekly attendance schedule | `employee_id`, `attendancedaynum`, `attendancetime` |

### Related Tables (References)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `accountstree` | Employee accounting entries | `id`, `customName`, `parentId` |
| `user` | System users linked to employees | `userid`, `username` |
| `country` | Employee nationality | `id`, `countryName` |
| `religions` | Employee religion | `id`, `religionName` |
| `branch` | Employee branch assignment | `branchId`, `branchName` |

### Reference Tables (Lookups)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `employeeattendancesystem` | Attendance system templates | `id`, `systemName` |
| `programsettings` | System configuration | `settingName`, `settingValue` |

---

## 🔧 Key Functions

### Main Controller Actions

#### **Default Action (Show Add Form)**
```php
if (!isset($_GET['do'])) // Line 121
```
- **Purpose**: Display employee add form with necessary data
- **Parameters**: None (GET request)
- **Process Flow**:
```
┌─ Load Data ─┐
│ • Week days │
│ • Countries │  
│ • Religions │
│ • Groups    │
│ • Branches  │
└─────────────┘
       ▼
┌─ Assign to Template ─┐
│ employeeview/add.html │
└───────────────────────┘
```

#### **Show Employee List**
```php
elseif ($_GET['do'] == "show") // Line 167
```
- **Purpose**: Display filtered list of employees
- **Parameters**: 
  - `txtSearch` (string): Employee name search
  - Branch filtering from session
- **Process Flow**:
```
┌─ Check Search ─┐
│ txtSearch != -1│
└────────────────┘
       ▼
┌─ Apply Filters ─┐
│ • Name search   │
│ • Branch filter │
└─────────────────┘
       ▼
┌─ Query Database ─┐
│ queryAllwithtname│
└──────────────────┘
```

#### **Edit Employee**
```php
elseif ($_GET['do'] == "edit") // Line 217
```
- **Purpose**: Load employee data for editing
- **Parameters**: 
  - `id` (int): Employee ID to edit
- **Security**: Branch access validation
- **Process Flow**:
```
┌─ Load Employee ─┐
│ employeeDAO->   │
│    load($id)    │
└─────────────────┘
       ▼
┌─ Branch Security ─┐
│ Check branchId    │
│ permissions       │
└───────────────────┘
       ▼
┌─ Load Attendance ─┐
│ Schedule & Groups │
└───────────────────┘
```

### Core Business Functions

#### **add() Function**
```php
function add() // Line 289
```
- **Purpose**: Create new employee with full data processing
- **Parameters** (from $_POST):
  - `empName`: Employee name (required)
  - `empSalary`: Base salary amount
  - `empBouns`: Bonus amount
  - `houseAllowance`: Housing allowance
  - `transportationAllowance`: Transport allowance
  - `noOfWorkDaysPerMonth`: Working days per month
  - `noOfWorkHoursDaysPerDay`: Working hours per day
  - `socialInsurance`: Social insurance percentage
  - `workTax`: Work tax percentage
  - `branchid`: Branch assignment
  - Multiple file uploads for documents
  - Attendance schedule for 7 days

- **Return**: Employee ID (int)

- **Process Flow**:
```
┌─ Validate Input ─┐
│ • Required fields│
│ • File uploads  │
│ • Numeric values│
└─────────────────┘
       ▼
┌─ Upload Documents ─┐
│ • Contract        │
│ • Personal photo  │
│ • ID cards        │
│ • Certificates   │
└───────────────────┘
       ▼
┌─ Calculate Costs ─┐
│ minuteLateCost =  │
│ (salary+allow)/   │
│ (days*hours*60)   │
└───────────────────┘
       ▼
┌─ Create Accounting ─┐
│ • Advance account  │
│ • Employee account │
│ addTreeElement()   │
└────────────────────┘
       ▼
┌─ Save Employee ─┐
│ employeeDAO->  │
│ insert()       │
└────────────────┘
       ▼
┌─ Setup Schedule ─┐
│ 7 days attendance│
│ system setup     │
└──────────────────┘
```

- **Code Example**:
```php
// Salary cost calculations
$bast = $employee->employeeSalary + $employee->houseAllowance + $employee->transportationAllowance;
$makam = $employee->noOfWorkDaysPerMonth * $employee->noOfWorkHoursDaysPerDay * 60;
if ($makam != 0) {
    $employee->minuteLateCost = round(($bast / $makam), 3);
}

// Create accounting entries
$treeId1 = addTreeElement("سلفة $employee->employeeName", 63, 1, 0, 1);
$treeId2 = addTreeElement($employee->employeeName, 97, 1, 0, 1);
```

#### **update() Function**
```php
function update() // Line 576
```
- **Purpose**: Update existing employee with change tracking
- **Parameters**: Similar to add() plus `employeeId`
- **Key Features**:
  - Salary change history tracking via `savesalaryChangeRecord()`
  - Document update with old file cleanup
  - Attendance schedule updates
  - Accounting tree updates

- **Process Flow**:
```
┌─ Load Current ─┐
│ Employee data │
└───────────────┘
       ▼
┌─ Track Changes ─┐
│ savesalaryChange│
│ Record()        │
└─────────────────┘
       ▼
┌─ Update Files ─┐
│ • Replace docs │
│ • Delete old   │
└────────────────┘
       ▼
┌─ Update Database ─┐
│ employeeDAO->     │
│ update()          │
└───────────────────┘
       ▼
┌─ Update Accounting ─┐
│ Tree element names │
└─────────────────────┘
```

#### **delete() Function**
```php
function delete() // Line 915
```
- **Purpose**: Soft delete employee (mark as deleted)
- **Parameters**: 
  - `id` (GET): Employee ID
  - `conditions` (GET): Delete status
- **Process Flow**:
```
┌─ Mark Deleted ─┐
│ conditions = 1 │
└────────────────┘
       ▼
┌─ Update Record ─┐
│ updateEmployee()│
└─────────────────┘
       ▼
┌─ Remove Accounting ─┐
│ delTreeElementById()│
└─────────────────────┘
```

#### **savesalaryChangeRecord() Function**
```php
function savesalaryChangeRecord($employeeId, $oldSalary, $newSalary, $changeReason = '') // Line 941
```
- **Purpose**: Track salary changes for audit purposes
- **Parameters**:
  - `$employeeId` (int): Employee identifier
  - `$oldSalary` (float): Previous salary amount
  - `$newSalary` (float): New salary amount
  - `$changeReason` (string): Optional reason for change

- **Process Flow**:
```
┌─ Compare Values ─┐
│ old == new?     │
│ return if same  │
└─────────────────┘
       ▼
┌─ Create Record ─┐
│ • Type 15       │
│ • Done = 0      │
│ • Current month │
└─────────────────┘
       ▼
┌─ Save to Personnel ─┐
│ employeepersonnel   │
│ table               │
└─────────────────────┘
```

---

## 🔄 Business Logic Flow

### Employee Creation Workflow
```
┌─ START: Add Employee ─┐
│                       │
▼                       │
┌─ Validate Required ─┐ │
│ • Name             │ │
│ • Branch           │ │
│ • Basic info       │ │
└────────────────────┘ │
       ▼               │
┌─ Process Documents ─┐│
│ • Contract         ││
│ • ID cards         ││
│ • Certificates     ││
│ • Photos           ││
└────────────────────┘│
       ▼               │
┌─ Calculate Rates ─┐ │
│ • Minute cost     │ │
│ • Absence cost    │ │
│ • Based on salary │ │
└───────────────────┘ │
       ▼               │
┌─ Setup Accounting ─┐│
│ • Advance account ││
│ • Employee ledger ││
└────────────────────┘│
       ▼               │
┌─ Configure Schedule ┐│
│ • 7-day setup      ││
│ • Attendance times ││
│ • Departure times  ││
└────────────────────┘│
       ▼               │
┌─ Save Employee ────┐│
│ Database insert    ││
└────────────────────┘│
       ▼               │
┌─ END: Return ID ───┘
```

### Salary Change Tracking
```
┌─ Salary Update ─┐
│                 │
▼                 │
┌─ Compare Values ┐│
│ old != new?    ││
└────────────────┘│
       ▼          │
┌─ Create History ┐│
│ • Old amount   ││
│ • New amount   ││
│ • Change date  ││
│ • User ID      ││
└────────────────┘│
       ▼          │
┌─ Save Record ──┐│
│ Type 15        ││
│ (salary change)││
└────────────────┘│
       ▼          │
┌─ Update Employee ┘
│ Main record     
└─────────────────
```

### Cost Calculation Logic
```
Total Compensation = Base Salary + House Allowance + Transportation Allowance

Minute Late Cost = Total Compensation / (Work Days × Work Hours × 60 minutes)

Day Absence Cost = Total Compensation / (Work Days × Absence Days Factor)
```

---

## ⚠️ Common Issues

### Known Bugs & Limitations

1. **File Upload Issues**
   - **Issue**: Unlink operations may fail if files don't exist
   - **Location**: Lines 640-727 in update()
   - **Impact**: PHP warnings when updating documents
   - **Solution**: Add file_exists() checks before unlink()

2. **Duplicate Code**
   - **Issue**: Army photo upload duplicated
   - **Location**: Lines 694-696 in update()
   - **Impact**: Redundant processing
   - **Solution**: Remove duplicate block

3. **Missing Validation**
   - **Issue**: No validation for required fields in frontend
   - **Impact**: Database errors if critical fields are empty
   - **Solution**: Add proper validation before processing

4. **Branch Security**
   - **Issue**: Branch filtering can be bypassed in some queries
   - **Location**: Various query functions
   - **Impact**: Users might see employees from other branches
   - **Solution**: Ensure consistent branch filtering

### PHP 8.2 Compatibility

1. **Object Initialization**
   - All objects properly initialized before property assignment
   - No "attempt to assign property on null" errors

2. **Type Safety**
   - Proper float casting for numeric fields
   - Safe array handling for POST data

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Database configuration
- `../public/include_dao.php` - DAO includes
- `../library/uploadImages.php` - File upload handling
- `dailyentryfun.php` - Daily entry functions

### Required DAOs
- `EmployeeDAO` - Main employee operations
- `EmployeeMySqlExtDAO` - Extended employee queries
- `EmployeegroupDAO` - Employee group management
- `EmployeesubgroupDAO` - Sub-group management
- `EmployeepersonnelDAO` - Employee history/transactions
- `UserDAO` - User management
- `CountryDAO` - Country lookup
- `ReligionsMySqlDAO` - Religion lookup
- `YoutubeLinkDAO` - Training video links

### Related Controllers
- Must work in coordination with attendance systems
- Integrates with payroll processing
- Links to accounting system through tree elements
- Connects to branch-based security system

### Template Files
- `employeeview/add.html` - Add employee form
- `employeeview/edit.html` - Edit employee form  
- `employeeview/show.html` - Employee listing
- `succes.html` - Success message
- `error.html` - Error message

### Key HR Features
- **Salary Management**: Base salary, allowances, bonuses tracking
- **Document Management**: 15+ document types (contract, ID, passport, etc.)
- **Attendance Integration**: 7-day schedule setup with flexible timing
- **Cost Calculations**: Automatic minute and day absence cost computation
- **Change Tracking**: Complete salary change audit trail
- **Branch Security**: Multi-branch organization support
- **Group Management**: Hierarchical employee categorization