# Employee Personal Controller Documentation

**File**: `/controllers/employeePersonalController.php`  
**Purpose**: Manages employee financial transactions, loans, advances, deductions, and rewards  
**Last Updated**: December 19, 2024  
**Total Functions**: 13  
**Lines of Code**: ~1285

---

## 📋 Overview

The Employee Personal Controller is the core component for managing all employee financial transactions beyond basic salary. It handles:
- Employee advance payments (سلف)
- Loan disbursements and repayments
- Employee withdrawals and deductions
- Bonus and reward payments
- Penalty and fine processing
- Integration with payroll and accounting systems
- Cost center allocation for employee expenses
- Multi-payment method support (cash, bank, check)
- Real-time employee debt tracking
- Automated salary processing capabilities

### Primary Functions
- [x] Process employee advance payments
- [x] Manage loan disbursements and repayments
- [x] Handle employee withdrawals and deductions
- [x] Process bonuses and rewards
- [x] Apply penalties and fines
- [x] Track employee debt balances
- [x] Generate accounting entries for all transactions
- [x] Support multiple payment methods
- [x] Cost center allocation
- [x] Print transaction receipts
- [x] Automated salary processing
- [x] Branch-based transaction filtering

### Related Controllers
- [employeeController.php](employeeController.md) - Employee management
- [salaryReportController.php](salaryReportController.md) - Salary processing
- [EmployeeAttendanceController.php](EmployeeAttendanceController.md) - Attendance tracking
- [dailyentry.php](dailyentry.md) - Accounting entries
- [saveController.php](saveController.md) - Cash/bank management
- [accountstree.php](accountstree.md) - Chart of accounts
- [costcenterController.php](#) - Cost center management
- [bankController.php](bankController.md) - Bank account management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `employeepersonnel` | Employee financial transactions | `employeeid`, `employeepersonneltype`, `employeepersonnelvalue`, `empdeptbefor`, `empdeptafter` |
| `employee` | Employee debt tracking | `employeeId`, `empdept`, `employeeName` |
| `save` | Cash accounts for payments | `saveid`, `savename`, `savevalue`, `treeId` |
| `savedaily` | Daily cash movements | `saveid`, `savedailychangeamount`, `savedailychangetype` |
| `salaryreport` | Salary payment records | `employeeid`, `salarymonth`, `salaryreportnet` |

### Related Tables (References)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `dailyentry` | Accounting journal entries | `dailyentryid`, `entryComment`, `thedate` |
| `dailyentrycreditor` | Credit side of entries | `dailyentryid`, `accountstreeid`, `value` |
| `dailyentrydebtor` | Debit side of entries | `dailyentryid`, `accountstreeid`, `value` |
| `costcenter` | Cost center allocation | `costcenterid`, `costcentername` |
| `costcenterdetail` | Cost center transaction details | `costcenterid`, `modelid`, `costamount` |
| `bankaccount` | Bank account information | `bankaccountid`, `treeId`, `accountname` |

### Reference Tables (Lookups)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `programsettings` | System configuration | `settingName`, `settingValue` |
| `bank` | Bank master data | `bankid`, `bankname` |
| `user` | User information for audit | `userid`, `username`, `saveids` |
| `branch` | Branch filtering | `branchId`, `branchName` |

---

## 🔧 Key Functions

### Transaction Type Constants
```php
// Employee Personnel Transaction Types
const TRANSACTION_TYPES = [
    1 => 'Bonus/Reward',           // مكافأة
    2 => 'Deduction/Fine',         // خصم/غرامة  
    3 => 'Withdrawal',             // سحب
    4 => 'Advance/Loan',           // سلفة
    5 => 'Absence Deduction',      // خصم غياب
    6 => 'Loan Repayment',         // سداد سلفة
    7 => 'Permission Deduction',   // خصم إذن
    8 => 'Debt Adjustment',        // تعديل رصيد
    9 => 'Late Penalty',           // خصم تأخير
    10 => 'Salary Receipt',        // قبض راتب
    11 => 'Extra Allowance',       // بدل إضافي
    12 => 'Overtime',              // إضافي
    13 => 'Holiday Work',          // عمل عطلة
    14 => 'Leave Deduction',       // خصم إجازة
    15 => 'Salary Change Record'   // تسجيل تغيير راتب
];
```

### Main Controller Actions

#### **Default Action (Transaction Entry Form)**
```php
if (!isset($_GET['do'])) // Line 179
```
- **Purpose**: Display employee transaction entry form
- **Process Flow**:
```
┌─ Load Form Data ──────┐
│ • Cost centers        │
│ • Cash accounts       │
│ • Bank accounts       │
│ • Active employees    │
│ • Current date/time   │
└───────────────────────┘
       ▼
┌─ Apply Branch Filter ─┐
│ Filter employees by   │
│ user's branch access  │
└───────────────────────┘
       ▼
┌─ Display Form ────────┐
│ employeePersonalview/ │
│ add.html              │
└───────────────────────┘
```

#### **Add Transaction**
```php
elseif ($do == "add") // Line 203
```
- **Purpose**: Process new employee financial transaction
- **Parameters** (from $_POST):
  - `type`: Transaction type (1-15)
  - `empName`: Employee ID
  - `empValue`: Transaction amount
  - `paymethod`: Payment method (0=cash, 1=bank)
  - `employeepersonneldate`: Transaction date
  - `desc`: Transaction description
  - `saveid`: Cash account ID (if cash payment)
  - `bankid`, `bankaccountid`, `checkNo`: Bank details (if bank payment)
  - `Costcenterid`: Cost center for allocation
  - `netSalary`: Employee's current net salary

- **Process Flow**:
```
┌─ Determine Transaction ─┐
│ Type and validation     │
└─────────────────────────┘
       ▼
┌─ Check Net Salary ─────┐
│ For advance transactions│
│ validate against        │
│ available net salary    │
└─────────────────────────┘
       ▼
┌─ Split Transaction ────┐
│ If amount > net salary: │
│ • Current month part   │
│ • Next month part      │
└─────────────────────────┘
       ▼
┌─ Process Payment ──────┐
│ Call add() function    │
│ with transaction data  │
└─────────────────────────┘
       ▼
┌─ Generate Receipt ─────┐
│ Optional print receipt │
│ or redirect to success │
└─────────────────────────┘
```

### Core Business Functions

#### **add() Function**
```php
function add($employeepersonnelvalue, $saveInNextMonth = 0, $paymethod = 0, 
    $employeepersonneltype = 0, $deviceid = '01', $employeeid, 
    $employeepersonneldate, $userid = 0, $saveid = 0) // Line 826
```
- **Purpose**: Core function to process employee financial transaction
- **Parameters**:
  - `$employeepersonnelvalue`: Transaction amount
  - `$saveInNextMonth`: Flag for next month processing
  - `$paymethod`: Payment method (0=cash, 1=bank)
  - `$employeepersonneltype`: Transaction type
  - `$deviceid`: Device/source identifier
  - `$employeeid`: Employee ID
  - `$employeepersonneldate`: Transaction date
  - `$userid`: User performing transaction
  - `$saveid`: Cash/bank account ID

- **Process Flow**:
```
┌─ Setup Transaction ────┐
│ • Create personnel rec │
│ • Set basic details    │
│ • Determine payment    │
│   method details       │
└────────────────────────┘
       ▼
┌─ Update Employee Debt ─┐
│ For debt-affecting     │
│ transaction types:     │
│ • Advances (type 4)    │
│ • Repayments (type 6)  │
│ • Debt adjustments     │
└────────────────────────┘
       ▼
┌─ Process Payment ──────┐
│ • Update cash/bank     │
│   account balances     │
│ • Create daily cash    │
│   movement records     │
└────────────────────────┘
       ▼
┌─ Cost Center Allocation┐
│ If cost center         │
│ specified, create      │
│ allocation record      │
└────────────────────────┘
       ▼
┌─ Generate Accounting ──┐
│ Create daily entry     │
│ with appropriate       │
│ debits and credits     │
└────────────────────────┘
```

- **Debt Calculation Logic**:
```php
// Advance/Loan (Type 4)
if ($employeepersonneltype == 4) {
    $empdeptafter = $empdept + $employeepersonnelvalue;
}
// Loan Repayment (Type 6) 
elseif ($employeepersonneltype == 6) {
    $empdeptafter = $empdept - $employeepersonnelvalue;
}
// Debt Adjustment (Type 8)
elseif ($employeepersonneltype == 8) {
    $empdeptafter = $employeepersonnelvalue; // Set absolute value
}
```

#### **show() Function**
```php
function show() // Line 458
```
- **Purpose**: Display employee transaction history with filtering
- **Features**:
  - Date range filtering
  - Employee-specific filtering
  - Transaction type filtering
  - Branch-based security
  - Pagination support

#### **delete() Function**  
```php
function delete() // Line 742
```
- **Purpose**: Reverse/cancel employee transaction
- **Process Flow**:
```
┌─ Load Transaction ─────┐
│ Get original personnel │
│ record details         │
└────────────────────────┘
       ▼
┌─ Reverse Debt Impact ──┐
│ Update employee debt   │
│ to pre-transaction     │
│ amount                 │
└────────────────────────┘
       ▼
┌─ Reverse Payment ──────┐
│ Add/subtract amount    │
│ back to cash/bank      │
│ account                │
└────────────────────────┘
       ▼
┌─ Reverse Accounting ───┐
│ Cancel daily entry     │
│ and related records    │
└────────────────────────┘
       ▼
┌─ Mark as Deleted ──────┐
│ Set conditions = 1     │
│ (soft delete)          │
└────────────────────────┘
```

#### **curlAddSalary() Function**
```php
function curlAddSalary($empid, $salarymonthdate, $Costcenterid) // Line 1261
```
- **Purpose**: Automated salary processing via internal API
- **Process**: Makes CURL request to salaryReportController for salary payment

#### **getEmployeeNetSalary() Function**
```php
function getEmployeeNetSalary($id) // Line 1135
```
- **Purpose**: Calculate employee's available net salary for advances
- **Calculation**:
```php
Net Salary = Base Salary + Bonuses + Allowances 
           - (Existing Advances + Deductions + Taxes)
           - Already Withdrawn This Month
```

### Utility Functions

#### **Cash Management Functions**
```php
function getSaveValueBefore($saveid)           // Get current balance
function updateSave($saveid, $savevalueafter)  // Update account balance
function insertSavedaily(...)                 // Record cash movement
```

#### **doEmployeePersonalDailyEntry() Function**
```php
function doEmployeePersonalDailyEntry($EmployeepersonnelId) // Line 1194
```
- **Purpose**: Generate accounting entries for employee transactions
- **Entry Types by Transaction**:
```
Advance (Type 4):
Dr: Employee Advance Account
Cr: Cash/Bank Account

Repayment (Type 6):  
Dr: Cash/Bank Account
Cr: Employee Advance Account

Bonus (Type 1):
Dr: Employee Account
Cr: Cash/Bank Account

Deduction (Type 2):
Dr: Cash/Bank Account  
Cr: Employee Account
```

---

## 🔄 Business Logic Flow

### Employee Advance Processing Workflow
```
┌─ START: Employee Advance ─┐
│                           │
▼                           │
┌─ Employee Requests ───────┐│
│ Advance amount            ││
└───────────────────────────┘│
       ▼                     │
┌─ Check Net Salary ────────┐│
│ Available balance for     ││
│ advance (current month)   ││
└───────────────────────────┘│
       ▼                     │
┌─ Split if Necessary ──────┐│
│ If amount > net salary:   ││
│ • Part from current month ││
│ • Part from next month    ││
└───────────────────────────┘│
       ▼                     │
┌─ Update Employee Debt ────┐│
│ empdept += advance_amount ││
└───────────────────────────┘│
       ▼                     │
┌─ Process Payment ─────────┐│
│ • Deduct from cash/bank   ││
│ • Create payment record   ││
│ • Generate receipt        ││
└───────────────────────────┘│
       ▼                     │
┌─ Create Accounting ───────┐│
│ Dr: Employee Advance A/c  ││
│ Cr: Cash/Bank Account     ││
└───────────────────────────┘│
       ▼                     │
┌─ Cost Center Allocation ──┐│
│ If specified, allocate    ││
│ to department/project     ││
└───────────────────────────┘│
       ▼                     │
┌─ END: Advance Processed ───┘
```

### Loan Repayment Processing
```
┌─ START: Loan Repayment ───┐
│                           │
▼                           │
┌─ Employee Payment ────────┐│
│ Repayment amount          ││
└───────────────────────────┘│
       ▼                     │
┌─ Validate Amount ─────────┐│
│ Check against outstanding ││
│ loan balance              ││
└───────────────────────────┘│
       ▼                     │
┌─ Receive Payment ─────────┐│
│ • Add to cash/bank account││
│ • Record transaction      ││
└───────────────────────────┘│
       ▼                     │
┌─ Update Employee Debt ────┐│
│ empdept -= repayment_amt  ││
└───────────────────────────┘│
       ▼                     │
┌─ Create Accounting ───────┐│
│ Dr: Cash/Bank Account     ││
│ Cr: Employee Advance A/c  ││
└───────────────────────────┘│
       ▼                     │
┌─ END: Repayment Complete ─┘
```

### Multi-Month Advance Logic
```
Requested Amount: $1000
Current Net Salary: $600

Processing:
┌─ Month 1 ─────────┐
│ Amount: $600      │
│ Source: Current   │
│ Net Salary        │
└───────────────────┘
       +
┌─ Month 2 ─────────┐  
│ Amount: $400      │
│ Source: Next      │
│ Month Salary      │
│ Flag: saveInNext  │
│ Month = 1         │
└───────────────────┘
```

---

## ⚠️ Common Issues

### Known Bugs & Limitations

1. **Salary Validation Logic**
   - **Issue**: Complex validation logic for advance amounts vs net salary
   - **Location**: Lines 233-241
   - **Impact**: May allow advances exceeding available salary in some cases
   - **Solution**: Implement more robust salary validation

2. **Transaction Splitting**
   - **Issue**: Multi-month transaction splitting may cause confusion
   - **Location**: add() function processing
   - **Impact**: Employees may not understand why advance is split
   - **Solution**: Add clear communication about split transactions

3. **Debt Calculation Race Conditions**
   - **Issue**: Multiple concurrent transactions may cause debt calculation errors
   - **Location**: Employee debt update operations
   - **Impact**: Incorrect debt balances
   - **Solution**: Implement transaction locking or atomic operations

4. **Payment Method Validation**
   - **Issue**: Insufficient validation for bank account details
   - **Location**: Bank payment processing
   - **Impact**: Invalid bank transactions may be recorded
   - **Solution**: Add comprehensive bank account validation

### 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 financial calculations
   - Safe array handling for transaction data

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Database configuration  
- `../public/include_dao.php` - DAO includes
- `initiateStaticSessionCommingWithCurl.php` - Session management
- `dailyentryfun.php` - Daily entry functions

### Required DAOs
- `EmployeepersonnelDAO` - Employee transaction records
- `EmployeeDAO` - Employee debt tracking
- `SaveDAO` - Cash account management
- `SavedailyDAO` - Daily cash movements  
- `BankaccountDAO` - Bank account operations
- `CostcenterDAO` - Cost center allocation
- `DailyentryDAO` - Accounting entries
- `SalaryreportDAO` - Salary processing

### Related Controllers
- Must coordinate with payroll system for salary deductions
- Integrates with accounting system for proper journal entries
- Works with cash management for payment processing
- Connects to cost center system for expense allocation

### Template Files
- `employeePersonalview/add.html` - Transaction entry form
- `employeePersonalview/showfinsh.html` - Transaction history
- `employeePersonalview/editprint.html` - Receipt printing
- `succes.html` - Success message
- `error.html` - Error message

### Key Financial Features
- **Multi-Type Transactions**: Support for 15+ transaction types including advances, loans, bonuses, deductions
- **Debt Tracking**: Real-time employee debt balance management with before/after tracking
- **Payment Flexibility**: Support for cash and bank payments with check handling
- **Smart Advance Logic**: Automatic splitting of advances across pay periods based on available net salary
- **Cost Center Integration**: Department/project-wise expense allocation for all transactions
- **Full Audit Trail**: Complete tracking of all financial transactions with user and timestamp
- **Accounting Integration**: Automatic journal entry generation for all transactions
- **Multi-Branch Support**: Branch-based filtering and access control
- **Receipt Generation**: Professional receipt printing for all transactions
- **Automated Processing**: Integration with automated salary processing systems