# Car Reviewer Controller Documentation

**File**: `/controllers/carReviewerController.php`  
**Purpose**: Manages reviewer assignments for car import operations  
**Last Updated**: December 20, 2024  
**Total Functions**: 2  
**Lines of Code**: ~58

---

## 📋 Overview

The Car Reviewer Controller is a simple configuration module that manages reviewer assignments for car import operations. It handles:
- Assignment of primary and secondary reviewers from user lists
- Configuration storage for reviewer selections
- Multi-select user assignment with "all users" option
- Simple CRUD operations for reviewer configuration

### Primary Functions
- [x] Display reviewer configuration form
- [x] Save reviewer assignments
- [x] Load existing reviewer settings
- [x] Multi-select user assignment
- [x] "All users" fallback option

### Related Controllers
- [carTrackingController.php](carTrackingController.md) - Car tracking operations
- [User management system](#) - Employee/user data source

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **carreviewer** | Reviewer assignment configuration | id, reviewer1, reviewer2, userid, sysdate |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users/employees | userid, employeename, conditions |

---

## 🔑 Key Functions

### 1. **Default Action** - Display Configuration Form
**Location**: Lines 8-21  
**Purpose**: Show reviewer assignment form with current settings

**Function Signature**:
```php
// Triggered when: empty($do) or no action specified
if (empty($do)) {
```

**Process Flow**:
1. Load all active users from database
2. Load existing reviewer configuration (ID=1)
3. Convert comma-separated reviewer lists to arrays
4. Display configuration form via add.html template

**Key Variables**:
- `$allUsers` - List of all active employees for selection
- `$reviewersData` - Current reviewer configuration
- `$reviewersData->reviewer1` - Array of primary reviewer user IDs
- `$reviewersData->reviewer2` - Array of secondary reviewer user IDs

**SQL Operations**:
```sql
-- Load active users
SELECT userid, employeename FROM user WHERE conditions = 0 AND userid > 0

-- Load reviewer configuration
SELECT * FROM carreviewer WHERE id = 1
```

---

### 2. **savedata** - Save Reviewer Configuration
**Location**: Lines 21-55  
**Purpose**: Process and save reviewer assignment changes

**Function Signature**:
```php
// Triggered when: do=savedata
else if ($do == 'savedata') {
```

**Process Flow**:
1. Filter and validate POST input arrays
2. Load or create reviewer configuration record
3. Process reviewer selections:
   - Handle "all users" option (value "0")
   - Convert arrays to comma-separated strings
4. Save configuration to database
5. Redirect back to main form

**Input Processing**:
```php
$reviewer1 = filter_input(INPUT_POST, 'reviewer1', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$reviewer2 = filter_input(INPUT_POST, 'reviewer2', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$id = filter_input(INPUT_POST, 'id');
```

**Special Logic**:
```php
// Handle "all users" selection
if (in_array("0", $reviewer1)) {
    $reviewers->reviewer1 = '0';  // All users
} else {
    $reviewers->reviewer1 = implode(",", $reviewer1);  // Specific users
}
```

**Database Operations**:
- **Create**: New carreviewer record if no ID provided
- **Update**: Existing record if ID provided
- **Store**: Save changes with current timestamp and user ID

---

## 🔄 Workflows

### Workflow 1: Initial Reviewer Setup
```
┌─────────────────────────────────────────────────────────────┐
│                  START: Access Controller                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load System Components                                  │
│     - Include core operations                               │
│     - Initialize date variables                             │
│     - Check for action parameter                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Load User Data                                          │
│     - Query all active users                                │
│     - Filter out disabled accounts                          │
│     - Prepare for dropdown population                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Load Current Configuration                              │
│     - Load carreviewer record (ID=1)                       │
│     - Convert comma-separated strings to arrays            │
│     - Prepare for multi-select population                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Display Configuration Form                              │
│     - Show multi-select dropdowns                          │
│     - Pre-populate with current selections                 │
│     - Include "all users" option                           │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Save Reviewer Changes
```
┌─────────────────────────────────────────────────────────────┐
│               START: Form Submission                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Process Input Data                                      │
│     - Filter reviewer1[] array                              │
│     - Filter reviewer2[] array                              │
│     - Get configuration ID                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Determine Operation Type                                │
│     ┌─────────────────┬─────────────────────────────────┐   │
│     │  No ID Provided │        ID Provided              │   │
│     │        │        │             │                   │   │
│     │        ▼        │             ▼                   │   │
│     │  Create New     │      Load Existing             │   │
│     │  Record         │      Record                     │   │
│     └─────────────────┴─────────────────────────────────┘   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Reviewer Selections                             │
│     FOR EACH reviewer field (1 and 2):                     │
│       │                                                     │
│       ├─→ Check if "0" (all users) is selected            │
│       │   ├─ YES: Set field to "0"                        │
│       │   └─ NO: Convert array to comma-separated string   │
│       │                                                     │
│       └─→ Update record field                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Configuration                                      │
│     - Set system date and user ID                          │
│     - Store record to database                             │
│     - Handle any exceptions                                 │
│     - Redirect to main form                                │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| (no parameters) | Default action | Display reviewer configuration form |
| `do=savedata` | Save action | Process and save reviewer assignments |

### Required Parameters by Action

**Configuration Form** (no parameters):
- No parameters required
- Automatically loads existing configuration

**Save Configuration** (`do=savedata`):
- `reviewer1[]` - Array of primary reviewer user IDs
- `reviewer2[]` - Array of secondary reviewer user IDs  
- `id` - Configuration record ID (optional for new records)

---

## 🧮 Data Processing

### Multi-Select Processing
```php
// Input validation and filtering
$reviewer1 = filter_input(INPUT_POST, 'reviewer1', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$reviewer2 = filter_input(INPUT_POST, 'reviewer2', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

// Special case: "All users" selection
if (in_array("0", $reviewer1)) {
    $reviewers->reviewer1 = '0';
} else {
    $reviewers->reviewer1 = implode(",", $reviewer1);
}
```

### Array to String Conversion
```php
// Convert array selections to database format
$reviewers->reviewer1 = implode(",", $reviewer1);  // e.g., "1,3,5,7"

// Convert string back to array for display
$reviewersData->reviewer1 = explode(',', $reviewersData->reviewer1);  // e.g., [1,3,5,7]
```

### Record Management
```php
// Create new or load existing
if (!$id) {
    $reviewers = R::dispense('carreviewer');  // New record
} else {
    $reviewers = R::load('carreviewer', $id);  // Existing record
}

// Set audit fields
$reviewers->sysdate = date("Y-m-d H:i:s");
$reviewers->userid = $_SESSION['userid'];
```

---

## 🔒 Security & Permissions

### Input Validation
```php
// Array filtering for multi-select inputs
$reviewer1 = filter_input(INPUT_POST, 'reviewer1', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$reviewer2 = filter_input(INPUT_POST, 'reviewer2', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$id = filter_input(INPUT_POST, 'id');
```

### User Restrictions
- Only active users (`conditions = 0`) appear in selection lists
- User IDs are validated against existing user table
- Session-based user tracking for audit trail

### Error Handling
```php
try {
    R::store($reviewers);
    header("location:carReviewerController.php");
} catch (Exception $e) {
    header("location:carReviewerController.php");  // Redirect even on error
}
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Simple Operations**: Only basic CRUD operations, minimal performance impact
2. **Single Record**: Configuration stored as single record (ID=1)
3. **User Query**: Could benefit from index on `(conditions, userid)` if many users exist

### Memory Usage
- Minimal memory footprint
- Small data sets (user list, single configuration record)
- No complex calculations or large result sets

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Configuration Record**
**Issue**: No existing reviewer configuration found  
**Cause**: First-time setup, record not yet created

**Debug**:
```sql
SELECT * FROM carreviewer WHERE id = 1;
-- Should return exactly one record
```

**Fix**: Submit form once to create initial record

### 2. **Multi-Select Not Saving**
**Issue**: Reviewer selections not persisting  
**Cause**: Array processing issues or filter problems

**Debug**:
```php
// Add at top of savedata action
var_dump($_POST['reviewer1']);
var_dump($_POST['reviewer2']);
```

### 3. **User List Empty**
**Issue**: No users appearing in dropdown  
**Cause**: All users disabled or permission issues

**Debug**:
```sql
SELECT userid, employeename, conditions FROM user WHERE userid > 0;
-- Check conditions column values
```

---

## 🧪 Testing Scenarios

### Test Case 1: Initial Setup
```
1. Access controller with no existing configuration
2. Verify user dropdown is populated
3. Select reviewers and save
4. Confirm configuration is created in database
5. Verify form shows saved selections on reload
```

### Test Case 2: Update Existing Configuration
```
1. Load existing reviewer configuration
2. Change reviewer selections
3. Save changes
4. Verify database is updated
5. Confirm new selections appear on form reload
```

### Test Case 3: "All Users" Option
```
1. Select "All Users" option for reviewer1
2. Save configuration
3. Verify database stores "0" value
4. Confirm "All Users" remains selected on reload
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [carTrackingController.md](carTrackingController.md) - Related car operations
- [User Management Documentation](#) - Employee/user system

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur