# Presence Report Controller Documentation

**File**: `/controllers/presenceReport.php`  
**Purpose**: Employee presence and login activity reporting system  
**Last Updated**: December 20, 2024  
**Total Functions**: 4  
**Lines of Code**: ~159

---

## 📋 Overview

The Presence Report Controller generates detailed reports on employee login activity and system presence tracking. It provides:
- Employee login/logout activity monitoring
- Date range filtering for activity reports
- User-specific presence tracking
- Grouped activity display by employee
- Login session analysis
- Employee attendance insights

### Primary Functions
- [x] Employee presence report generation
- [x] Date range filtering capabilities
- [x] User-specific activity filtering
- [x] Grouped activity display
- [x] Login session tracking
- [x] System access monitoring

### Related Controllers
- [movementmanageController.php](movementmanageController.md) - General movement tracking
- [employeeAttendance.php](employeeAttendance.md) - Employee attendance management
- [userController.php](userController.md) - User management
- [employeedailyreport.php](employeedailyreport.md) - Daily employee reports

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **movementmanage** | System access tracking | movementmanageid, userid, operationname, movementmanagedate |
| **user** | Employee/user master data | userid, username, employeename |

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

---

## 🔑 Key Functions

### 1. **Default Display / Presence Report Generator** - Main Report Interface
**Location**: Line 65  
**Purpose**: Generate employee presence reports with flexible filtering options

**Function Signature**:
```php
// Triggered when: empty($do) || $do == "show"
// Supports filtering by date range and user
```

**Process Flow**:
1. **Load User Data**: Get all active users for filtering dropdown
2. **Parse Filter Parameters**: Extract date range and user filters
3. **Build Query Conditions**: Construct SQL filters based on parameters
4. **Execute Main Query**: Retrieve login activity with user joins
5. **Group and Process Data**: Organize results by user and activity
6. **Display Results**: Show formatted report with activity details

**Filter Processing Logic**:
```php
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$userSearchId = $_REQUEST['usersearchid'];

$queryString = '';
if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
    $queryString .= ' and date(movementmanagedate) >= "' . $startDate . '" and date(movementmanagedate) <= "' . $endDate . '" ';
}

if ($userSearchId > 0) {
    $queryString .= ' and movementmanage.userid = ' . $userSearchId . ' ';
}

if (empty($queryString)) {
    $today = date("Y-m-d");
    $queryString = ' and date(movementmanagedate) >= "' . $today . '" and date(movementmanagedate) <= "' . $today . '" ';
}
```

**Main Query Structure**:
```sql
SELECT movementmanage.*, user.username
FROM movementmanage
JOIN user ON movementmanage.userid = user.userid
WHERE movementmanage.operationname = "index.php" 
AND movementmanage.userid > 0
[FILTER_CONDITIONS]
ORDER BY movementmanage.userid, movementmanage.movementmanageid
```

**Data Grouping**:
```php
$movementmanageData = customArrayManyIndexMany($movementmanageData, array('userid', 'username'));
// Groups results by user ID and includes username for easy access
```

---

### 2. **loadUser() / User Data Loading** - Employee List Provider
**Location**: Line 121  
**Purpose**: Load all active users for report filtering dropdown

**Function Signature**:
```php
function loadUser()
// Returns: Array of active user objects (conditions=0)
```

**Implementation**:
```php
$usersearchData = $myUserRecord->queryByConditions(0);
return $usersearchData;
```

---

### 3. **showByDate() / Date-Specific Reports** - Date Range Filtering
**Location**: Line 129  
**Purpose**: Generate reports for specific date ranges (helper function)

**Function Signature**:
```php
function showByDate($startDate, $endDate)
// Used for date-specific report generation
```

**Process Flow**:
1. Query movement data for date range
2. Filter by operation name ('index.php' for logins)
3. Assign data to template for display

---

### 4. **showByUser() / User-Specific Reports** - Individual Employee Reports
**Location**: Line 139  
**Purpose**: Generate reports for specific employees

**Function Signature**:
```php
function showByUser($userSearchId)
// Generates grouped report for single user
```

**Features**:
- Grouped activity display
- Operation-specific filtering
- User-centric data organization

---

## 🔄 Workflows

