# Employee Number Auto-Generation Feature

## Overview
This feature allows administrators to configure the system to automatically generate employee numbers with a custom prefix and format when creating new employees.

---

## Features

✅ **Toggle Auto-Generation** - Enable or disable automatic employee number generation
✅ **Custom Prefix** - Set your preferred prefix (e.g., EMP, STAFF, EMPL)
✅ **Starting Number** - Define where numbering should start
✅ **Number Padding** - Control the number of digits (e.g., 0001, 00001)
✅ **Live Preview** - See what the next employee number will look like
✅ **Manual Override** - Can still manually enter employee numbers when auto-generation is disabled

---

## Installation Steps

### Step 1: Run the SQL Script

Execute the SQL script to add the settings to your database:

```bash
# Using command line
mysql -u your_username -p your_database < EMPLOYEE_NUMBER_SETUP.sql

# Or copy and paste the contents of EMPLOYEE_NUMBER_SETUP.sql into phpMyAdmin
```

**Or manually execute this SQL:**

```sql
INSERT INTO `system_settings` (`key`, `value`, `type`, `description`, `is_public`, `created_at`, `updated_at`) VALUES
('enable_auto_employee_number', '1', 'boolean', 'Automatically generate employee numbers when creating new employees', 0, NOW(), NOW()),
('employee_number_prefix', 'EMP', 'string', 'Prefix for auto-generated employee numbers (e.g., EMP0001, STAFF0001)', 0, NOW(), NOW()),
('employee_number_start', '1', 'number', 'Starting number for auto-generated employee numbers', 0, NOW(), NOW()),
('employee_number_padding', '4', 'number', 'Number of digits for employee number (e.g., 4 = 0001, 5 = 00001)', 0, NOW(), NOW());
```

### Step 2: Clear Cache (Optional)

If your system uses caching, clear it:
- Go to **Settings > System Settings**
- Click the "Clear Cache" button

---

## Configuration

### Access the Settings

1. Log in as an administrator
2. Navigate to **Settings > System Settings**
3. Go to the **General** tab
4. Scroll to the **Employee Number** section

### Settings Explained

| Setting | Type | Description | Example |
|---------|------|-------------|---------|
| **Enable Auto Employee Number** | Toggle | Turn on/off automatic generation | ON/OFF |
| **Employee Number Prefix** | Text | Prefix for employee numbers | EMP, STAFF, EMPL |
| **Employee Number Start** | Number | Starting number for new employees | 1, 100, 1000 |
| **Employee Number Padding** | Number | Number of digits for padding | 4 (0001), 5 (00001) |

### Configuration Examples

**Example 1: Default Setup**
- Prefix: `EMP`
- Start: `1`
- Padding: `4`
- Result: `EMP0001`, `EMP0002`, `EMP0003`...

**Example 2: HR Department**
- Prefix: `HR`
- Start: `100`
- Padding: `4`
- Result: `HR0100`, `HR0101`, `HR0102`...

**Example 3: Large Organization**
- Prefix: `STAFF`
- Start: `1`
- Padding: `6`
- Result: `STAFF000001`, `STAFF000002`, `STAFF000003`...

**Example 4: No Prefix**
- Prefix: `` (empty)
- Start: `1`
- Padding: `5`
- Result: `00001`, `00002`, `00003`...

---

## How It Works

### When Auto-Generation is ENABLED:

1. **Creating New Employee**
   - Navigate to **Employees > Add New Employee**
   - The employee number field shows "Auto-Generated" badge
   - Field is pre-filled with the next number (readonly)
   - You cannot edit the employee number

2. **Number Generation Logic**
   - System finds the last employee number with the same prefix
   - Extracts the numeric part
   - Increments by 1
   - Formats with the specified padding
   - Combines with the prefix

3. **Example Flow**
   - Last employee: `EMP0005`
   - Next employee: `EMP0006`
   - Settings changed to `STAFF` prefix
   - Next employee: `STAFF0001` (starts fresh)

### When Auto-Generation is DISABLED:

1. **Creating New Employee**
   - Employee number field is editable
   - You must manually enter the employee number
   - Field shows "Enter employee number" placeholder
   - System validates for uniqueness

---

## Files Modified

### 1. Migration File (Optional)
**Location:** `app/Database/Migrations/2026-01-19-100000_AddEmployeeNumberSettings.php`

Adds the settings to the `system_settings` table.

### 2. Helper Functions
**Location:** `app/Helpers/employee_helper.php`

