# Employee Daily Report Controller Documentation

**File**: `/controllers/employeedailyreport.php`  
**Purpose**: Generate comprehensive daily attendance reports for employees with filtering and analytics  
**Last Updated**: December 20, 2024  
**Total Functions**: 3+  
**Lines of Code**: ~148

---

## 📋 Overview

The Employee Daily Report Controller provides specialized reporting capabilities for employee attendance monitoring and daily workforce analytics. It handles:
- Individual employee attendance reports
- Date range filtering for attendance data
- Employee selection and filtering
- Absence tracking and reporting
- Branch-based employee filtering
- Multi-criteria attendance analytics
- Integration with attendance systems
- Report customization with time zones

### Primary Functions
- [x] Generate daily employee attendance reports
- [x] Filter employees by date ranges
- [x] Track employee absence patterns
- [x] Support branch-based filtering
- [x] Handle time zone adjustments
- [x] Provide absence status filtering
- [x] Integration with employee management
- [x] YouTube tutorial integration

### Related Controllers
- [employeeController.php](employeeController.md) - Employee management
- [employeeAttendance.php](employeeAttendance.md) - Attendance tracking
- [employeeendday.php](employeeendday.md) - End of day processing
- [employeereport.php](employeereport.md) - General employee reports

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employee** | Employee master data | employeeId, employeeName, employeeDate, branchid, conditions |
| **employeeattendance** | Attendance records | employeeId, employeeDate, attendanceTime, departureTime |

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

### Branch Management
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **branch** | Branch information | branchid, branchname, branchstatus |

---

## 🔑 Key Functions

### 1. **Default Action (empty $do)** - Initial Report Display
**Location**: Line 51-86  
**Purpose**: Display default employee daily report with current day data

**Function Signature**:
```php
// Triggered when: no action specified
// Access: Requires authentication
```

**Process Flow**:
1. Apply authentication check
2. Filter employees by branch (if branch-specific user)
3. Set default date range (current day)
4. Apply time zone adjustments from program settings
5. Query employee attendance data for the day
6. Load YouTube tutorial links
7. Display via employeedailyreportview/show.html

**Time Zone 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 +0 minutes', strtotime($endDate)));
    $startDate = date('Y-m-d', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
} else {
    $endDate = $endDate . ' 23:59:59';
    $startDate = $startDate . " 00:00:00";
}
```

**Features**:
- Automatic current day selection
- Branch-based employee filtering
- Time zone adjustment support
- Integration with program settings

---

### 2. **show()** - Custom Date Range Report
**Location**: Line 87-141  
**Purpose**: Generate employee attendance report for specific date range and employee

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

**Process Flow**:
1. Load all employees for dropdown (branch-filtered)
2. Parse input parameters for date range and employee selection
3. Apply time zone adjustments (with bug fix needed - see Issues section)
4. Build query string with filters:
   - Date range filter
   - Employee ID filter
   - Branch filter
5. Execute query with absence status filter
6. Display results with same template

**Parameter Handling**:
```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'];
```

**Absence Filtering**:
- $isAbsent = 0: Show present employees
- $isAbsent = 1: Show absent employees  
- Default: Show all employees

---

### 3. **queryAllByIdAndDate()** - Extended Query Function
**Location**: Line 134 (called from EmployeeMySqlExtDAO)  
**Purpose**: Execute complex attendance queries with multiple filters

**Function Call**:
```php
$employes = $employeeEX->queryAllByIdAndDate($queryString, $isAbsent);
```

**Features**:
- Supports complex WHERE clauses
- Absence status filtering
- Branch-based restrictions
- Date range filtering
- Employee-specific filtering

---

## 🔄 Workflows

### Workflow 1: Default Daily Report Generation
```
┌─────────────────────────────────────────────────────────────┐
│                START: Access Daily Report                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Authentication Check                                    │
│     - Verify user permissions                               │
│     - Load user session data                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Apply Branch Filtering                                  │
│     - Check if user has branch restrictions                 │
│     - Add branch filter to query string                    │
│     - Load branch-specific employees                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Set Default Date Range                                  │
│     - Use current date as start and end                    │
│     - Apply time zone adjustments from settings            │
│     - Format dates for SQL queries                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Query Employee Attendance Data                          │
│     - Execute queryAllString() for date range              │
│     - Load all employees for dropdown                      │
│     - Apply absence status if specified                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Generate Report Display                                 │
│     - Assign data to Smarty template                       │
│     - Load YouTube tutorial links                          │
│     - Display employeedailyreportview/show.html            │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Custom Date Range Report
```
┌─────────────────────────────────────────────────────────────┐
│            START: Custom Report Parameters                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Parse Input Parameters                                  │
│     - Extract from/to dates                                 │
│     - Get employee ID filter                               │
│     - Parse absence status filter                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Build Dynamic Query String                              │
│     - Add date range filter                                │
│     - Add employee filter if specified                     │
│     - Add branch filter if applicable                      │
│     - Add absence status filter                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Execute Attendance Query                                │
│     - Call queryAllByIdAndDate() with filters              │
│     - Process absence status logic                         │
│     - Apply time zone adjustments                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Display Filtered Results                                │
│     - Show attendance data for criteria                    │
│     - Maintain filter parameters in form                   │
│     - Provide export/print options                         │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| (empty) | Default action | Current day attendance report |
| `do=show` | show() | Custom date range and employee filter |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Required Parameters by Action

**Default Report** (no parameters):
- Uses current date automatically
- Shows all employees (branch-filtered)
- Uses default time zone settings

**Custom Report** (`do=show`):
- `from` - Start date (YYYY-MM-DD)
- `to` - End date (YYYY-MM-DD)  
- `chooseEmp` - Employee ID (optional)
- `isAbsent` - Absence filter (0=present, 1=absent, null=all)

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```
- All actions require valid user session
- Authentication check on every function call
- Session-based user identification

