# Employee Doctor Controller Documentation

**File**: `/controllers/employeedoctorController.php`  
**Purpose**: Comprehensive employee and doctor advance/loan management with debt tracking and financial integration  
**Last Updated**: December 20, 2024  
**Total Functions**: 8+  
**Lines of Code**: ~697

---

## 📋 Overview

The Employee Doctor Controller is a sophisticated financial management module that handles employee and doctor advances, loans, and debt tracking. It provides:
- Employee and doctor advance/loan management
- Integrated debt tracking and change history
- Automatic accounting entries (journal entries)
- Cash register integration and management
- Payment processing (cash and salary deduction)
- Account tree integration for accounting
- Comprehensive audit trail for all transactions
- Multi-type expense categorization

### Primary Functions
- [x] Create employee/doctor records with initial advances
- [x] Process advance payments (cash or salary deduction)
- [x] Track debt changes with full audit trail
- [x] Integrate with accounting system (chart of accounts)
- [x] Manage cash register transactions
- [x] Generate debt change reports
- [x] Handle advance repayments
- [x] Delete and reverse transactions

### Related Controllers
- [employeeController.php](employeeController.md) - Employee management
- [savedailyController.php](savedailyController.md) - Cash register management
- [accountstree.php](accountstree.md) - Chart of accounts
- [dailyentry.php](dailyentry.md) - Journal entries

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeedoctor** | Employee/doctor master records | employeedoctorid, name, val, thetype, treeId, dailyentryid, userid, del |
| **employeedoctordebtandpay** | Advance/payment transactions | id, employeeOrDoctorId, val, thetype, paytype, saveid, dailyentryid |
| **employeedoctordebtchange** | Debt change audit trail | id, employeeOrDoctorId, debtchangebefore, debtchangeamount, debtchangeafter, debtchangetype |

### Financial Integration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **accountstree** | Chart of accounts | accountstreeid, accountstreename, parentid, accountstreetypeid |
| **dailyentry** | Journal entry headers | dailyentryid, entryComment, userid, sysdate |
| **dailyentrycreditor** | Journal entry credits | value, accountstreeid, dailyentryid |
| **dailyentrydebtor** | Journal entry debits | value, accountstreeid, dailyentryid |

### Cash Management Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Cash registers/safes | saveid, savename, savecurrentvalue, treeId |
| **savedaily** | Cash register transactions | savedailyid, saveid, savedailychangeamount, savedailychangetype, processname |

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

---

## 🔑 Key Functions

### 1. **add()** - Create Employee/Doctor with Initial Advance
**Location**: Line 273-359  
**Purpose**: Create new employee or doctor record with optional initial advance amount

**Function Signature**:
```php
function add()
// POST Parameters:
$name = $_POST["txtName"];
$debtVal = (float) $_POST["txtDebt"];
$thetype = (int) $_POST["thetype"]; // 0=employee, 1=doctor
```

**Process Flow**:
1. **Account Tree Integration**:
   ```php
   $parent = 63; //employee
   if ($thetype == 1) {
       $parent = 388; //doctor
   }
   $treeName = "سلفة " . $name;
   $treeId = addTreeElement($treeName, $parent, 3, 1, 1, '', 0, 0, 1);
   ```

2. **Journal Entry Creation** (if advance amount > 0):
   ```php
   if ($debtVal != 0) {
       // Debit: Employee/Doctor Account
       $dailyEntryDebtor->value = $debtVal;
       $dailyEntryDebtor->accountstreeid = $treeId;
       
       // Credit: Initial Balance Account
       $dailyEntryCreditor->value = $debtVal;
       $dailyEntryCreditor->accountstreeid = 121; // Opening balance account
   }
   ```

3. **Employee/Doctor Record Creation**:
   ```php
   $employeeDoctor->thetype = $thetype;
   $employeeDoctor->name = $name;
   $employeeDoctor->val = $debtVal; // Current debt amount
   $employeeDoctor->treeId = $treeId; // Link to chart of accounts
   $employeeDoctor->dailyentryid = $did; // Link to journal entry
   ```

