# Absent Report Controller Documentation

**File**: `/controllers/absentReportController.php`  
**Purpose**: Generates employee attendance and absence tracking reports  
**Last Updated**: December 20, 2024  
**Total Functions**: 0 (Main logic inline)  
**Lines of Code**: ~147

---

## 📋 Overview

The Absent Report Controller is a simple yet essential reporting module that tracks employee attendance and absence patterns. It provides:
- Employee daily attendance tracking
- Absence pattern analysis  
- Date range filtering for attendance reports
- Branch-based employee filtering
- Real-time attendance status display
- Employee selection and filtering capabilities
- Timezone-aware reporting
- Integration with employee management system

### Primary Functions
- [x] Display employee attendance reports
- [x] Track absence patterns by date range
- [x] Filter employees by branch assignment
- [x] Support date range selection for analysis
- [x] Provide employee selection dropdowns
- [x] Handle timezone adjustments for reports
- [x] Generate attendance summaries
- [x] Show current day attendance status

### Related Controllers
- [employeeController.php](#) - Employee management
- [userController.php](#) - User management
- [branchController.php](#) - Branch management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employee** | Employee master data | employeeId, employeename, branchid, employeeDate, status |

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

---

## 🔑 Key Functions

### 1. **Default Action** - Current Day Attendance
**Location**: Line 51-86  
**Purpose**: Display today's employee attendance status with default filtering

**Process Flow**:
1. Check branch permission restrictions
2. Load all employees for current branch
3. Set default date range to today
4. Apply timezone adjustments if configured
5. Load today's attendance data
6. Display via `absentReportview/show.html` template

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

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

**Timezone Handling**:
```php
$Programsetting = $ProgramsettingDAO->load(1);
if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
    $reportsPlusHours = $Programsetting->reportsPlusHours + 24;
    $endDate = date('Y-m-d', strtotime('+' . $reportsPlusHours . ' hour', strtotime($endDate)));
    $startDate = date('Y-m-d', strtotime('+' . $Programsetting->reportsPlusHours . ' hour', strtotime($startDate)));
}
```

---

### 2. **show Action** - Custom Date Range Report
**Location**: Line 87-137  
**Purpose**: Generate attendance report for specified date range and employee

**Function Signature**:
```php
// Triggered when: do=show
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$employeeId = $_REQUEST['chooseEmp'];
```

**Process Flow**:
1. Load employee dropdown data with branch filtering
2. Parse date range and employee selection parameters
3. Apply timezone adjustments to date range
4. Build query string with date and employee filters
5. Execute attendance query with filters
6. Display filtered results via template

**Query Building**:
```php
if (!empty($startDate) && !empty($endDate)) {
    $queryString .= ' AND employeeDate >= "' . $startDate . '" AND employeeDate <= "' . $endDate . '" ';
}

if (!empty($employeeId)) {
    $queryString .= ' AND employee.employeeId =' . $employeeId;
}

if ($_SESSION['branchId'] > 0)
    $queryString .= ' AND branchid = ' . $_SESSION['branchId'];
```

**Features**:
- Custom date range selection
- Individual employee filtering
- Branch-based access control
- Timezone-aware date processing

---

## 🔄 Workflows

### Workflow 1: Daily Attendance Check
```
┌─────────────────────────────────────────────────────────────┐
│                    START: Daily Attendance                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Initialize Default Parameters                           │
│     ├─ Set date range to today                             │
│     ├─ Check user's branch assignment                      │
│     └─ Load program timezone settings                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Apply Branch Filtering                                  │
│     ├─ Check if user assigned to specific branch           │
│     ├─ Build branch filter query string                    │
│     └─ Load employees for allowed branches                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Load Today's Employee Data                              │
│     ├─ Query employee table with date filter               │
│     ├─ Apply branch restrictions                           │
│     ├─ Load basic employee information                     │
│     └─ Include attendance status                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Load Today's Attendance Details                        │
│     ├─ Query detailed attendance records                   │
│     ├─ Apply same branch and date filters                  │
│     ├─ Load attendance status information                  │
│     └─ Calculate attendance statistics                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Generate Daily Report                                   │
│     ├─ Combine employee and attendance data                │
│     ├─ Assign data to template variables                   │
│     ├─ Include YouTube tutorial links                      │
│     └─ Display via show.html template                      │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Custom Date Range Analysis
```
┌─────────────────────────────────────────────────────────────┐
│                START: Date Range Selection                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Parse User Input Parameters                             │
│     ├─ Extract start and end dates                         │
│     ├─ Extract selected employee ID (optional)             │
│     ├─ Validate date formats                               │
│     └─ Check parameter completeness                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Apply Timezone Adjustments                             │
│     ├─ Load system timezone settings                       │
│     ├─ Calculate report hour offset                        │
│     ├─ Adjust start date with timezone                     │
│     ├─ Adjust end date with timezone                       │
│     └─ Format dates for database queries                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Build Dynamic Query Filters                            │
│     ├─ Add date range filter to query string               │
│     ├─ Add employee filter if specified                    │
│     ├─ Add branch filter based on user permissions         │
│     └─ Combine all filters into final query               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Execute Attendance Queries                             │
│     ├─ Query basic employee information                    │
│     ├─ Query detailed attendance records                   │
│     ├─ Apply all constructed filters                       │
│     └─ Load related employee data                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Generate Filtered Report                               │
│     ├─ Process attendance data                             │
│     ├─ Calculate absence patterns                          │
│     ├─ Assign processed data to templates                  │
│     └─ Display comprehensive attendance report             │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Today's attendance report |
| `do=show` | Custom filtering | Date range and employee filtered report |
| `do=sucess` | Template only | Success message display |
| `do=error` | Template only | Error message display |

### Required Parameters by Action

**Default Report** (no `do` parameter):
- No parameters required
- Uses today's date automatically
- Applies user's branch restrictions

**Custom Report** (`do=show`):
- `from` - Start date (optional, YYYY-MM-DD)
- `to` - End date (optional, YYYY-MM-DD)  
- `chooseEmp` - Employee ID filter (optional)

---

## 🧮 Calculation Methods

### Date Range Processing
```php
// Default to today if no dates provided
$startDate = date('Y-m-d');
$endDate = date('Y-m-d');

// Timezone adjustment
if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
    $reportsPlusHours = $Programsetting->reportsPlusHours + 24;
    $endDate = date('Y-m-d', strtotime('+' . $reportsPlusHours . ' hour', strtotime($endDate)));
    $startDate = date('Y-m-d', strtotime('+' . $Programsetting->reportsPlusHours . ' hour', strtotime($startDate)));
} else {
    $endDate = $endDate . ' 23:59:59';
    $startDate = $startDate . " 00:00:00";
}
```

### Branch Filtering
```php
$queryString = '';
if ($_SESSION['branchId'] > 0) {
    $queryString = ' AND branchid = ' . $_SESSION['branchId'];
}
```

### Query String Construction
```php
if (!empty($startDate) && !empty($endDate)) {
    $queryString .= ' AND employeeDate >= "' . $startDate . '" AND employeeDate <= "' . $endDate . '" ';
}

if (!empty($employeeId)) {
    $queryString .= ' AND employee.employeeId =' . $employeeId;
}
```

---

## 🔒 Security & Permissions

### Branch-Based Access Control
```php
// Users can only see employees from their assigned branch
if ($_SESSION['branchId'] > 0) {
    $queryString .= ' AND branchid = ' . $_SESSION['branchId'];
}
```

**Permission Model**:
- Users assigned to specific branches can only see those employees
- Users with `branchId = 0` or `NULL` can see all employees  
- Branch restrictions apply to both employee lists and attendance data

### Session Management
- Uses standard ERP session authentication
- Validates session before allowing access to reports
- Branch permissions enforced through session variables

### Input Validation
- Date format validation for start/end dates
- Employee ID validation and type casting
- Branch ID validation through session system
- SQL injection prevention through DAO layer

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Required Indexes**:
   - `employee(branchid, employeeDate)`
   - `employee(employeeId, employeeDate)`
   - `employee(branchid, employeeId)`

2. **Query Optimization**:
   - Use of date range indexes for efficient filtering
   - Branch filtering reduces dataset size
   - Simple queries minimize complexity

3. **Memory Management**:
   - Small dataset typically due to daily focus
   - Branch filtering limits result size
   - Minimal data processing required

### Known Performance Issues
```sql
-- Avoid functions in WHERE clauses for large datasets
-- BAD: WHERE DATE(employeeDate) = '2024-12-20'
-- GOOD: WHERE employeeDate >= '2024-12-20 00:00:00' AND employeeDate <= '2024-12-20 23:59:59'
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Employee Data**
**Issue**: Some employees don't appear in attendance reports  
**Cause**: Branch filtering or inactive employee status

**Debug**:
```sql
-- Check branch assignments
SELECT employeeId, employeename, branchid FROM employee WHERE branchid = [USER_BRANCH];

-- Check employee status
SELECT COUNT(*) FROM employee WHERE status = 0; -- Inactive employees
```

### 2. **Date Range Issues**
**Issue**: No data appears for valid date ranges  
**Cause**: Timezone configuration or date format problems

**Debug**:
```php
// Check timezone settings
$Programsetting = $ProgramsettingDAO->load(1);
echo "Report Plus Hours: " . $Programsetting->reportsPlusHours;

// Verify date format
echo "Start Date: " . $startDate . "<br>";
echo "End Date: " . $endDate . "<br>";
```

### 3. **Branch Permission Issues**
**Issue**: Users see employees from wrong branches  
**Cause**: Incorrect branch assignment in session

**Fix**:
```php
// Verify session branch assignment
if (!isset($_SESSION['branchId']) || $_SESSION['branchId'] <= 0) {
    // Handle missing or invalid branch assignment
    echo "Warning: No branch assigned to user";
}
```

### 4. **Empty Dropdown Lists**
**Issue**: Employee selection dropdown appears empty  
**Cause**: Overly restrictive branch filtering

**Debug**:
```sql
-- Check if branch has any employees
SELECT COUNT(*) FROM employee WHERE branchid = [BRANCH_ID];

-- Check employee status in branch
SELECT status, COUNT(*) FROM employee WHERE branchid = [BRANCH_ID] GROUP BY status;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Daily Attendance Report
```
1. Login as user assigned to specific branch
2. Access absent report controller without parameters
3. Verify only employees from user's branch appear
4. Check that today's date is used automatically
5. Confirm attendance data loads correctly
```

### Test Case 2: Date Range Filtering
```
1. Select custom date range (e.g., last week)
2. Choose specific employee from dropdown
3. Submit report and verify data filtering
4. Test edge cases (same start/end date, future dates)
5. Confirm timezone adjustments work correctly
```

### Test Case 3: Branch Permissions
```
1. Create test employees in different branches
2. Login as user assigned to Branch A
3. Verify only Branch A employees appear in reports
4. Test with user having no branch assignment
5. Confirm cross-branch access is properly restricted
```

### Debug Mode Enable
```php
// Add at top of controller for debugging
echo "Session Branch ID: " . $_SESSION['branchId'] . "<br>";
echo "Query String: " . $queryString . "<br>";
echo "Start Date: " . $startDate . " End Date: " . $endDate . "<br>";

// Debug employee loading
echo "Employees loaded: " . count($allemployee) . "<br>";
echo "Attendance records: " . count($employes) . "<br>";
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeeController.php](#) - Employee management
- [userController.php](#) - User management  
- [branchController.php](#) - Branch management
- [Database Schema Documentation](#) - Table relationships

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When attendance tracking requirements change