# Employee Attendance Systems Controller Documentation

**File**: `/controllers/employeeAttendanceSystems.php`  
**Purpose**: Manages attendance system configurations and weekly schedules for employee groups  
**Last Updated**: December 20, 2024  
**Total Functions**: 4+  
**Lines of Code**: ~262

---

## 📋 Overview

The Employee Attendance Systems Controller manages the configuration and administration of attendance systems within the ERP. It handles:
- Attendance system creation and configuration
- Weekly schedule management for each system
- Penalty and discount structure setup
- Permission-based absence and lateness handling
- Multi-language support for weekdays
- CRUD operations for attendance systems
- Integration with RedBean ORM for week schedules

### Primary Functions
- [x] Create and configure attendance systems
- [x] Manage weekly work schedules
- [x] Set penalty rates for lateness and absences
- [x] Configure permission-based discounts
- [x] Define workday schedules per day of week
- [x] Edit and update existing systems
- [x] Delete attendance systems
- [x] Multi-language weekday support

### Related Controllers
- [employeeAttendance.php](employeeAttendance.md) - Real-time attendance tracking
- [EmployeeAttendanceExcelController.php](EmployeeAttendanceExcelController.md) - Excel attendance management
- [employeeController.php](employeeController.md) - Employee management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeeattendancesystem** | Attendance system configurations | id, name, numberOfMinutesOfDelayAllowed, takeVacationDays, various discount fields, userid, del, sysdate |
| **employeeattendancesystemweek** | Weekly schedule definitions | id, employeeattendancesystem_id, employee_id, attendancedaynum, attendancedayar, attendancedayen, attendancetime, departuretime, chosseday |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial video links | youtubelinkid, title, url |
| **user** | System users | userid, username |

---

## 🔑 Key Functions

### 1. **Default Action / show()** - System Management Interface
**Location**: Line 60  
**Purpose**: Display the main attendance system management interface

**Process Flow**:
1. Include authentication check
2. Set up Arabic weekday array
3. Assign week data to Smarty template
4. Display add form template

**Weekday Configuration**:
```php
$week = array(
    "7" => "السبت",   // Saturday
    "1" => "الاحد",    // Sunday  
    "2" => "الاثنين",  // Monday
    "3" => "الثلاثاء",  // Tuesday
    "4" => "الاربعاء", // Wednesday
    "5" => "الخميس",   // Thursday
    "6" => "الجمعه"    // Friday
);
```

---

### 2. **add()** - Create New Attendance System
**Location**: Line 150  
**Purpose**: Create a comprehensive attendance system with penalty structure and weekly schedule

**Function Signature**:
```php
function add() {
    global $employeeAttendanceSystem;
    global $employeeAttendanceSystemDAO;
}
```

**Process Flow**:
1. Populate attendance system object with penalty rates
2. Insert main system record
3. Create 7 weekly schedule records (one per day)
4. Link weekly records to main system

**Penalty Configuration Fields**:
- `numberOfMinutesOfDelayAllowed` - Grace period for lateness
- `takeVacationDays` - Vacation day allowance
- `halfHourLateWithPermissionDisount` - 30-min late with permission penalty
- `hourLateWithPermissionDisount` - 1-hour late with permission penalty
- `hourAndHalfLateWithPermissionDisount` - 1.5-hour late with permission penalty
- `twoHoursLateWithPermissionDisount` - 2-hour late with permission penalty
- `moreThanTwoHoursLateWithPermissionDisount` - >2-hour late with permission penalty
- `halfHourLateWithoutPermissionDisount` - 30-min late without permission penalty
- `hourLateWithoutPermissionDisount` - 1-hour late without permission penalty
- `hourAndHalfLateWithoutPermissionDisount` - 1.5-hour late without permission penalty
- `twoHoursLateWithoutPermissionDisount` - 2-hour late without permission penalty
- `moreThanTwoHoursLateWithoutPermissionDisount` - >2-hour late without permission penalty
- `halfHourPermissionDisount` - 30-min early leave penalty
- `hourPermissionDisount` - 1-hour early leave penalty
- `hourAndHalfPermissionDisount` - 1.5-hour early leave penalty
- `twoHoursPermissionDisount` - 2-hour early leave penalty
- `dayAbsenceWithPermissionDisount` - Full day absence with permission penalty
- `dayAbsenceWithoutPermissionDisount` - Full day absence without permission penalty
- `quarterHourLateWithPermissionDisount` - 15-min late with permission penalty
- `quarterHourLateWithoutPermissionDisount` - 15-min late without permission penalty
- `numberOfCountsOfDelayAllowed` - Number of allowed delays before penalty