4. **Debt Change Tracking**:
   ```php
   $employeeDoctorDebtChange->debtchangetype = 1; // Debt increase
   $employeeDoctorDebtChange->processname = 'اضافة موظف او طبيب';
   $employeeDoctorDebtChange->debtchangebefore = 0;
   $employeeDoctorDebtChange->debtchangeafter = $debtVal;
   ```

**Features**:
- Automatic chart of accounts integration
- Journal entry creation for accounting compliance
- Complete audit trail from creation
- Support for both employees and doctors

---

### 2. **savedebtandpay()** - Process Advance Payments
**Location**: Line 384-573  
**Purpose**: Process new advances or repayments for employees/doctors

**Function Signature**:
```php
function savedebtandpay()
// POST Parameters:
$thetype = (int) $_POST['thetype']; // 0=advance, 1=repayment
$employeeOrDoctor = (int) $_POST['employeeOrDoctor']; // 0=employee, 1=doctor
$employeeOrDoctorId = (int) $_POST['employeeOrDoctorId'];
$val = (float) $_POST['val'];
$comment = $_POST['comment'];
```

**Advance Processing** ($thetype = 0):
```php
if ($thetype == 0) { // Advance/Loan
    $saveid = (int) $_POST['saveidDebt'];
    
    // Journal Entry: Debit Employee, Credit Cash
    $dailyEntryDebtor->accountstreeid = $empDoc->treeId; // Employee account
    $dailyEntryCreditor->accountstreeid = $saveData->treeId; // Cash account
    
    // Update cash register
    $saveData->savecurrentvalue = $before - $val;
    
    // Update employee debt
    $empDoc->val += $val;
}
```

**Repayment Processing** ($thetype = 1):
```php
if ($thetype == 1) { // Repayment
    if ($paytype == 0) { // Cash payment
        // Debit Cash, Credit Employee
    } else if ($paytype == 1) { // Salary deduction
        // Debit Salary Expense, Credit Employee
        if ($employeeOrDoctor == 0) { // Employee
            $ogoorTreeId = 417; // General expenses
        } else { // Doctor  
            $ogoorTreeId = 416; // Doctor wages
        }
    }
}
```

**Debt Change Tracking**:
- Records before/after debt amounts
- Links to source transaction
- Maintains complete audit trail

---

### 3. **deletedebtandpay()** - Reverse Transactions
**Location**: Line 575-675  
**Purpose**: Delete and reverse advance/payment transactions

**Process Flow**:
1. Load original transaction
2. Reverse journal entry
3. Update cash register (opposite direction)
4. Update employee debt (opposite direction) 
5. Create debt change record for deletion
6. Mark transaction as deleted

**Reversal Logic**:
```php
if ($thetype == 0) { // Reversing advance
    // Add money back to cash register
    $after = $before + $val;
    // Reduce employee debt
    $empDoc->val -= $val;
} else if ($thetype == 1) { // Reversing repayment
    // Remove money from cash register  
    $after = $before - $val;
    // Increase employee debt
    $empDoc->val += $val;
}
```

---

### 4. **deleteFinaly()** - Complete Record Deletion
**Location**: Line 361-382  
**Purpose**: Permanently delete employee/doctor record and reverse all accounting

**Process Flow**:
1. Load employee/doctor record
2. Mark as deleted (del = 1)
3. Reverse original journal entry
4. Remove from chart of accounts
5. Update all related records

**Safety Features**:
- Transaction-based deletion
- Complete accounting reversal
- Audit trail preservation

---

### 5. **employeedoctordebtchange** Report
**Location**: Line 225-251  
**Purpose**: Generate debt change history reports for date ranges

**Features**:
- Date range filtering
- Employee/doctor specific reports
- Complete transaction history
- Audit trail display

