# Department Edit Form Fix

## Problem

When editing a proposal and refreshing the page, the selected departments were being lost/reset. This was causing users to lose their department selections when the form was refreshed.

## Root Cause

The issue was in the `EditProposal` component where:

1. **Form Data Not Properly Reloaded**: After saving, the `selectedDepartments` property wasn't being updated with the saved data
2. **Livewire Hydration Issue**: The component wasn't properly maintaining state during page refreshes
3. **Missing Debug Information**: No way to track what was happening with the department selections
4. **Insufficient Validation**: No validation to ensure departments were properly loaded before saving
5. **Status Validation Error**: The status validation was failing because `pending_review` status wasn't included in the allowed values

## Solution

### 1. Fixed Form Data Reloading

Updated the `save()` method to properly reload the `selectedDepartments` after saving:

```php
// Refresh the proposal to get the updated status
$this->proposal = Proposal::with(['items', 'client'])->find($this->proposal->id);
$this->status = $this->proposal->status;

// Reload the selectedDepartments to ensure they match the saved data
$this->selectedDepartments = $this->proposal->departments ?? [];
```

### 2. Added Department Validation

Added a method to validate departments before saving:

```php
public function validateDepartments()
{
    \Log::info('Validating departments:', [
        'selectedDepartments' => $this->selectedDepartments,
        'type' => gettype($this->selectedDepartments),
        'is_array' => is_array($this->selectedDepartments),
        'count' => is_array($this->selectedDepartments) ? count($this->selectedDepartments) : 'not array',
    ]);
    
    if (empty($this->selectedDepartments) || !is_array($this->selectedDepartments)) {
        \Log::warning('Departments validation failed - reloading from database');
        $this->syncDepartmentsFromDatabase();
        return false;
    }
    
    \Log::info('Departments validation passed');
    return true;
}
```

### 3. Fixed Status Validation

Updated the status validation to include all possible status values:

```php
'status' => 'required|in:draft,sent,pending,pending_review,approved,rejected,expired,conflict_analyse,no_conflict,conflict',
```

And updated the view to include all status options:

```blade
<select wire:model="status" id="status" class="...">
    <option value="draft">Draft</option>
    <option value="sent">Sent</option>
    <option value="pending">Pending</option>
    <option value="pending_review">Pending Review</option>
    <option value="approved">Approved</option>
    <option value="rejected">Rejected</option>
    <option value="expired">Expired</option>
    <option value="conflict_analyse">Conflict Analysis</option>
    <option value="no_conflict">No Conflict</option>
    <option value="conflict">Conflict</option>
</select>
```

### 4. Added Department Synchronization

Added methods to sync departments with the database:

```php
public function syncDepartmentsFromDatabase()
{
    if (!empty($this->proposal)) {
        $this->selectedDepartments = $this->proposal->departments ?? [];
        \Log::info('Synced departments from database:', [
            'proposal_id' => $this->proposal->id,
            'departments' => $this->selectedDepartments,
        ]);
    }
}

public function forceReloadDepartments()
{
    // Force reload the proposal from database
    $this->proposal = Proposal::with(['items', 'client'])->find($this->proposal->id);
    $this->syncDepartmentsFromDatabase();
}
```

### 5. Enhanced Livewire Lifecycle Methods

Added methods to handle component hydration and updates:

```php
public function hydrate()
{
    // Always ensure departments are loaded from database when component is hydrated
    if (!empty($this->proposal)) {
        // Only reload if we don't have the proposal loaded or if departments are missing
        if (empty($this->selectedDepartments) || !is_array($this->selectedDepartments)) {
            $this->selectedDepartments = $this->proposal->departments ?? [];
        }
    }
}

public function updatedSelectedDepartments($value)
{
    \Log::info('selectedDepartments updated:', [
        'new_value' => $value,
        'old_value' => $this->selectedDepartments,
        'proposal_departments' => $this->proposal->departments,
    ]);
    
    // Ensure we always have an array
    if (!is_array($value)) {
        $this->selectedDepartments = [];
    }
}
```

### 6. Enhanced Debug Logging

Added comprehensive logging to track department loading:

```php
private function fillForm()
{
    // ... existing code ...
    
    // Debug logging
    \Log::info('fillForm called:', [
        'proposal_id' => $this->proposal->id,
        'proposal_departments' => $this->proposal->departments,
        'selected_departments' => $this->selectedDepartments,
        'available_departments' => array_keys($departments),
    ]);
}
```

### 7. Added Manual Refresh Buttons

Added buttons to the edit form that allow users to manually reload form data:

```php
public function refreshForm()
{
    // Reload the proposal from database
    $this->proposal = Proposal::with(['items', 'client'])->find($this->proposal->id);
    $this->fillForm();
    $this->syncDepartmentsFromDatabase();
}

public function forceReloadDepartments()
{
    // Force reload the proposal from database
    $this->proposal = Proposal::with(['items', 'client'])->find($this->proposal->id);
    $this->syncDepartmentsFromDatabase();
}
```

### 8. Enhanced Debug Information

Added debug information to the view (only in development mode):

```blade
@if(config('app.debug'))
    <div class="mt-2 p-2 bg-gray-100 rounded text-xs">
        <strong>Debug:</strong><br>
        Selected: {{ json_encode($selectedDepartments) }}<br>
        Proposal: {{ json_encode($proposal->departments) }}<br>
        Count: {{ count($selectedDepartments ?? []) }} selected, {{ count($proposal->departments ?? []) }} in DB
    </div>
@endif
```

## How It Works Now

### Before Fix
1. User edits proposal and selects departments
2. User saves the proposal
3. Page refreshes
4. **Departments are lost/reset** ❌

### After Fix
1. User edits proposal and selects departments
2. **Departments are validated** before saving ✅
3. User saves the proposal
4. **Departments are properly saved** to database ✅
5. Page refreshes
6. **Departments are properly loaded** from database ✅

## Testing

To test the fix:

1. **Edit a proposal** and select multiple departments
2. **Save the proposal**
3. **Refresh the page**
4. **Verify** that the selected departments are still there
5. **Check the debug information** (if in development mode) to see the current state
6. **Use the "Reload Depts" button** if departments seem to be missing

## Files Modified

- `app/Livewire/EditProposal.php` - Main fixes
- `resources/views/livewire/edit-proposal.blade.php` - Added refresh buttons and debug info

## Benefits

1. **Data Persistence**: Departments are properly maintained across page refreshes
2. **Better UX**: Users don't lose their selections unexpectedly
3. **Debug Capability**: Easy to track what's happening with department selections
4. **Manual Recovery**: Multiple buttons allow users to recover if needed
5. **Comprehensive Logging**: Full audit trail of department changes
6. **Validation**: Departments are validated before saving to prevent data loss
7. **Synchronization**: Multiple methods to sync with database when needed

## Related Issues

This fix also addresses:
- Livewire component state management
- Form data persistence
- User experience during form editing
- Debug visibility for development
- Data validation and integrity 