# Gender Validation Issue Report - Mary Ward Enrollment Problem

## Executive Summary
Mary Ward (Female) was incorrectly enrolled in a Men's group event. Investigation reveals **NO gender validation exists** in the enrollment process.

## Root Cause
The enrollment code does NOT validate:
1. ❌ Member's gender against event's groupType (Men/Women/Mixed)
2. ❌ Member's group membership against event's assigned group
3. ✓ Only checks: already enrolled, capacity/waitlist

## Affected Enrollment Entry Points
The following files allow enrollment WITHOUT gender validation:

1. **event-member-form.php** (lines 84-165)
   - Admin "Add Member" function
   - User "Enrol me" function
   - Path: Manual enrollment via UI

2. **event-enrol-me.php** (lines 64-76)
   - Direct email enrollment link
   - Path: Email click-through enrollment

3. **event-enroll-confirm.php** (lines 71-91)
   - Email confirmation enrollment
   - Path: Email confirmation link

4. **event-participant-add.php**
   - Admin participant addition
   - Path: Admin panel

5. **event-auto-enroll.php**
   - Automatic enrollment system
   - Path: System auto-enrollment

6. **event-import-csv.php**
   - Bulk import from CSV/Excel
   - Path: Import functionality

## How to Trace Mary Ward's Enrollment

### Step 1: Check the Audit Log
Run the debug script we created:
```
http://your-domain/EP/debug-mary-ward-enrollment.php?EventId=49
```

This will show:
- Mary Ward's user details (ID, gender)
- All audit log entries (who enrolled her, when, from where)
- All events she's enrolled in (highlighting gender mismatches)
- Her group memberships

### Step 2: Check Audit Log Directly
Or query the audit log manually:
```
http://your-domain/EP/event-audit-log.php?search_user=WARD
```

### Step 3: Check Server Error Logs
The debug diagnostics log to PHP error log:
```bash
tail -f /var/log/apache2/error.log | grep "WARD"
tail -f /var/log/apache2/error.log | grep "Enrollment"
```

Look for entries like:
- `Enrollment Request - ParticipantName: WARD, MARY, EventId: XX`
- `Enrollment Success - ParticipantId: 1389, EventId: XX`

## What the Audit Log Will Show
The audit log captures:
- **Timestamp**: When enrollment occurred
- **Source**: How they were enrolled
  - "Self Enrollment" = User clicked "Enrol me"
  - "Email Confirmation" = Email link enrollment
  - "Admin Enrollment" = Admin added them
  - "Import" = CSV/Excel import
  - "Auto Enrollment" = System auto-enrolled
- **AdminUserId/AdminName**: Who performed the action
- **IpAddress**: Where the request came from
- **Referer**: Which page the request came from
- **UserAgent**: Browser/device used
- **Status**: SUCCESS/FAILED/PENDING

## Likely Enrollment Scenarios for Mary Ward

### Scenario 1: Admin Added Her Manually
- Admin opened event-participants.php
- Clicked "Add Member"
- Selected Mary Ward from dropdown
- System allowed enrollment without gender check

### Scenario 2: She Enrolled Herself
- Mary clicked "Enrol me" button
- System allowed enrollment (group membership check passed)
- No gender validation occurred

### Scenario 3: Email Link Enrollment
- Mary received event email
- Clicked enrollment link
- System auto-enrolled without gender check

### Scenario 4: CSV/Excel Import
- Admin imported participants from spreadsheet
- Mary's name was in the import file
- System imported without gender validation

## The Critical Missing Validation

### Current Code (event-member-form.php lines 84-165):
```php
// ❌ NO VALIDATION for gender or group type
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['participant_id'])) {
    $participantId = intval($_GET['participant_id']);
    
    // Only checks if already enrolled
    $checkStmt = $conn->prepare("SELECT 1 FROM EventUsers WHERE EventId = ? AND UserId = ?");
    // ...
    
    // Checks capacity only
    $capacity = checkEventCapacity($conn, $EventId);
    
    // ❌ INSERTS WITHOUT GENDER VALIDATION
    $stmt = $conn->prepare("INSERT INTO EventUsers ...");
}
```

### What Should Happen:
```php
// ✅ SHOULD CHECK GENDER vs GROUP TYPE
// Get event groupType
$eventStmt = $conn->prepare("SELECT groupType FROM Events WHERE id = ?");
$eventStmt->bind_param("i", $EventId);
$eventStmt->execute();
$eventStmt->bind_result($eventGroupType);
$eventStmt->fetch();
$eventStmt->close();

// Get user gender
$userStmt = $conn->prepare("SELECT gender FROM Users WHERE id = ?");
$userStmt->bind_param("i", $participantId);
$userStmt->execute();
$userStmt->bind_result($userGender);
$userStmt->fetch();
$userStmt->close();

// Validate gender against group type
if ($eventGroupType == 'Men' && $userGender != 'M') {
    error_log("Gender Validation Failed - Cannot enroll Female in Men's event");
    header("Location: event-participants.php?error=gender_mismatch&EventId=$EventId");
    exit();
}

if ($eventGroupType == 'Women' && $userGender != 'F') {
    error_log("Gender Validation Failed - Cannot enroll Male in Women's event");
    header("Location: event-participants.php?error=gender_mismatch&EventId=$EventId");
    exit();
}
```

## Group Membership Issue
From the screenshot, Mary Ward is shown as NOT being in the "fridayLadies" (Friday Roll Up) group. 

The current code DOES check group membership (lines 47-62 of event-member-form.php), but this only filters the dropdown list for admins. It doesn't prevent:
1. Direct URL manipulation (adding participant_id in GET parameter)
2. Email link enrollment
3. Import functionality
4. API/automated enrollment

## Recommendations

### Immediate Action
1. Run the debug script to identify HOW Mary Ward was enrolled
2. Check audit log for the enrollment source
3. Review server error logs for the enrollment timestamp

### Short-term Fix
1. Add gender validation to ALL enrollment entry points
2. Add proper error messages for gender mismatches
3. Prevent enrollment if gender doesn't match event type

### Long-term Solution
1. Create centralized enrollment validation function
2. All enrollment paths must call this validation
3. Log all validation failures to audit log
4. Add UI warnings before enrollment attempts

## Files That Need Gender Validation Added
1. event-member-form.php (line 85+)
2. event-enrol-me.php (line 65+)
3. event-enroll-confirm.php (line 71+)
4. event-participant-add.php
5. event-auto-enroll.php
6. event-import-csv.php
7. Any other enrollment entry points

## Next Steps
1. Run debug-mary-ward-enrollment.php to see HOW she was enrolled
2. Check audit log for the specific enrollment entry
3. Implement gender validation in all enrollment paths
4. Add gender mismatch error handling
5. Test with various enrollment scenarios