### Workflow 1: Employee Presence Report Generation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Access Presence Report                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Initialize Report Interface                             │
│     - Load all active users for dropdown                   │
│     - Display filter options (date range, user)           │
│     - Show current filter status                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Filter Parameters                               │
│     ┌─────────────────────────────────────────────────────┐ │
│     │  Date Range Filter:                                 │ │
│     │  - Parse start and end dates                       │ │
│     │  - Validate date format                            │ │
│     │  - Generate filter message                         │ │
│     └─────────────────────────────────────────────────────┘ │
│     ┌─────────────────────────────────────────────────────┐ │
│     │  User Filter:                                       │ │
│     │  - Check for specific user ID                      │ │
│     │  - Load user details for display                   │ │
│     │  - Generate user-specific message                  │ │
│     └─────────────────────────────────────────────────────┘ │
│     ┌─────────────────────────────────────────────────────┐ │
│     │  Default Behavior:                                  │ │
│     │  - If no filters, default to current day          │ │
│     │  - Generate appropriate filter message             │ │
│     └─────────────────────────────────────────────────────┘ │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Build and Execute Query                                 │
│     - Construct SQL with movement tracking joins           │
│     - Filter for login operations (index.php)             │
│     - Apply date and user filters                         │
│     - Order by user and chronological sequence            │
│     - Execute query and retrieve results                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Process and Group Results                              │
│     - Group login records by user ID                      │
│     - Include username for easy template access           │
│     - Organize chronologically within each user           │
│     - Calculate session patterns and frequencies          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Generate Report Display                                │
│     - Display filter status and date range                │
│     - Show grouped results by employee                    │
│     - Include login times and session information         │
│     - Provide navigation and tutorial links               │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Login Activity Tracking
```
┌─────────────────────────────────────────────────────────────┐
│             START: Employee System Login                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Login Event Occurs                                      │
│     - Employee accesses index.php (main system page)       │
│     - System captures login attempt                        │
│     - User authentication validates                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Movement Tracking Record Creation                       │
│     - Insert record into movementmanage table              │
│     - Set operationname = "index.php"                      │
│     - Record userid from session                           │
│     - Timestamp with movementmanagedate                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Presence Report Integration                             │
│     - Record becomes available for presence reports        │
│     - Can be filtered by date and user                     │
│     - Contributes to login pattern analysis               │
│     - Available for attendance tracking                   │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Main report | Employee presence report with filtering |

### Required Parameters by Action

**Presence Report** (empty or `do=show`):
- `from` (optional) - Start date filter (YYYY-MM-DD)
- `to` (optional) - End date filter (YYYY-MM-DD)
- `usersearchid` (optional) - Specific user ID filter

### Filter Behavior

**No Filters Provided**:
- Defaults to current day activity
- Shows all users who logged in today

**Date Range Only**:
- Shows activity for all users within date range
- Useful for period analysis

**User Only**:
- Shows all activity for specific user
- No date restrictions

**Date Range + User**:
- Most specific filtering
- Shows user activity within date range

---

## 🧮 Calculation Methods

### Date Range Construction
```php
// Date filter building
if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
    $queryString .= ' and date(movementmanagedate) >= "' . $startDate . '" and date(movementmanagedate) <= "' . $endDate . '" ';
}
```

### Default Date Handling
```php
// Default to current day if no filters
if (empty($queryString)) {
    $today = date("Y-m-d");
    $queryString = ' and date(movementmanagedate) >= "' . $today . '" and date(movementmanagedate) <= "' . $today . '" ';
}
```

### User-Specific Filtering
```php
// Add user filter if specified
if ($userSearchId > 0) {
    $queryString .= ' and movementmanage.userid = ' . $userSearchId . ' ';
}
```

### Data Grouping Algorithm
```php
// Group results for easy template access
$movementmanageData = customArrayManyIndexMany($movementmanageData, array('userid', 'username'));
// Creates structure: [userid1] => [username1] => [activity_records...]
//                   [userid2] => [username2] => [activity_records...]
```

---

## 🔒 Security & Permissions

### Authentication Requirements
- No explicit authentication checks visible
- Relies on framework-level session security
- Reports require valid user session

### Data Access Control
- Shows only login activity data
- No sensitive employee information exposed
- User filtering available to all users

### Input Validation
```php
$userSearchId = $_REQUEST['usersearchid']; // Should be cast to int
$startDate = $_REQUEST['from'];            // Should validate date format
$endDate = $_REQUEST['to'];                // Should validate date format
```

### Recommended Security Enhancements
```php
// Add input validation
$userSearchId = (int) $_REQUEST['usersearchid'];
$startDate = filter_var($_REQUEST['from'], FILTER_VALIDATE_REGEXP, array(
    "options" => array("regexp" => "/^\d{4}-\d{2}-\d{2}$/")
));
```

---

## 📊 Performance Considerations

### Database Optimization
1. **Required Indexes**:
   - `movementmanage(operationname, userid, movementmanagedate)` - Core filtering
   - `movementmanage(userid, movementmanagedate)` - User-specific queries
   - `user(userid, conditions)` - User joins

2. **Query Performance**:
   - Efficient JOIN between movementmanage and user tables
   - Date filtering using DATE() function (consider indexed date columns)
   - User filtering with direct userid comparison

3. **Data Volume Considerations**:
   - Movement tracking data grows continuously
   - Consider archiving old records
   - Implement pagination for large date ranges

### Query Optimization Opportunities
```sql
-- Current query uses DATE() function which prevents index usage
WHERE date(movementmanagedate) >= "2024-01-01"

