# March Salary Report Controller Documentation

**File**: `/controllers/marchSalaReport.php`  
**Purpose**: Generates detailed employee salary reports with allowances, deductions, and printing capabilities  
**Last Updated**: December 20, 2024  
**Total Functions**: 2 main actions  
**Lines of Code**: ~182

---

## 📋 Overview

The March Salary Report Controller (Employee Salary Report) provides comprehensive salary calculation and reporting functionality. It processes various salary components including base salary, bonuses, allowances, deductions, advances, and absences to generate detailed salary reports for individual employees with print-ready formatting.

### Primary Functions
- [x] Employee salary calculation and reporting
- [x] Multi-component salary breakdown analysis
- [x] Date range filtering for salary periods
- [x] Branch-based employee filtering
- [x] Detailed salary component tracking
- [x] Print-ready salary report generation
- [x] YouTube tutorial integration

### Related Controllers
- [employeeController.md](employeeController.md) - Employee management
- [employeePersonalController.md](employeePersonalController.md) - Employee personal records
- [salaryReportController.md](salaryReportController.md) - General salary reporting

---

## 🗄️ Database Tables

### Employee Management Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employee** | Employee master data | employeeid, employeeName, employeesalary, branchid, conditions |
| **employeepersonnel** | Employee salary components | employeepersonnelid, employeeid, employeepersonneltype, employeepersonnelvalue, employeepersonneldate, conditions |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **show / Default Action** - Salary Report Display
**Location**: Lines 52-144  
**Purpose**: Generate and display employee salary report with component breakdown

**Function Signature**:
```php
// Triggered when: empty $do or $do == "show"
$empid = filter_input(INPUT_POST, "chooseEmp");
$fromdate = filter_input(INPUT_POST, "fromdate");  
$todate = filter_input(INPUT_POST, "todate");
```

**Process Flow**:
1. **Branch Filtering**: Filter employees by user's branch
2. **Employee Selection**: Load employee dropdown for selection
3. **Date Range Processing**: Handle from/to date parameters
4. **Salary Calculation**: Process all salary components if employee selected
5. **Template Assignment**: Assign calculated values to display template

**Employee Filtering**:
```php
$queryString = '';
if ($_SESSION['branchId'] > 0)
    $queryString = ' AND branchid = ' . $_SESSION['branchId'];

$allemployee = $employeeEX->queryAllSimple($queryString);
```

**Salary Component Processing**:
```php
// Initialize salary component variables
$salary1 = $salary2 = $salary3 = $salary4 = $salary5 = $salary6 = $salary7 = $salary8 = '0';

// Process each personnel record for selected employee
foreach ($prsonalEmployee as $persData) {
    if ($persData['employeepersonneltype'] == 1 && $persData['conditions'] == 0) {
        $salary1 += $persData['employeepersonnelvalue']; // مكافاة (Bonus)
    } elseif ($persData['employeepersonneltype'] == 2 && $persData['conditions'] == 0) {
        $salary2 += $persData['employeepersonnelvalue']; // خصم (Deduction)
    }
    // ... additional component types
}
```

---

### 2. **editprint** - Print Format Generation  
**Location**: Lines 145-172  
**Purpose**: Generate print-ready salary report with complete calculations

**Function Signature**:
```php
// Triggered when: $do == 'editprint'
$empSalary = $_POST['empSalary'];           // Base salary
$fromdate = $_POST['fromdate'];             // Period start
$todate = $_POST['todate'];                 // Period end
$bonuses = $_POST['bonuses'];               // Bonuses
$houseAllowance = $_POST['houseAllowance']; // Housing allowance
// ... additional component inputs
```

**Calculation Logic**:
```php
// Total earnings calculation
$eradat = $bonuses + $houseAllowance + $payAdvances + 
          $transportationAllowance + $otherAllowance + $empSalary;

// Total deductions calculation  
$disc = $absence_delay + $discounts + $withdrawals + 
        $predecessor + $permission + $leave;

// Net salary calculation
$sub = $eradat - $disc;
```

**Print Data Array**:
```php
// Comprehensive salary data for printing
$prnData = array();
array_push($prnData, $empSalary, $bonuses, $houseAllowance, $payAdvances, 
          $transportationAllowance, $otherAllowance, $absence_delay, $discounts, 
          $withdrawals, $predecessor, $sub, $empName, $eradat, $disc, 
          $fromdate, $todate, $permission, $leave);
```