### Branch-Level Access Control
```php
if ($_SESSION['branchId'] > 0)
    $queryString = ' AND  branchid = ' . $_SESSION['branchId'];
```

**Access Levels**:
- Branch Manager: Can see all employees in their branch only
- Super Admin: Can see employees across all branches
- Regular User: Subject to branch restrictions

### Input Sanitization
- All `$_REQUEST` parameters filtered through framework
- Numeric IDs validated and cast to integers
- Date strings validated before SQL inclusion
- SQL injection prevented by DAO layer

---

## 🐛 Common Issues & Troubleshooting

### 1. **Time Zone Variable Bug**
**Issue**: Line 109 references undefined `$Programsettingdata`  
**Location**: Line 109-112  
**Problem Code**:
```php
if (isset($Programsettingdata->reportsPlusHours) && !empty($Programsettingdata->reportsPlusHours)) {
```

**Fix**:
```php
if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
```

### 2. **Duplicate Query Execution**
**Issue**: Lines 132 and 134 execute similar queries  
**Problem**: Inefficient database calls

**Fix**: Remove redundant query on line 132:
```php
// Remove this line:
// $employes = $employeeEX->queryAllString($startDate, $endDate);

// Keep only this line:
$employes = $employeeEX->queryAllByIdAndDate($queryString,$isAbsent);
```

### 3. **Missing Employee Data**
**Issue**: Reports show no employees when branch filtering is too restrictive  
**Debug Steps**:
1. Check `$_SESSION['branchId']` value
2. Verify employee.branchid assignments in database
3. Test query without branch filter

### 4. **Date Format Issues**
**Issue**: Time zone adjustments fail with invalid date formats  
**Solution**:
```php
// Validate date format before processing
if (!empty($startDate) && strtotime($startDate) !== false) {
    // Safe to process
}
```

---

## 📊 Performance Considerations

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

2. **Query Optimization**:
   - Use specific date ranges to limit result sets
   - Apply branch filtering early in queries
   - Consider pagination for large employee counts

### Memory Usage
- Large date ranges can return thousands of records
- Consider implementing pagination for reports > 100 employees
- Cache employee dropdown data for repeated usage

---

## 🧪 Testing Scenarios

### Test Case 1: Default Daily Report
```
1. Access controller without parameters
2. Verify current date is used
3. Check that branch filtering is applied
4. Confirm employee list is populated
5. Validate time zone adjustments
```

### Test Case 2: Date Range Filtering
```
1. Specify custom from/to dates
2. Test with various date formats
3. Verify time zone handling
4. Check edge cases (same day, future dates)
5. Test with empty date ranges
```

### Test Case 3: Employee Specific Report
```
1. Select specific employee from dropdown
2. Verify attendance data is employee-specific
3. Test with employees from different branches
4. Check absence status filtering
```

### Test Case 4: Branch Restrictions
```
1. Login as branch-restricted user
2. Verify only branch employees appear
3. Test as super admin (all branches)
4. Check query string construction
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeeController.md](employeeController.md) - Employee management
- [employeeAttendance.md](employeeAttendance.md) - Attendance tracking
- [Database Schema Documentation](#) - Table relationships

---

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