---

## 🧮 Calculation Methods

### Debt Balance Calculation
```php
// For advances (increases debt)
$empDoc->val += $val;
$employeeDoctorDebtChange->debtchangetype = 0; // Increase

// For repayments (decreases debt)  
$empDoc->val -= $val;
$employeeDoctorDebtChange->debtchangetype = 1; // Decrease
```

### Cash Register Management
```php
// For advance payments (money out)
$before = $saveData->savecurrentvalue;
$after = $before - $val;
$savedailychangetype = 1; // Decrease

// For cash repayments (money in)
$after = $before + $val;
$savedailychangetype = 0; // Increase
```

### Journal Entry Logic
```php
// Advance Journal Entry:
// DR: Employee/Doctor Account (Asset/Receivable)
// CR: Cash Account (Asset)

// Cash Repayment Journal Entry:  
// DR: Cash Account (Asset)
// CR: Employee/Doctor Account (Asset/Receivable)

// Salary Repayment Journal Entry:
// DR: Salary Expense Account (Expense)
// CR: Employee/Doctor Account (Asset/Receivable)
```

---

## 🔄 Workflows

### Workflow 1: Employee Advance Processing
```
┌─────────────────────────────────────────────────────────────┐
│                START: Employee Advance Request              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Employee/Doctor & Amount                         │
│     - Choose from existing employee/doctor                  │
│     - Enter advance amount                                  │
│     - Select cash register for payment                     │
│     - Add comments/notes                                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Create Journal Entry                                    │
│     - DR: Employee/Doctor Account (increase receivable)    │
│     - CR: Cash Account (decrease cash)                     │
│     - Generate journal entry ID                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Cash Register                                    │
│     - Get current cash balance                              │
│     - Subtract advance amount                               │
│     - Create savedaily transaction record                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update Employee Debt                                    │
│     - Load current debt amount                              │
│     - Add new advance to total debt                        │
│     - Update employee record                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Create Debt Change Record                               │
│     - Record before/after debt amounts                     │
│     - Link to transaction and journal entry                │
│     - Create audit trail entry                             │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Advance Repayment Processing
```
┌─────────────────────────────────────────────────────────────┐
│              START: Advance Repayment                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Repayment Method                                 │
│     IF Cash Payment:                                        │
│       │ - Select cash register                             │
│       │ - Enter amount                                     │
│     ELSE Salary Deduction:                                 │
│       │ - Select expense account type                      │
│       │ - No cash register needed                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Create Appropriate Journal Entry                        │
│     IF Cash Payment:                                        │
│       │ DR: Cash Account, CR: Employee Account             │
│     ELSE Salary Deduction:                                 │
│       │ DR: Salary Expense, CR: Employee Account           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Cash Register (if cash payment)                 │
│     - Add repayment amount to cash balance                 │
│     - Create cash register transaction record              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Reduce Employee Debt                                    │
│     - Subtract repayment from total debt                   │
│     - Update employee record                                │
│     - Create debt change audit record                      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| (empty) | Default action | Add new employee/doctor form |
| `do=add` | `add()` | Create new employee/doctor record |
| `do=show` | Show listing | Display all employee/doctor records |
| `do=deleteFinaly` | `deleteFinaly()` | Permanently delete record |
| `do=debtandpay` | Payment form | Display advance/payment form |
| `do=savedebtandpay` | `savedebtandpay()` | Process advance/payment |
| `do=showdebtandpay` | Payment history | Show payment transaction history |
| `do=deletedebtandpay` | `deletedebtandpay()` | Delete payment transaction |
| `do=employeedoctordebtchange` | Debt report | Generate debt change reports |

### Required Parameters by Action

**Add Employee/Doctor** (`do=add`):
- `txtName` - Employee/doctor name
- `txtDebt` - Initial advance amount (optional)
- `thetype` - Type (0=employee, 1=doctor)

