# Employee Attendance Controller Documentation

**File**: `/controllers/EmployeeAttendanceController.php`  
**Purpose**: Manages daily employee attendance tracking and time recording  
**Last Updated**: December 19, 2024  
**Total Functions**: 0 (Controller actions only)  
**Lines of Code**: ~202

---

## 📋 Overview

The Employee Attendance Controller handles daily attendance operations for tracking employee check-ins and check-outs. It provides:
- Daily attendance time recording (arrival/departure)
- Real-time attendance monitoring dashboard
- Employee attendance history management
- Integration with attendance calculation systems
- Branch-based attendance filtering
- Manual time entry and corrections
- Attendance system initialization for new periods
- AJAX-based time entry for seamless user experience

### Primary Functions
- [x] Display daily attendance dashboard
- [x] Record employee arrival times
- [x] Record employee departure times
- [x] View employee attendance history
- [x] Filter attendance by date and branch
- [x] Manual time entry and corrections
- [x] Initialize attendance for new periods
- [x] Real-time attendance updates via AJAX
- [x] Integration with fingerprint/RFID systems
- [x] Support for YouTube training links

### Related Controllers
- [employeeController.php](employeeController.md) - Employee management
- [salaryReportController.php](salaryReportController.md) - Salary calculations based on attendance
- [employeePersonalController.php](#) - Employee loans and advances
- [employeeAttendance.php](#) - Extended attendance features
- [EmployeeAttendanceExcelController.php](#) - Excel import/export
- [employeeendday.php](#) - End-of-day processing
- [absentReportController.php](#) - Absence reporting

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `employeeattendance` | Raw attendance records | `empid`, `sysdate`, `fingerid`, `rfid`, `accessType` |
| `employeeclosedayhistory` | Daily attendance summary | `employeeid`, `day`, `attendanceTime`, `departureTime`, `isAbsent` |
| `employee` | Employee master data | `employeeId`, `employeeName`, `branchid`, `conditions` |

### Related Tables (References)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `employeeattendancesystemweek` | Weekly schedule templates | `employee_id`, `attendancedaynum`, `attendancetime`, `departuretime` |
| `employeeattendancesystem` | Attendance system definitions | `id`, `systemName`, `description` |
| `branch` | Branch information for filtering | `branchId`, `branchName` |
| `user` | User information for audit | `userid`, `username` |

### Reference Tables (Lookups)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `youtubelink` | Training video links | `id`, `title`, `url`, `description` |

---

## 🔧 Key Functions

### Main Controller Actions

#### **Default Action (Show Attendance Dashboard)**
```php
if (empty($do) || $do == "show") // Line 84
```
- **Purpose**: Display daily attendance dashboard with all employees
- **Parameters**: 
  - `date` (POST): Target date for attendance (defaults to today)
- **Process Flow**:
```
┌─ Initialize Date ────┐
│ Default to today if  │
│ no date provided     │
└──────────────────────┘
       ▼
┌─ Apply Branch Filter ┐
│ Filter employees by  │
│ user's branch        │
└──────────────────────┘
       ▼
┌─ Load All Employees ─┐
│ queryAllemployeeby   │
│ condation(0)         │
└──────────────────────┘
       ▼
┌─ For Each Employee ──┐
│ • Load attendance    │
│ • Load daily history │
│ • Prepare time data  │
└──────────────────────┘
       ▼
┌─ Display Dashboard ──┐
│ employee_attendance_ │
│ view/add.html        │
└──────────────────────┘
```

- **Employee Data Processing**:
```php
foreach ($employees as $emp) {
    if ($emp->employeeId > 0) {
        // Build query for specific employee and date
        $queryString = " and empid = $emp->employeeId ";
        if ($date != '') {
            $queryString .= " and date(employeeattendance.sysdate) = '" . $date . "' ";
        }
        
        // Load raw attendance records
        $employeeAttendanceData = $employeeAttendanceEX->queryByQueryString($queryString);
        
        // Load daily summary
        $employeeClosedHistoryData = $employeeCloseDayHistoryEX
            ->getEmployeeHistoryByQueryString(" and employeeid = " . $emp->employeeId . 
            " and date(day) = '" . $date . "'");
        
        // Attach data to employee object
        $emp->attendanceData = $employeeClosedHistoryData;
    }
}
```

#### **Add Time Entry (AJAX)**
```php
elseif ($do == "addTime") // Line 139
```
- **Purpose**: Process attendance time entry via AJAX
- **Parameters** (from $_POST):
  - `empid` (int): Employee ID
  - `date` (string): Attendance date
  - `value` (string): Time value (HH:MM format)
  - `type` (string): "attend" or "depart"

- **Process Flow**:
```
┌─ Validate Input ─────┐
│ • Employee ID valid  │
│ • Date format valid  │
│ • Time format valid  │
│ • Type is valid      │
└──────────────────────┘
       ▼
┌─ Initialize Day ─────┐
│ If first attendance  │
│ of day, create day   │
│ record via           │
│ beginDayAttendance() │
└──────────────────────┘
       ▼
┌─ Check Entry Limit ──┐
│ If < 2 attendance    │
│ records exist,       │
│ create new raw       │
│ attendance record    │
└──────────────────────┘
       ▼
┌─ Update Daily Summary┐
│ • Load existing      │
│   history record     │
│ • Update attend/     │
│   depart time        │
│ • Clear absence flags│
│ • Save changes       │
└──────────────────────┘
       ▼
┌─ Return Status ──────┐
│ Echo 1 on success    │
│ Echo -1 on error     │
└──────────────────────┘
```

- **Code Example**:
```php
try {
    $empid = (int) filter_input(INPUT_POST, 'empid');
    $day = filter_input(INPUT_POST, 'date');
    $time = filter_input(INPUT_POST, 'value');
    $type = filter_input(INPUT_POST, 'type');

    // Ensure day attendance record exists
    if ((int) $employeeCloseDayHistoryEX->dayAttendanceCount($day) == 0) {
        $employeeCloseDayHistoryEX->beginDayAttendance($day, date('Y-m-d H:i:s'), $_SESSION['userid']);
    }

    // Check if we can add more attendance records (limit of 2)
    $employeeAttendanceData = $employeeAttendanceEX->queryByQueryString(
        " and empid = " . $empid . " and date(sysdate) = '" . $day . "'"
    );
    
    if (count($employeeAttendanceData) < 2) {
        // Create new raw attendance record
        $employeeAttendance->empid = $empid;
        $employeeAttendance->sysdate = date_format(date_create($day . ' ' . $time), 'Y-m-d H:i:s');
        $employeeAttendance->userid = $_SESSION['userid'];
        $id = $employeeAttendanceDAO->insert($employeeAttendance);
    }

    // Update daily summary record
    $row = $employeeCloseDayHistoryEX->getEmployeeHistoryByQueryString(
        " and employeeid=$empid and day='" . $day . "' and del = 0"
    );
    
    if (count($row) > 0) {
        $employeeCloseDayHistory = $row[0];
        if ($type == "attend") {
            $employeeCloseDayHistory->attendanceTime = $time;
        } else {
            $employeeCloseDayHistory->departureTime = $time;
        }
        $employeeCloseDayHistory->isAbsent = 0;
        $employeeCloseDayHistoryDAO->update($employeeCloseDayHistory);
    }
    
    echo 1; // Success
} catch (Exception $e) {
    echo -1; // Error
}
```

---

## 🔄 Business Logic Flow

### Daily Attendance Workflow
```
┌─ START: Daily Attendance ─┐
│                           │
▼                           │
┌─ Select Date ──────────┐  │
│ Default to current date │  │
└────────────────────────┘  │
       ▼                    │
┌─ Load Employee List ───┐  │
│ • Active employees     │  │
│ • Branch filtered      │  │
│ • Not deleted          │  │
└────────────────────────┘  │
       ▼                    │
┌─ For Each Employee ────┐  │
│ • Load daily schedule  │  │
│ • Check existing       │  │
│   attendance           │  │
│ • Load history data    │  │
└────────────────────────┘  │
       ▼                    │
┌─ Display Dashboard ────┐  │
│ • Employee list        │  │
│ • Time input fields    │  │
│ • Current status       │  │
│ • Action buttons       │  │
└────────────────────────┘  │
       ▼                    │
┌─ User Time Entry ──────┐  │
│ • Select employee      │  │
│ • Enter time           │  │
│ • Choose attend/depart │  │
│ • Submit via AJAX      │  │
└────────────────────────┘  │
       ▼                    │
┌─ Process Entry ────────┐  │
│ • Validate data        │  │
│ • Create/update records│  │
│ • Update status        │  │
└────────────────────────┘  │
       ▼                    │
┌─ END: Save Success ────────┘
```

### Time Entry Processing
```
┌─ Receive Time Entry ───┐
│ empid, date, time, type│
└────────────────────────┘
       ▼
┌─ Initialize Day ───────┐
│ Create day record if   │
│ first entry of the day │
└────────────────────────┘
       ▼
┌─ Check Entry Limit ────┐
│ Max 2 raw attendance   │
│ records per employee   │
│ per day                │
└────────────────────────┘
       ▼
┌─ Create Raw Record ────┐
│ employeeattendance     │
│ table with timestamp   │
│ and employee details   │
└────────────────────────┘
       ▼
┌─ Update Daily Summary ─┐
│ employeeclosedayhistory│
│ • attendanceTime       │
│ • departureTime        │
│ • Clear absence flags  │
└────────────────────────┘
       ▼
┌─ Return Response ──────┐
│ AJAX response:         │
│ 1 = Success           │
│ -1 = Error            │
└────────────────────────┘
```

### Attendance Data Structure
```
Employee Daily Attendance:
┌─ Raw Records ────────────┐
│ Table: employeeattendance│
│ • First punch (IN)       │
│ • Second punch (OUT)     │
│ • Timestamp exact        │
│ • Source device info     │
└──────────────────────────┘
       ▼
┌─ Daily Summary ──────────┐
│ Table: employeeclosed... │
│ • Start time (HH:MM)     │
│ • End time (HH:MM)       │
│ • Absence flags          │
│ • Permission flags       │
│ • Daily totals           │
└──────────────────────────┘
       ▼
┌─ Schedule Template ──────┐
│ Table: employeeattend... │
│ systemweek               │
│ • Expected start time    │
│ • Expected end time      │
│ • Day of week            │
│ • Work day flag          │
└──────────────────────────┘
```

---

## ⚠️ Common Issues

### Known Bugs & Limitations

1. **Time Format Validation**
   - **Issue**: No client-side validation for time format
   - **Location**: AJAX time entry
   - **Impact**: Invalid time entries may cause database errors
   - **Solution**: Add time format validation before processing

2. **Attendance Limit Logic**
   - **Issue**: Hard-coded limit of 2 attendance records per day
   - **Location**: Line 154 (count check)
   - **Impact**: Cannot handle multiple in/out entries for breaks
   - **Solution**: Make attendance entry limit configurable

3. **Error Handling**
   - **Issue**: Generic error responses without specific error messages
   - **Location**: AJAX response handling
   - **Impact**: Difficult to diagnose attendance entry issues
   - **Solution**: Return specific error codes and messages

4. **Date Validation**
   - **Issue**: No validation for future dates or invalid date formats
   - **Location**: Date parameter processing
   - **Impact**: May allow invalid attendance entries
   - **Solution**: Add proper date validation

### PHP 8.2 Compatibility

1. **Object Initialization**
   - All objects properly initialized before use
   - No "attempt to assign property on null" errors

2. **Array Access Safety**
   - Safe array handling for attendance data processing
   - Proper count() usage with array checks

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations (conditionally loaded)
- `../public/config.php` - Database configuration
- `../public/include_dao.php` - DAO includes
- `../library/uploadImages.php` - File handling utilities
- `../library/num_to_ar.php` - Number to Arabic conversion
- `../library/Classes/PHPExcel/IOFactory.php` - Excel operations
- `dailyentryfun.php` - Daily entry functions

### Required DAOs
- `EmployeeattendanceDAO` - Raw attendance records
- `EmployeeclosedayhistoryDAO` - Daily attendance summaries
- `EmployeeDAO` - Employee master data
- `EmployeeMySqlExtDAO` - Extended employee queries
- `YoutubeLinkDAO` - Training video management
- `UserDAO` - User information for audit trail

### Related Controllers
- Must coordinate with employee management system
- Integrates with payroll calculations for attendance-based pay
- Works with absence tracking and reporting systems
- Connects to fingerprint/RFID attendance devices

### Template Files
- `employee_attendance_view/add.html` - Main attendance dashboard
- `succes.html` - Success message
- `error.html` - Error message
- `header.html` - Page header (conditionally loaded)
- `footer.html` - Page footer

### Key Attendance Features
- **Real-time Dashboard**: Live view of all employee attendance status
- **AJAX Time Entry**: Seamless time recording without page refresh
- **Branch Filtering**: Multi-branch organization support with proper access control
- **Dual Recording**: Both raw punch records and daily summaries for flexibility
- **Schedule Integration**: Links to employee weekly attendance schedules
- **Device Support**: Ready for integration with fingerprint and RFID devices
- **Training Integration**: YouTube video links for attendance system training
- **Audit Trail**: Complete tracking of who recorded what and when
- **Error Recovery**: Handles day initialization and duplicate entry scenarios
- **Time Correction**: Manual time entry and correction capabilities