# Attendance Periods Migration Instructions

## ⚠️ Error Fix: getUserRole() undefined

**Error:** `Call to undefined function getUserRole()`

**Solution:** Use one of these methods:

---

## Method 1: Simple Migration (Recommended) ✅

### Steps:
```
1. Open browser
2. Go to: http://localhost/hrm2/database/run_migration_simple.php
3. Migration will run automatically (no login required)
4. Done! ✅
```

**Advantages:**
- No authentication required
- Simple and direct
- Works even if init.php has issues

---

## Method 2: phpMyAdmin (Manual) ✅

### Steps:
```
1. Open phpMyAdmin (http://localhost/phpmyadmin)
2. Select database: hrm2
3. Click "SQL" tab
4. Copy the SQL below and paste it
5. Click "Go"
6. Done! ✅
```

### SQL to Execute:

```sql
-- Create attendance_periods table
CREATE TABLE IF NOT EXISTS attendance_periods (
    period_id INT AUTO_INCREMENT PRIMARY KEY,
    site_id INT NOT NULL,
    attendance_month VARCHAR(10) NOT NULL COMMENT 'Format: Jan-25, Feb-25, etc.',
    period_display VARCHAR(50) NOT NULL COMMENT 'Format: January 2025, February 2025',
    employee_count INT DEFAULT 0 COMMENT 'Number of employees in this period',
    is_finalized TINYINT(1) DEFAULT 0 COMMENT '1 = Period is finalized/locked',
    created_by INT DEFAULT NULL COMMENT 'User ID who created this period',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    finalized_at TIMESTAMP NULL DEFAULT NULL,
    
    UNIQUE KEY unique_site_period (site_id, attendance_month),
    KEY idx_site_month (site_id, attendance_month),
    KEY idx_created_at (created_at),
    
    FOREIGN KEY (site_id) REFERENCES sites(site_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Migrate existing data from attendance_monthly_grid
INSERT INTO attendance_periods (site_id, attendance_month, period_display, employee_count, created_at)
SELECT 
    site_id,
    attendance_month,
    DATE_FORMAT(STR_TO_DATE(CONCAT('01-', attendance_month), '%d-%b-%y'), '%M %Y') as period_display,
    COUNT(DISTINCT employee_id) as employee_count,
    NOW() as created_at
FROM attendance_monthly_grid
GROUP BY site_id, attendance_month
ON DUPLICATE KEY UPDATE 
    employee_count = VALUES(employee_count);
```

---

## Method 3: Fixed Main Migration ✅

### If you still want to use the main migration file:

The file `run_attendance_periods_migration.php` has been fixed.

### Steps:
```
1. Make sure you're logged in to the HRM system first
2. Open: http://localhost/hrm2/database/run_attendance_periods_migration.php
3. Migration will run
4. Done! ✅
```

**What was fixed:**
- Removed dependency on `getUserRole()` function
- Added fallback authentication
- Now works with basic login only

---

## Verification Steps:

After running migration (any method):

### Check 1: Table Created
```
1. Open phpMyAdmin
2. Select database: hrm2
3. Look for table: attendance_periods
4. Should have columns: period_id, site_id, attendance_month, etc.
✅ Pass if table exists
```

### Check 2: Data Migrated
```
1. In phpMyAdmin, click on attendance_periods table
2. Click "Browse"
3. Should see rows with your existing attendance periods
✅ Pass if data visible
```

### Check 3: Attendance Module Works
```
1. Go to: http://localhost/hrm2/modules/attendance/attendance_excel_grid.php
2. Should load without errors
3. Select a period that exists
4. Should show: ✓ Data from database
✅ Pass if working correctly
```

---

## Troubleshooting:

### Issue 1: "Table already exists"
**Solution:** Table is already created, skip migration. Go directly to attendance module.

### Issue 2: "Foreign key constraint fails"
**Solution:** 
```sql
-- Run this first to disable foreign key checks
SET FOREIGN_KEY_CHECKS = 0;

-- Then run the CREATE TABLE statement

-- Then enable it back
SET FOREIGN_KEY_CHECKS = 1;
```

### Issue 3: "Sites table not found"
**Solution:** Remove the foreign key constraint from the SQL:
```sql
-- Remove this line:
FOREIGN KEY (site_id) REFERENCES sites(site_id) ON DELETE CASCADE
```

### Issue 4: Still getting getUserRole error
**Solution:** Use Method 1 (Simple Migration) or Method 2 (phpMyAdmin)

---

## Quick Reference:

### Files Created:
```
1. database/run_migration_simple.php
   → No authentication, direct migration

2. database/run_attendance_periods_migration.php
   → Fixed main migration file

3. database/migrations/create_attendance_periods_table.sql
   → SQL script for manual execution
```

### Which Method to Use?

**Use Method 1 (Simple Migration) if:**
- You're getting authentication errors
- You want quickest solution
- You don't care about security checks

**Use Method 2 (phpMyAdmin) if:**
- You prefer manual control
- You're familiar with phpMyAdmin
- Migration files not working

**Use Method 3 (Main Migration) if:**
- You want proper authentication
- You're logged in as admin
- Original file now works after fix

---

## Post-Migration:

After successful migration:

1. ✓ attendance_periods table created
2. ✓ Existing data migrated
3. ✓ System ready to use

### Next Steps:
```
1. Go to Attendance module
2. Test viewing existing periods
3. Test creating new periods
4. Everything should work! 🎉
```

---

## Example Output (Successful):

```
✓ SQL file loaded
✓ attendance_periods table created!
✓ Table verified

📊 Migrating existing data...
  ✓ Site 1: January 2025 (10 employees)
  ✓ Site 1: February 2025 (10 employees)
  ✓ Site 1: August 2025 (5 employees)
✓ Migrated 3 periods total

✅ MIGRATION COMPLETED!
```

---

**Choose any method that works for you!** 🚀

All methods achieve the same result - creating the attendance_periods table and migrating existing data.