**Functions:**
- `generate_employee_number()` - Generates the next employee number
- `get_employee_number_settings()` - Returns current settings
- `preview_employee_number()` - Previews next number format

### 3. Employee Controller
**Location:** `app/Controllers/Employees/EmployeeController.php`

**Changes:**
- Loads employee helper
- Passes settings to create view
- Auto-generates number if enabled in `store()` method

### 4. System Settings Controller
**Location:** `app/Controllers/Settings/SystemSettingController.php`

**Changes:**
- Added employee number settings to General category

### 5. Employee Create View
**Location:** `app/Views/employees/create.php`

**Changes:**
- Shows "Auto-Generated" badge when enabled
- Makes field readonly when auto-generation is on
- Displays next employee number preview

### 6. System Settings View
**Location:** `app/Views/settings/system/index.php`

**Changes:**
- Added JavaScript for live preview
- Shows next employee number format as settings change

---

## Usage Examples

### Scenario 1: Starting Fresh

**Initial Setup:**
```
Prefix: EMP
Start: 1
Padding: 4
```

**Creating Employees:**
1. First employee: `EMP0001`
2. Second employee: `EMP0002`
3. Third employee: `EMP0003`

### Scenario 2: Changing Prefix Mid-Way

**Initial Setup:**
```
Prefix: EMP
Current last: EMP0050
```

**Change Settings:**
```
Prefix: STAFF
Start: 1
Padding: 4
```

**Result:**
- Next employee: `STAFF0001` (new sequence starts)
- Old employees keep `EMP####` format

### Scenario 3: Migrating from Manual Numbers

**Current State:**
- Employees manually numbered: E001, E002, E003

**Enable Auto-Generation:**
```
Prefix: E
Start: 1
Padding: 3
```

**Result:**
- System finds last: `E003`
- Next employee: `E004`
- Continues sequence automatically

---

## Troubleshooting

### Issue: Settings Not Showing

**Solution:**
1. Verify SQL was executed successfully
2. Check `system_settings` table has the 4 new records
3. Clear browser cache
4. Clear system cache

### Issue: Employee Number Not Auto-Generating

**Solution:**
1. Go to Settings > System Settings > General
2. Verify "Enable Auto Employee Number" toggle is ON
3. Check that prefix and padding values are valid
4. Try creating a new employee again

### Issue: Wrong Number Sequence

**Solution:**
1. Check the last employee in the database
2. The system reads the numeric part and adds 1
3. If sequence is wrong, adjust "Employee Number Start" setting
4. Create a test employee to verify

### Issue: Duplicate Employee Numbers

**Solution:**
- This should not happen as the system checks uniqueness
- If it does, there may be concurrent requests
- Report as a bug with steps to reproduce

---

## API Integration

The employee number generation also works with the API endpoint:

**Endpoint:** `POST /api/attendance/sync`

When auto-generation is enabled, the mobile app doesn't need to send an employee number - the system will generate it automatically.

---

## Best Practices

1. **Choose a Consistent Prefix**
   - Keep it short (2-5 characters)
   - Make it meaningful (EMP, HR, IT, SALES)
   - Avoid special characters

2. **Set Appropriate Padding**
   - Small org (< 100 employees): 3 digits
   - Medium org (< 1000 employees): 4 digits
   - Large org (> 1000 employees): 5-6 digits

3. **Starting Number**
   - Start from 1 for new systems
   - Start from higher number if migrating data
   - Leave room for growth

4. **Changing Settings**
   - Avoid changing prefix frequently
   - Old employees keep their numbers
   - New employees get new format
   - Document changes for audit trail

---

## Security & Permissions

- Only users with `edit-system-settings` permission can change these settings
- All changes are logged in the audit log
- Employee number generation happens server-side (secure)

---

## Future Enhancements

Potential improvements for future versions:

- Multiple numbering schemes per department
- Custom patterns (e.g., YEAR-PREFIX-NUMBER)
- Auto-increment per location
- Import/export employee number ranges
- Bulk renumbering tool

---

## Support

For issues or questions:
1. Check the system logs: `writable/logs/log-YYYY-MM-DD.log`
2. Review the audit logs in Settings > Audit Logs
3. Contact your system administrator

---

## Summary

This feature simplifies employee management by:
- Eliminating manual number entry
- Ensuring consistent formatting
- Preventing duplicate numbers
- Saving time when onboarding employees
- Providing flexibility with custom prefixes

**Next Steps:**
1. Run the SQL script to enable the feature
2. Configure your preferred settings
3. Create a test employee to verify it works
4. Enjoy automated employee numbering! 🎉