**Weekly Schedule Creation**:
```php
for ($i = 1; $i < 8; $i++) {
    $attendancedaynum = (int)filter_input(INPUT_POST, 'attendancedaynum_' . $i);
    $attendancedayar = filter_input(INPUT_POST, 'attendancedayar_' . $i);
    $attendancetime = filter_input(INPUT_POST, 'attendancetime_' . $i);
    $departuretime = filter_input(INPUT_POST, 'departuretime_' . $i);
    $chosseday = filter_input(INPUT_POST, 'chosseday_' . $i);
    
    $week = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    
    $employeeattendancesystemweek = R::dispense('employeeattendancesystemweek');
    $employeeattendancesystemweek->attendancedaynum = $attendancedaynum;
    $employeeattendancesystemweek->attendancedayar = $attendancedayar;
    $employeeattendancesystemweek->attendancedayen = $week[$attendancedaynum - 1];
    $employeeattendancesystemweek->attendancetime = $attendancetime;
    $employeeattendancesystemweek->departuretime = $departuretime;
    $employeeattendancesystemweek->employeeattendancesystem_id = $employeeAttendanceid;
    $employeeattendancesystemweek->chosseday = $chosseday;
    $employeeattendancesystemweek->employee_id = 0;
    R::store($employeeattendancesystemweek);
}
```

---

### 3. **show()** - List All Attendance Systems
**Location**: Line 77  
**Purpose**: Display all configured attendance systems with management options

**Process Flow**:
1. Include authentication check
2. Query all non-deleted attendance systems
3. Load YouTube tutorial links
4. Assign data to template
5. Display via show.html template

---

### 4. **edit()** - Edit Existing Attendance System
**Location**: Line 102  
**Purpose**: Load and display attendance system for editing

**Process Flow**:
1. Get system ID from URL parameter
2. Load attendance system data
3. Load associated weekly schedule records
4. Assign data to edit template

**Weekly Schedule Loading**:
```php
$employeeattendancesystemweek = R::findAll(
    'employeeattendancesystemweek',
    'employeeattendancesystem_id = ? and employee_id = 0',
    [$id]
);
```

---

### 5. **update()** - Update Existing Attendance System
**Location**: Line 209  
**Purpose**: Update attendance system configuration and weekly schedules

**Process Flow**:
1. Load existing attendance system
2. Update penalty and configuration fields
3. Update associated weekly schedule records
4. Save changes to database

**Weekly Schedule Update**:
```php
for ($i = 1; $i < 8; $i++) {
    $employeeattendancesystemweekid = (int)filter_input(INPUT_POST, 'employeeattendancesystemweekid_' . $i);
    $attendancetime = filter_input(INPUT_POST, 'attendancetime_' . $i);
    $departuretime = filter_input(INPUT_POST, 'departuretime_' . $i);
    $chosseday = filter_input(INPUT_POST, 'chosseday_' . $i);

    $employeeattendancesystemweek = R::load('employeeattendancesystemweek', $employeeattendancesystemweekid);
    $employeeattendancesystemweek->attendancetime = $attendancetime;
    $employeeattendancesystemweek->departuretime = $departuretime;
    $employeeattendancesystemweek->chosseday = $chosseday;
    R::store($employeeattendancesystemweek);
}
```

---

### 6. **delete()** - Remove Attendance System
**Location**: Line 90  
**Purpose**: Delete attendance system by ID