-- Better approach with datetime comparison
WHERE movementmanagedate >= "2024-01-01 00:00:00" 
  AND movementmanagedate <= "2024-01-01 23:59:59"
```

### Memory Management
- Data grouping happens in PHP memory
- Large date ranges may consume significant memory
- Consider implementing result pagination

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Login Records**
**Issue**: Employee logins not appearing in reports  
**Cause**: Movement tracking not recording index.php access

**Debug**:
```sql
-- Check if movement records exist
SELECT COUNT(*) FROM movementmanage 
WHERE operationname = 'index.php' 
AND userid > 0 
AND DATE(movementmanagedate) = CURDATE();

-- Check specific user records
SELECT * FROM movementmanage 
WHERE userid = [USER_ID] 
ORDER BY movementmanagedate DESC 
LIMIT 10;
```

### 2. **Date Filter Not Working**
**Issue**: Date range filtering returns no results  
**Cause**: Date format mismatch or timezone issues

**Debug**:
```php
// Add date debugging
error_log("Date filter: FROM={$startDate}, TO={$endDate}");
error_log("Query string: " . $queryString);

// Test without date filtering
$testQuery = "SELECT COUNT(*) as total FROM movementmanage WHERE operationname = 'index.php'";
```

### 3. **User Grouping Issues**
**Issue**: Results not properly grouped by user  
**Cause**: customArrayManyIndexMany function errors

**Debug**:
```php
// Debug data structure before grouping
error_log("Raw data: " . print_r($movementmanageData, true));

// Test manual grouping
foreach ($movementmanageData as $record) {
    error_log("User ID: {$record['userid']}, Username: {$record['username']}");
}
```

### 4. **Performance Issues with Large Date Ranges**
**Issue**: Report loading slowly for large periods  
**Cause**: Too many records being processed

**Fix**:
```php
// Add record limits
$queryString .= " LIMIT 1000";

// Or implement pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 100;
$offset = ($page - 1) * $limit;
$queryString .= " LIMIT {$limit} OFFSET {$offset}";
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Report Generation
```
1. Access presence report (empty do)
2. Verify current day data loads by default
3. Check user dropdown populates correctly
4. Confirm report message displays properly
5. Verify tutorial videos load
```

### Test Case 2: Date Range Filtering
```
1. Select specific start and end dates
2. Submit report with date filter
3. Verify only records within range appear
4. Check filter message updates correctly
5. Test edge cases (same start/end date)
```

### Test Case 3: User-Specific Filtering
```
1. Select specific user from dropdown
2. Submit report with user filter
3. Verify only selected user's activity shows
4. Check user name appears in filter message
5. Test with user having no activity
```

### Test Case 4: Combined Filtering
```
1. Set both date range and specific user
2. Submit report with both filters
3. Verify results meet both criteria
4. Check filter message includes both filters
5. Test with combinations yielding no results
```

### Test Case 5: Edge Cases
```
1. Test with invalid date formats
2. Test with non-existent user IDs
3. Test with very large date ranges
4. Test with future date ranges
5. Verify proper error handling
```

### Debug Mode Enable
```php
// Add comprehensive logging
error_log("Presence Report - Filters: Date={$startDate} to {$endDate}, User={$userSearchId}");
error_log("Query: " . $finalQuery);
error_log("Results count: " . count($movementmanageData));

// Debug data structure
error_log("Grouped data structure: " . print_r($movementmanageData, true));
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [movementmanageController.md](movementmanageController.md) - Movement tracking system
- [employeeAttendance.md](employeeAttendance.md) - Employee attendance management
- [userController.md](userController.md) - User management system
- [employeedailyreport.md](employeedailyreport.md) - Daily employee reports

---

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