---

## 🗃️ Salary Component Types

### Component Type Mapping
| Type ID | Arabic Name | English Name | Description |
|---------|-------------|--------------|-------------|
| 1 | مكافاة | Bonus | Performance bonuses and incentives |
| 2 | خصم | Deduction | General deductions from salary |
| 3 | سحب | Withdrawal | Cash withdrawals against salary |
| 4 | سلفة | Advance | Salary advances given to employee |
| 5 | تأخير | Delay | Late arrival deductions |
| 7 | سداد سلفة من المرتب | Advance Repayment | Advance repayment from salary |
| 9 | غياب | Absence | Absence deductions |
| 11 | استئذان | Permission | Permission/leave deductions |
| 14 | انصراف | Early Leave | Early departure deductions |

---

## 🔄 Workflows

### Workflow 1: Salary Report Generation
```
┌─────────────────────────────────────────────────────────────┐
│           START: Access Salary Report Page                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Employee List                                      │
│     ├─→ Apply branch filtering based on user session       │
│     ├─→ Query employee records via queryAllSimple()        │
│     └─→ Assign employee dropdown to template               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Employee Selection (Optional)                           │
│     ├─→ User selects employee from dropdown                │
│     ├─→ User selects date range (from/to dates)           │
│     └─→ System loads selected employee data                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Salary Components                              │
│     IF employee selected:                                  │
│       ├─→ Query employeepersonnel table for date range    │
│       ├─→ Loop through each personnel record               │
│       ├─→ Categorize by component type (1-14)             │
│       ├─→ Sum amounts for each component category          │
│       └─→ Handle both date-filtered and all-time queries   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Calculate Final Totals                                 │
│     ├─→ Create salary array with 8 component totals       │
│     ├─→ Pass data to template for display                 │
│     └─→ Include YouTube tutorial links                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Display Salary Report                                  │
│     └─→ Show via marchesSalaries/show.html template       │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Print Report Generation
```
┌─────────────────────────────────────────────────────────────┐
│        START: User Clicks Print/Edit Print                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Collect Print Parameters                               │
│     ├─→ Base salary amount                                 │
│     ├─→ Date range (from/to)                              │
│     ├─→ All allowance amounts                              │
│     ├─→ All deduction amounts                              │
│     └─→ Employee ID for name lookup                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Perform Final Calculations                             │
│     ├─→ Total Earnings = Base + All Allowances            │
│     ├─→ Total Deductions = All Deduction Types            │
│     ├─→ Net Salary = Earnings - Deductions                │
│     └─→ Load employee name from database                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Generate Print Array                                   │
│     ├─→ Create comprehensive data array                    │
│     ├─→ Include all 18 salary components                  │
│     └─→ Format for print template                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Display Print View                                     │
│     └─→ Show via marchesSalaries/editprint.html           │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Default action | Display salary report form |
| `do=editprint` | Print generation | Generate print-ready salary report |
| `do=sucess` | Success page | Success confirmation |
| `do=error` | Error page | Error display |

### Required Parameters

**Salary Report** (`do=show`):
- `chooseEmp` - Employee ID (optional for dropdown only)
- `fromdate` - Start date (YYYY-MM-DD, optional)
- `todate` - End date (YYYY-MM-DD, optional)

**Print Report** (`do=editprint`):
- `emplId` - Employee ID
- `empSalary` - Base salary amount
- `fromdate` - Period start date
- `todate` - Period end date  
- `bonuses` - Bonus amount
- `houseAllowance` - Housing allowance
- `payAdvances` - Advance payments
- `transportationAllowance` - Transportation allowance
- `otherAllowance` - Other allowances
- `absence_delay` - Absence/delay deductions
- `discounts` - General discounts
- `withdrawals` - Withdrawals
- `predecessor` - Advance amounts
- `permission` - Permission deductions
- `leave` - Leave deductions

---

## 🧮 Calculation Methods