**Process Flow**:
1. Get system ID from URL parameter
2. Call DAO delete method
3. Redirect to success/error page

---

## 🔄 Workflows

### Workflow 1: Creating New Attendance System
```
┌─────────────────────────────────────────────────────────────┐
│            START: Create Attendance System                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display System Configuration Form                      │
│     - Load weekday translations                            │
│     - Show penalty structure fields                        │
│     - Display weekly schedule grid                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Main System Configuration                      │
│     - Set system name and basic settings                   │
│     - Configure delay allowances                           │
│     - Set penalty rates for various scenarios              │
│     - Define vacation day allowances                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Weekly Schedule (7 days)                        │
│     FOR each day of week (1-7):                            │
│       │                                                     │
│       ├─→ Set day number and names (AR/EN)                │
│       ├─→ Configure attendance time                        │
│       ├─→ Configure departure time                         │
│       ├─→ Set work/non-work day flag                       │
│       └─→ Link to main attendance system                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Complete Configuration                             │
│     - Insert main system record                            │
│     - Insert 7 weekly schedule records                     │
│     - Set audit fields (userid, sysdate)                   │
│     - Redirect to success page                             │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Editing Attendance System
```
┌─────────────────────────────────────────────────────────────┐
│             START: Edit Attendance System                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Existing Configuration                            │
│     - Get system ID from URL parameter                     │
│     - Load main attendance system record                   │
│     - Load associated weekly schedule records              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Pre-filled Edit Form                          │
│     - Show current penalty configuration                   │
│     - Display current weekly schedule                      │
│     - Allow modification of all settings                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Updates                                         │
│     - Update main system configuration                     │
│     - Update weekly schedule records                       │
│     - Preserve existing IDs and relationships              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Changes                                           │
│     - Update system record via DAO                         │
│     - Update weekly records via RedBean                    │
│     - Update audit fields                                  │
│     - Redirect to success page                             │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display attendance system creation form |
| `do=add` | `add()` | Create new attendance system |
| `do=show` | List view | Display all attendance systems |
| `do=edit` | Edit form | Display edit form for specific system |
| `do=update` | `update()` | Update existing attendance system |
| `do=delete` | `delete()` | Delete attendance system |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Required Parameters by Action

**Edit System** (`do=edit`):
- `id` - Attendance system ID (integer)

**Update System** (`do=update`):
- `id` - System ID (hidden field)
- `numberOfMinutesOfDelayAllowed` - Grace period minutes
- `takeVacationDays` - Vacation day allowance
- Multiple penalty rate fields (float values)
- Weekly schedule fields per day (1-7):
  - `employeeattendancesystemweekid_{i}` - Week record ID
  - `attendancetime_{i}` - Start time
  - `departuretime_{i}` - End time  
  - `chosseday_{i}` - Work/non-work flag

**Delete System** (`do=delete`):
- `id` - System ID to delete

---

## 🧮 Calculation Methods

### Penalty Rate Configuration
```php
// Example penalty structure for various lateness scenarios
$employeeAttendanceSystem->halfHourLateWithoutPermissionDisount = (float) filter_input(INPUT_POST, 'halfHourLateWithoutPermissionDisount');
$employeeAttendanceSystem->hourLateWithoutPermissionDisount = (float) filter_input(INPUT_POST, 'hourLateWithoutPermissionDisount');
$employeeAttendanceSystem->hourAndHalfLateWithoutPermissionDisount = (float) filter_input(INPUT_POST, 'hourAndHalfLateWithoutPermissionDisount');
```

### Weekly Schedule Time Management
```php
// Default working hours (8:00 AM - 4:00 PM)
$timeNow = "08:00:00";
$timeNowsum8 = "16:00:00";

$smarty->assign('timeNow', $timeNow);
$smarty->assign('timeNowsum8', $timeNowsum8);
```

### Day Number to Name Mapping
```php
$week = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
$employeeattendancesystemweek->attendancedayen = $week[$attendancedaynum - 1];
```

---

