# Staff Editing - Code Analysis Report

## 1. editStaff() Method
**Location:** [app/Http/Controllers/UserManagementController.php](app/Http/Controllers/UserManagementController.php#L193-L205)

```php
/**
 * Edit staff member
 */
public function editStaff(User $user)
{
    $this->authorize('edit-staff', $user);

    $roles = ['assistant_director', 'training_officer', 'warden'];

    $trades = DB::table('trades')
                ->where('status', 1)
                ->orderBy('trade_name')
                ->get();

    return view('staff.edit', compact('user', 'roles', 'trades'));
}
```

**Key Points:**
- Authorization check: `$this->authorize('edit-staff', $user)` - requires UserPolicy
- Loads available roles: assistant_director, training_officer, warden
- Fetches active trades from database
- Passes user, roles, and trades to the view

---

## 2. updateStaff() Method
**Location:** [app/Http/Controllers/UserManagementController.php](app/Http/Controllers/UserManagementController.php#L208-L285)

```php
/**
 * Update staff member
 */
public function updateStaff(Request $request, User $user)
{
    $this->authorize('edit-staff', $user);

    $validated = $request->validate([
        'name' => 'required|string|max:255|regex:/^[a-zA-Z\s]+$/',
        'email' => 'required|email|unique:users,email,' . $user->id,
        'mobile' => 'required|string|regex:/^\d{10}$/',
        'location' => 'required|string|max:255',
        'role' => 'required|in:assistant_director,training_officer,warden',
        'trade_id' => 'nullable|string|max:255',
        'img' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        'status' => 'required|in:active,inactive',
        'hostel_type' => 'nullable|in:boys,girls',
    ], [
        'name.regex' => 'Name can only contain letters and spaces',
        'mobile.regex' => 'Mobile number must be exactly 10 digits',
    ]);

    try {
        // Validate hostel_type for warden
        if ($validated['role'] === 'warden' && !$validated['hostel_type']) {
            return back()->withInput()->withErrors(['hostel_type' => 'Hostel type is required for Warden role']);
        }

        // Validate trade for training_officer
        if ($validated['role'] === 'training_officer' && !$validated['trade_id']) {
            return back()->withInput()->withErrors(['trade_id' => 'Trade is required for Training Officer role']);
        }

        // Handle photo upload
        $imgPath = $user->img;
        if ($request->hasFile('img')) {
            $imgPath = $request->file('img')->store('staff-photos', 'public');
        }

        // Prepare update data
        $updateData = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'mobile' => $validated['mobile'],
            'location' => $validated['location'],
            'role' => $validated['role'],
            'trade_id' => $validated['trade_id'] ?? null,
            'status' => $validated['status'],
            'hostel_type' => $validated['hostel_type'] ?? null,
        ];

        if ($imgPath) {
            $updateData['img'] = $imgPath;
        }

        // Update user
        $user->update($updateData);

        return redirect()->route('staff.list')
            ->with('success', 'Staff member updated successfully!');

    } catch (\Exception $e) {
        return back()->with('error', 'Error updating staff member: ' . $e->getMessage());
    }
}
```

**Validation Rules:**
- **name**: Required, string, max 255 chars, letters and spaces only
- **email**: Required, email format, unique (excluding current user's email)
- **mobile**: Required, exactly 10 digits
- **location**: Required, string, max 255 chars
- **role**: Required, must be one of: assistant_director, training_officer, warden
- **trade_id**: Optional (required only for training_officer role)
- **img**: Optional, image file (jpeg/png/jpg/gif), max 2MB
- **status**: Required, must be active or inactive
- **hostel_type**: Optional (required only for warden role)

**Conditional Logic:**
1. Wardens MUST have hostel_type (boys/girls)
2. Training officers MUST have trade_id
3. Photo upload handled if file provided
4. Returns to staff.list on success

---

## 3. Edit Form (Complete)
**Location:** [resources/views/staff/edit.blade.php](resources/views/staff/edit.blade.php)

### Form Structure:

```blade
<form action="{{ route('staff.update', $user->id) }}" method="POST" enctype="multipart/form-data" id="staffEditForm" novalidate>
    @csrf
    @method('PUT')

    <!-- Personal Information Section -->
    - Name field (with error display)
    - Email field (with error display)
    - Mobile field (10 digits, with error display)
    - Location field (with error display)
    - Role dropdown (assistant_director, training_officer, warden)
    - Photo upload (JPG, PNG, GIF, max 2MB)

    <!-- Professional Information Section -->
    - Trade dropdown (shown only for training_officer role)
    - Status dropdown (active/inactive)
    - Hostel Type dropdown (shown only for warden role)

    <!-- Form Actions -->
    - Cancel button (links to staff.list)
    - Update Staff button (type="submit")
</form>
```

### Key Features:

**Conditional Field Display:**
- Trade field hidden by default, shown when role === 'training_officer'
- Hostel Type field hidden by default, shown when role === 'warden'
- JavaScript handles field visibility on role change

**Image Upload:**
- Displays current photo if exists
- File size validation (max 2MB)
- Type validation (JPG, PNG, GIF only)
- Client-side feedback on selection

**Mobile Field:**
- Enforces 10-digit input only
- Strips non-numeric characters via JavaScript

**Error Display:**
- Server-side errors shown in alert box at top
- Individual field errors displayed below each field
- Red styling for invalid fields

---

## 4. Route Configuration
**Location:** [routes/web.php](routes/web.php#L71-L90)

```php
// Edit staff route (GET)
Route::get('/staff/{user}/edit',
    [UserManagementController::class,'editStaff']
)->name('staff.edit');

// Update staff route (PUT)
Route::put('/staff/{user}',
    [UserManagementController::class,'updateStaff']
)->name('staff.update');
```

**Routes are correct:**
✅ GET /staff/{user}/edit → editStaff() method
✅ PUT /staff/{user} → updateStaff() method
✅ Route names match form action

---

## 5. Log File Findings

**Current Log Issues:**
- ❌ Vite manifest not found (2026-05-10 15:10:28)
- ❌ Missing routes/auth.php file (2026-05-05, older)

**Staff Editing Specific Issues:**
- ✅ No recent errors related to editStaff() or updateStaff()
- ✅ No validation errors in logs
- ✅ No database errors related to staff updates

---

## 6. Potential Issues & Troubleshooting

### Issue 1: Authorization Failing
**Problem:** If you see "This action is unauthorized" error
**Solution:** Check UserPolicy.php for edit-staff policy definition
```bash
Check: app/Policies/UserPolicy.php
Verify: edit() or editStaff() method exists and allows current user
```

### Issue 2: File Upload Fails
**Problem:** Photo upload doesn't work
**Solution:**
- Verify storage/app/public/staff-photos directory exists
- Check file permissions on storage directory
- Run: `php artisan storage:link` if not already done
- Ensure max_upload_size in php.ini is > 2MB

### Issue 3: Trade Not Showing for Training Officer
**Problem:** Trade field doesn't appear when selecting training_officer role
**Solution:**
- Check browser console for JavaScript errors
- Verify f_trade_id element ID matches JavaScript
- Ensure trades are in database with status = 1

### Issue 4: Email Unique Constraint Fails
**Problem:** Can't update email even if same value
**Solution:**
- The validation rule is correct: `unique:users,email,' . $user->id`
- This allows same email for current user
- Check for database transaction issues

### Issue 5: Hostel Type Not Persisting for Warden
**Problem:** Hostel type saved as NULL
**Solution:**
- Ensure users table has hostel_type column (nullable, string)
- Verify migration exists: `2024_01_01_000003_create_teachers_table.php`
- Check that users table column definition includes hostel_type

---

## 7. Summary

**Status:** ✅ Code appears structurally correct

**The edit and update flow is:**
1. User navigates to `/staff/{id}/edit`
2. editStaff() loads user data and form
3. User submits form to `/staff/{id}` with PUT method
4. updateStaff() validates and updates data
5. User redirected to staff.list with success message

**Most Likely Issues:**
1. Missing or incorrect UserPolicy edit-staff method
2. Database migration missing hostel_type/trade_id columns
3. Storage directory permissions
4. Browser caching preventing conditional field display
5. JavaScript not running properly in browser