**Process Payment** (`do=savedebtandpay`):
- `thetype` - Transaction type (0=advance, 1=repayment)
- `employeeOrDoctor` - Person type (0=employee, 1=doctor)
- `employeeOrDoctorId` - Person ID
- `val` - Amount
- `comment` - Description
- `saveidDebt` - Cash register (for advances)
- `paytype` - Payment type (0=cash, 1=salary) for repayments

**Debt Change Report** (`do=employeedoctordebtchange`):
- `from` - Start date
- `to` - End date

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```
- All actions require valid user session
- User ID tracked in all transactions
- Session-based access control

### Transaction Security
```php
$mytransactions = new Transaction();
try {
    // Transaction operations
    $mytransactions->commit();
} catch (Exception $exc) {
    $mytransactions->rollback();
}
```

**Security Features**:
- Database transaction isolation
- Automatic rollback on errors
- Comprehensive audit trails
- User action tracking

### Input Sanitization
- Numeric values cast to appropriate types
- SQL injection prevented by DAO layer
- All financial amounts validated as float
- String inputs properly escaped

---

## 🐛 Common Issues & Troubleshooting

### 1. **Variable Initialization Issue**
**Issue**: Uninitialized global variables in functions  
**Location**: Multiple functions  
**Fix**: Initialize variables before use:
```php
global $dailyEntryDebtor, $dailyEntryCreditor;
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryCreditor = new Dailyentrycreditor();
```

### 2. **Chart of Accounts Dependencies**
**Issue**: Hard-coded account tree IDs may not exist  
**Accounts Used**:
- 63: Employee accounts parent
- 388: Doctor accounts parent  
- 121: Opening balance account
- 417: General employee expenses
- 415: Operating employee expenses
- 416: Doctor wages

**Fix**: Verify accounts exist before creating transactions

### 3. **Cash Register Balance Issues**
**Issue**: Negative cash balances when insufficient funds  
**Solution**: Add balance validation:
```php
if ($saveData->savecurrentvalue < $val) {
    throw new Exception("Insufficient cash in register");
}
```

### 4. **Debt Change Audit Trail Gaps**
**Issue**: Missing debt change records for some operations  
**Fix**: Ensure all debt-affecting operations call debt change creation

---

## 📊 Performance Considerations

### Database Optimization
1. **Required Indexes**:
   - `employeedoctor(userid, del)`
   - `employeedoctordebtandpay(employeeOrDoctorId, del)`
   - `employeedoctordebtchange(employeeOrDoctorId, debtchangedate)`

2. **Query Performance**:
   - Use prepared statements for repeated queries
   - Limit date range queries appropriately
   - Index foreign key relationships

### Memory Management
- Transaction objects properly managed
- Large result sets paginated
- Connection pooling for database access

---

## 🧪 Testing Scenarios

### Test Case 1: Employee Creation with Advance
```
1. Create employee with initial advance amount
2. Verify chart of accounts entry created
3. Check journal entry generation
4. Confirm debt change record
5. Validate accounting equation balance
```

### Test Case 2: Advance Payment Processing
```
1. Process advance for existing employee
2. Verify cash register balance decreases
3. Check employee debt increases
4. Confirm journal entry accuracy
5. Test insufficient funds scenario
```

### Test Case 3: Repayment via Salary Deduction
```
1. Process repayment via salary deduction
2. Verify no cash register impact
3. Check correct expense account debited
4. Confirm employee debt decreases
5. Validate audit trail creation
```

### Test Case 4: Transaction Reversal
```
1. Delete advance/payment transaction
2. Verify all accounting entries reversed
3. Check cash register restoration
4. Confirm debt amounts corrected
5. Validate audit trail preserved
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeeController.md](employeeController.md) - Employee management
- [accountstree.md](accountstree.md) - Chart of accounts
- [savedailyController.md](savedailyController.md) - Cash register management

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur