# Participant Deletion Debugging Guide

## Issues Identified and Fixed

### 1. **Critical Issue: No Error Checking in Main Deletion Logic**

**Problem**: The main deletion file `event-user-delete.php` was not checking if the deletion actually succeeded.

**Original Code**:
```php
$sql = "DELETE FROM EventUsers WHERE id = $eventUserId";
$conn->query($sql);
// Always redirects with &deleted=1 regardless of success
```

**Fixed Code**:
```php
$stmt = $conn->prepare("DELETE FROM EventUsers WHERE id = ? AND EventId = ?");
$stmt->bind_param("ii", $eventUserId, $eventId);

if ($stmt->execute()) {
    $affectedRows = $stmt->affected_rows;
    if ($affectedRows > 0) {
        // Success - redirect with deleted=1
    } else {
        // No rows affected - participant not found
        header("Location: event-participants.php?EventId=$eventId&error=participant_not_found");
    }
} else {
    // Database error
    header("Location: event-participants.php?EventId=$eventId&error=deletion_failed&message=" . urlencode($error));
}
```

### 2. **Race Condition Protection**

**Added**: EventId validation in DELETE query to ensure we're only deleting participants from the correct event.

**Before**: `DELETE FROM EventUsers WHERE id = ?`
**After**: `DELETE FROM EventUsers WHERE id = ? AND EventId = ?`

### 3. **Improved Error Messages**

**Added new error types**:
- `participant_not_found`: When participant doesn't exist or already deleted
- `deletion_failed`: When database error occurs

### 4. **Fixed Debug Output**

**Problem**: `event-eventuser-delete.php` had debug output that could confuse users.

**Removed**: `echo "<br> $id DELETE FROM EventUsers WHERE id = ?";`

## How to Debug Future Issues

### 1. **Check Error Logs**
```bash
tail -f /var/log/apache2/error.log
# or
tail -f /var/log/nginx/error.log
```

### 2. **Enable PHP Error Logging**
Add to your PHP files for debugging:
```php
error_log("Debug: Attempting to delete participant ID: $eventUserId from Event: $eventId");
```

### 3. **Database Query Testing**
Test deletion queries directly in MySQL:
```sql
-- Check if participant exists
SELECT * FROM EventUsers WHERE id = ? AND EventId = ?;

-- Test deletion
DELETE FROM EventUsers WHERE id = ? AND EventId = ?;
SELECT ROW_COUNT(); -- Should return 1 if successful
```

### 4. **Common Scenarios That Cause Issues**

#### A. **Participant Already Deleted**
- **Symptom**: Success message but participant still visible
- **Cause**: Race condition or stale page cache
- **Fix**: Refresh page, check if participant actually exists

#### B. **Database Constraint Violation**
- **Symptom**: "Deletion failed" error
- **Cause**: Foreign key constraints or triggers
- **Fix**: Check database schema for constraints

#### C. **Permission Issues**
- **Symptom**: "Access denied" or silent failure
- **Cause**: User doesn't have permission to delete
- **Fix**: Check session privileges

#### D. **Invalid Parameters**
- **Symptom**: "Missing required parameters" error
- **Cause**: Malformed POST data or missing EventId
- **Fix**: Check form submission and URL parameters

### 5. **Monitoring and Prevention**

#### A. **Add Logging to Track Deletions**
```php
error_log("Participant deletion: UserID=$eventUserId, EventID=$eventId, DeletedBy=" . $_SESSION['userId']);
```

#### B. **Add Confirmation Before Deletion**
The system already has a modal confirmation, but you can add additional checks:
```php
// Verify participant exists before showing delete button
$checkStmt = $conn->prepare("SELECT id FROM EventUsers WHERE id = ? AND EventId = ?");
$checkStmt->bind_param("ii", $participantId, $eventId);
$checkStmt->execute();
$exists = $checkStmt->get_result()->num_rows > 0;
```

#### C. **Database Constraints Check**
```sql
-- Check for foreign key constraints
SELECT 
    CONSTRAINT_NAME,
    TABLE_NAME,
    COLUMN_NAME,
    REFERENCED_TABLE_NAME,
    REFERENCED_COLUMN_NAME
FROM information_schema.KEY_COLUMN_USAGE 
WHERE REFERENCED_TABLE_NAME = 'EventUsers';
```

## Testing the Fix

### 1. **Test Normal Deletion**
- Delete a participant that exists
- Should see "User deleted and confirmation email sent"

### 2. **Test Non-existent Participant**
- Try to delete a participant that doesn't exist
- Should see "Participant not found or already deleted"

### 3. **Test Database Error**
- Simulate database error (e.g., disconnect database)
- Should see "Failed to delete participant" with error details

### 4. **Test Race Condition**
- Have two users try to delete the same participant simultaneously
- One should succeed, one should get "participant not found"

## Additional Recommendations

### 1. **Add Soft Delete Option**
Consider implementing soft deletes instead of hard deletes:
```sql
ALTER TABLE EventUsers ADD COLUMN deleted_at TIMESTAMP NULL;
ALTER TABLE EventUsers ADD COLUMN deleted_by INT NULL;
```

### 2. **Add Audit Trail**
Track all deletion attempts:
```sql
CREATE TABLE EventUsersAudit (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_user_id INT,
    event_id INT,
    action VARCHAR(20),
    deleted_by INT,
    deleted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    delete_reason TEXT
);
```

### 3. **Improve Error Handling in Frontend**
Add JavaScript error handling for failed deletions:
```javascript
// In event-table.php
function handleDeleteError(response) {
    if (response.includes('participant_not_found')) {
        alert('This participant has already been deleted by another user.');
        location.reload(); // Refresh to update the list
    }
}
```

## Files Modified

1. **event-user-delete.php** - Fixed main deletion logic
2. **event-participants.php** - Added new error message types
3. **event-eventuser-delete.php** - Fixed debug output and error handling

## Next Steps

1. Test the fixes in a development environment
2. Monitor error logs for any remaining issues
3. Consider implementing soft deletes for better data integrity
4. Add more comprehensive logging for audit purposes