## 🔒 Security & Permissions

### Authentication
- **Required for All Actions**: `include_once("../public/authentication.php")`
- **Session-based**: User must be logged in to access any functionality

### Input Validation
- **Type Casting**: Integer fields cast with `(int) filter_input()`
- **Float Validation**: Penalty amounts cast with `(float) filter_input()`
- **String Filtering**: Uses `filter_input()` for all POST data

### Database Security
- **Audit Trail**: All records include `userid` and `sysdate`
- **Soft Delete**: Uses `del` flag instead of hard deletion
- **Transaction Safety**: Try-catch blocks with redirection on error

---

## 📊 Performance Considerations

### Database Optimization
1. **Efficient Queries**:
   - Direct loads by ID for edit operations
   - Simple queries for non-deleted records
   - RedBean ORM for weekly schedule management

2. **Index Requirements**:
   - `employeeattendancesystem(id, del)`
   - `employeeattendancesystemweek(employeeattendancesystem_id, employee_id)`

### Known Performance Issues
- **No Pagination**: Show page loads all attendance systems
- **7 Insert Operations**: Weekly schedule requires 7 separate inserts
- **RedBean Overhead**: Mixed DAO/RedBean usage may have performance impact

---

## 🐛 Common Issues & Troubleshooting

### 1. **Weekly Schedule Not Created**
**Issue**: Attendance system created but weekly schedule missing  
**Cause**: Loop counter issue or POST data missing

**Debug**:
```php
// Check if all 7 days are processed
for ($i = 1; $i < 8; $i++) {
    echo "Processing day: " . $i . "<br>";
    // ... rest of loop
}
```

### 2. **Penalty Rates Not Saving**
**Issue**: Penalty amounts show as 0 or NULL  
**Cause**: Float conversion failure or field name mismatch

**Fix**:
```php
// Validate float conversion
$value = filter_input(INPUT_POST, 'halfHourLateWithoutPermissionDisount');
if ($value === false || $value === null) {
    $value = 0.0;
}
$employeeAttendanceSystem->halfHourLateWithoutPermissionDisount = (float) $value;
```

### 3. **Arabic Weekdays Not Displaying**
**Issue**: Weekday names show as question marks or corrupted  
**Cause**: Character encoding issue

**Fix**: Ensure UTF-8 encoding in templates and database:
```php
header('Content-Type: text/html; charset=UTF-8');
```

### 4. **Edit Form Not Loading Data**
**Issue**: Edit form shows empty fields  
**Cause**: System ID not passed correctly or record not found

**Debug**:
```php
$id = (int) $_GET['id'];
echo "Loading system ID: " . $id;
$loadData = $employeeAttendanceSystemDAO->load($id);
if (!$loadData) {
    echo "System not found!";
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Create Complete Attendance System
```
1. Access default form (no parameters)
2. Fill in system name and penalty rates
3. Configure weekly schedule for all 7 days
4. Submit form and verify creation
5. Check database for main record and 7 weekly records
6. Verify all penalty amounts saved correctly
```

### Test Case 2: Edit Existing System
```
1. Create test attendance system
2. Access edit form with system ID
3. Verify all fields pre-filled correctly
4. Modify penalty rates and weekly schedule
5. Submit update and verify changes saved
6. Check that weekly record IDs preserved
```

### Test Case 3: Weekly Schedule Configuration
```
1. Create system with mixed work/non-work days
2. Set different start/end times per day
3. Verify Arabic and English day names
4. Test with edge cases (midnight times, etc.)
5. Confirm schedule applied to employee groups
```

### Test Case 4: Penalty Structure Validation
```
1. Test with various penalty amount formats
2. Verify float conversion for different locales
3. Test extreme values (0, negative, very large)
4. Confirm penalty rates applied correctly in attendance
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeeAttendance.md](employeeAttendance.md) - Real-time attendance tracking
- [EmployeeAttendanceExcelController.md](EmployeeAttendanceExcelController.md) - Excel management
- [employeeController.md](employeeController.md) - Employee management

---

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