### Component Aggregation
```php
// Date-filtered calculation
if ($fromdate && $todate) {
    $todate = $todate . ' 23:59:59';
    $fromdate = $fromdate . " 00:00:00";
    $prsonalEmployee = R::getAll('SELECT * FROM employeepersonnel 
        WHERE employeeid = ' . $empid . ' 
        and employeepersonneldate >= "' . $fromdate . '" 
        AND employeepersonneldate <= "' . $todate . '"');
}

// Component type processing
foreach ($prsonalEmployee as $persData) {
    switch($persData['employeepersonneltype']) {
        case 1: $salary1 += $persData['employeepersonnelvalue']; break; // Bonus
        case 2: $salary2 += $persData['employeepersonnelvalue']; break; // Deduction
        // ... additional cases
    }
}
```

### Net Salary Calculation
```php
// Total earnings (all positive components)
$eradat = $bonuses + $houseAllowance + $payAdvances + 
          $transportationAllowance + $otherAllowance + $empSalary;

// Total deductions (all negative components)  
$disc = $absence_delay + $discounts + $withdrawals + 
        $predecessor + $permission + $leave;

// Net salary
$sub = $eradat - $disc;
```

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```
- All actions require valid user session
- No specific payroll permissions verified

### Branch Access Control
```php
// Users limited to their branch employees
if ($_SESSION['branchId'] > 0)
    $queryString = ' AND branchid = ' . $_SESSION['branchId'];
```

### Input Sanitization
- All inputs filtered via `filter_input()` functions
- Numeric values properly cast to prevent injection
- Date formats validated before database queries

---

## 📊 Performance Considerations

### Database Optimization
1. **Employee Queries**: Branch filtering improves performance
2. **Date Range Queries**: Indexed date fields important for large datasets
3. **Required Indexes**:
   - `employee(branchid, conditions)`
   - `employeepersonnel(employeeid, employeepersonneldate)`
   - `employeepersonnel(employeepersonneltype, conditions)`

### Query Efficiency
```sql
-- Optimized query with proper indexing
SELECT * FROM employeepersonnel 
WHERE employeeid = ? 
AND employeepersonneldate >= ? 
AND employeepersonneldate <= ?
AND conditions = 0

-- Index suggestion:
CREATE INDEX idx_emp_personnel_lookup ON employeepersonnel(employeeid, employeepersonneldate, conditions);
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Salary Components**
**Issue**: Employee salary components not appearing in report  
**Cause**: Date range too narrow or component records marked as deleted

**Debug**:
```sql
-- Check all personnel records for employee
SELECT employeepersonneltype, COUNT(*), SUM(employeepersonnelvalue)
FROM employeepersonnel 
WHERE employeeid = [ID] AND conditions = 0
GROUP BY employeepersonneltype;
```

### 2. **Incorrect Calculations**
**Issue**: Net salary doesn't match expected amount  
**Cause**: Missing component types or calculation errors

**Fix**:
```php
// Verify all component types are handled
$knownTypes = [1, 2, 3, 4, 5, 7, 9, 11, 14];
foreach ($prsonalEmployee as $record) {
    if (!in_array($record['employeepersonneltype'], $knownTypes)) {
        // Log unknown component type
        error_log("Unknown component type: " . $record['employeepersonneltype']);
    }
}
```

### 3. **Date Range Issues**
**Issue**: Report showing unexpected date ranges  
**Cause**: Date format issues or timezone problems

**Fix**:
```php
// Ensure proper date formatting
if ($fromdate && $todate) {
    $todate = $todate . ' 23:59:59';
    $fromdate = $fromdate . " 00:00:00";
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Salary Calculation
```
1. Create employee with base salary
2. Add various component types (bonus, deduction, etc.)
3. Run salary report for employee
4. Verify component totals and net salary calculation
```

### Test Case 2: Date Range Filtering
```
1. Create salary components across multiple months
2. Run report for specific month
3. Verify only components in date range included
4. Test edge cases (start/end of month)
```

### Test Case 3: Branch Access Control
```
1. Create employees in different branches
2. Login as branch-specific user
3. Verify only branch employees appear in dropdown
4. Test admin user sees all employees
```

### Test Case 4: Print Functionality
```
1. Complete salary report for employee
2. Navigate to print view
3. Verify all calculated values transfer correctly
4. Test print formatting and layout
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeeController.md](employeeController.md) - Employee management
- [employeePersonalController.md](employeePersonalController.md) - Personnel records
- [salaryReportController.md](salaryReportController.md) - General salary reporting

---

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