# Aid Type Controller Documentation

**File**: `/controllers/aidTypeController.php`  
**Purpose**: Manages guarantee/aid types for charity subvention programs  
**Last Updated**: December 20, 2024  
**Total Functions**: 5  
**Lines of Code**: ~74

---

## 📋 Overview

The Aid Type Controller is a simple CRUD (Create, Read, Update, Delete) module that manages guarantee types for charity aid programs. These types categorize different forms of assistance or guarantee requirements for beneficiaries. It provides:
- Basic aid type management (add, edit, delete, list)
- Soft delete functionality with audit trails
- AJAX search for dropdown populations
- Simple form-based operations
- User tracking for all changes

### Primary Functions
- [x] Create new aid types
- [x] Edit existing aid types
- [x] Soft delete aid types
- [x] List all active aid types
- [x] AJAX search for dropdown integration
- [x] Audit trail with user and timestamp tracking

### Related Controllers
- [beneficiariesController.php](beneficiariesController.md) - Uses aid types for subvention
- [subventionController.php](#) - Aid/payment processing
- [charityController.php](#) - Charity management

---

## 🗄️ Database Tables

### Primary Table (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **guaranteetype** | Aid type definitions | id, name, del, addtoday, adduserid, updatetoday, updateuserid, deltoday, deluserid |

### Usage in Other Tables
| Table Name | Reference | Purpose |
|------------|-----------|---------|
| **subvention** | guarantee_type_id | Links aid assignments to guarantee types |
| **subventionpay** | N/A | Payment records (may reference indirectly) |

### System Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, username (for audit trail) |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Aid Type Form
**Location**: Line 7  
**Purpose**: Display simple add form for new aid types

**Process Flow**:
1. Display header template
2. Display add form (`aidtypesview/add.html`)
3. Display footer template

**Template**: Simple form with single name field

---

### 2. **show** - List Aid Types
**Location**: Line 11  
**Purpose**: Display all active aid types in a list/table format

**Function Signature**:
```php
$aidtypes = R::findAll('guaranteetype','del < 2');
```

**Process Flow**:
1. Load all active aid types (`del < 2`)
2. Assign to template variable
3. Display listing template (`aidtypesview/show.html`)

**Data Structure**: Array of aid type objects with full details

---

### 3. **edit** - Edit Aid Type Form
**Location**: Line 17  
**Purpose**: Load and display aid type editing form

**Function Signature**:
```php
$id = filter_input(INPUT_GET, 'id');
$aidtypes = R::load('guaranteetype', $id);
```

**Process Flow**:
1. Extract ID from GET parameter
2. Load aid type record by ID
3. Assign to template variable
4. Display edit template (`aidtypesview/edit.html`)

**Security**: No permission checking - relies on URL parameter validation

---

### 4. **savedata** - Save Aid Type Data
**Location**: Line 24  
**Purpose**: Create new or update existing aid type

**Function Signature**:
```php
$name = filter_input(INPUT_POST, 'name');
$id = filter_input(INPUT_POST, 'id');
```

**Process Flow**:
1. Extract name and ID from POST data
2. **If new record** (no ID):
   - Create new `guaranteetype` bean
   - Set `del = 0` (active status)
   - Set `addtoday` = current timestamp
   - Set `adduserid` = current user ID
   - Initialize delete fields as empty
3. **If updating** (has ID):
   - Load existing record by ID
   - Set `del = 1` (updated status)
   - Set `updatetoday` = current timestamp
   - Set `updateuserid` = current user ID
4. Set name field
5. Store record
6. Redirect to show page on success/error

**Audit Trail Fields**:
- `addtoday`, `adduserid` - Creation tracking
- `updatetoday`, `updateuserid` - Update tracking
- `deltoday`, `deluserid` - Deletion tracking

**Error Handling**: Redirects to appropriate page on exception

---

### 5. **delete** - Soft Delete Aid Type
**Location**: Line 47  
**Purpose**: Mark aid type as deleted (soft delete)

**Function Signature**:
```php
$id = filter_input(INPUT_GET, 'id');
```

**Process Flow**:
1. Extract ID from GET parameter
2. Load aid type record by ID
3. Set `del = 2` (soft deleted status)
4. Set `deltoday` = current timestamp
5. Set `deluserid` = current user ID
6. Store updated record
7. Redirect to show page

**Note**: This is true soft delete - record remains in database but marked as deleted

---

### 6. **aidtypes** - AJAX Search
**Location**: Line 55  
**Purpose**: Provide searchable aid type data for AJAX dropdowns

**Function Signature**:
```php
$name = $_POST['searchTerm'];
```

**Process Flow**:
1. Extract search term from POST data
2. Query active aid types matching search term
3. Format results as JSON array for dropdown consumption
4. Return JSON response

**Query Pattern**:
```sql
SELECT id, name as name
FROM guaranteetype 
WHERE del < 2 and name LIKE '%{searchTerm}%' 
LIMIT 50
```

**Response Format**:
```json
[
  {"id": 1, "text": "Financial Guarantee"},
  {"id": 2, "text": "Property Guarantee"},
  ...
]
```

**Usage**: Integrated with Select2 or similar dropdown libraries

---

## 🔄 Workflows

### Workflow 1: Create New Aid Type
```
┌─────────────────────────────────────────────────────────────┐
│                START: New Aid Type                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Add Form                                        │
│     - Show simple form with name field                     │
│     - Include hidden form fields                           │
│     - Display via aidtypesview/add.html                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Enters Data                                        │
│     - Enter aid type name (e.g., "Financial Guarantee")    │
│     - Submit form                                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Submission (savedata)                          │
│     - Validate input                                        │
│     - Create new guaranteetype record                      │
│     - Set audit fields (del=0, addtoday, adduserid)       │
│     - Save to database                                      │
│     - Redirect to list page                                 │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Edit Existing Aid Type
```
┌─────────────────────────────────────────────────────────────┐
│            START: Edit Aid Type (from list)                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Edit Form                                          │
│     - Extract ID from URL parameter                         │
│     - Load existing aid type data                           │
│     - Pre-populate form with current values                │
│     - Display via aidtypesview/edit.html                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Modifies Data                                      │
│     - Change aid type name                                  │
│     - Submit updated form                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Update (savedata)                              │
│     - Load existing record by ID                           │
│     - Update name field                                     │
│     - Set audit fields (del=1, updatetoday, updateuserid) │
│     - Save changes                                          │
│     - Redirect to list page                                 │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 3: Soft Delete Aid Type
```
┌─────────────────────────────────────────────────────────────┐
│           START: Delete Aid Type (from list)               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Confirm Deletion                                        │
│     - User clicks delete link/button                       │
│     - Extract ID from URL parameter                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Perform Soft Delete                                     │
│     - Load aid type record by ID                           │
│     - Set del = 2 (soft deleted)                          │
│     - Set audit fields (deltoday, deluserid)              │
│     - Save changes                                          │
│     - Redirect to list page                                 │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display add aid type form |
| `do=show` | List view | Display all active aid types |
| `do=edit&id=X` | Edit form | Display edit form for aid type X |
| `do=savedata` | Save function | Save aid type data (POST) |
| `do=delete&id=X` | Delete function | Soft delete aid type X |
| `do=aidtypes` | AJAX search | Return JSON for dropdown search (POST) |

### Required Parameters by Action

**Add Aid Type** (`do=` empty):
- No parameters required

**Show Aid Types** (`do=show`):
- No parameters required

**Edit Aid Type** (`do=edit`):
- `id` - Aid type ID (GET parameter)

**Save Aid Type** (`do=savedata`):
- `name` - Aid type name (POST parameter)
- `id` - Aid type ID for updates (POST parameter, optional)

**Delete Aid Type** (`do=delete`):
- `id` - Aid type ID (GET parameter)

**AJAX Search** (`do=aidtypes`):
- `searchTerm` - Search string (POST parameter)

---

## 🧮 Data Management Features

### Soft Delete System
```php
// Deletion status levels:
// del = 0: Active (new records)
// del = 1: Updated (edit mode)  
// del = 2: Soft deleted
// del < 2: Active filter for queries
```

### Audit Trail System
```php
// Creation tracking
$aidtypes->addtoday = date("Y-m-d H:i:s");
$aidtypes->adduserid = $_SESSION['userid'];

// Update tracking  
$aidtypes->updatetoday = date("Y-m-d H:i:s");
$aidtypes->updateuserid = $_SESSION['userid'];

// Deletion tracking
$tables->deltoday = date("Y-m-d H:i:s");
$tables->deluserid = $_SESSION['userid'];
```

### Simple Validation
- Basic input filtering through `filter_input()`
- No duplicate name checking (unlike some other controllers)
- No complex business rules

---

## 🔒 Security & Permissions

### Input Sanitization
```php
// All inputs filtered through filter_input
$name = filter_input(INPUT_POST, 'name');
$id = filter_input(INPUT_POST, 'id');
```

### Access Control
- No explicit permission checking implemented
- Relies on session-based authentication
- URL parameter validation through filter_input()

### Potential Security Concerns
1. **No permission verification** - Any authenticated user can manage aid types
2. **No duplicate checking** - Could create duplicate aid type names
3. **No referential integrity check** - Deleting aid types used by subventions

---

## 📊 Performance Considerations

### Database Optimization
1. **Recommended Indexes**:
   - `guaranteetype(del)` - For active record filtering
   - `guaranteetype(name)` - For search functionality
   - `guaranteetype(id, del)` - For load operations

2. **Query Patterns**:
   - Simple queries with single table operations
   - No complex joins or subqueries
   - LIMIT 50 on search to prevent large result sets

### Memory Usage
- Very lightweight operations
- Single record operations for most functions
- Limited result sets in AJAX searches

---

## 🐛 Common Issues & Troubleshooting

### 1. **Duplicate Aid Type Names**
**Issue**: Multiple aid types with same name created  
**Cause**: No duplicate checking in save function

**Solution**: Add duplicate validation:
```php
$existing = R::count('guaranteetype', 'name = ? AND del < 2 AND id != ?', [$name, $id]);
if ($existing > 0) {
    // Handle duplicate
}
```

### 2. **Referential Integrity Violations**
**Issue**: Deleting aid types that are still referenced by subventions  
**Cause**: No foreign key constraint checking

**Solution**: Check references before delete:
```php
$references = R::count('subvention', 'guarantee_type_id = ? AND del < 2', [$id]);
if ($references > 0) {
    // Prevent deletion or cascade
}
```

### 3. **Missing Audit Information**
**Issue**: Records show blank user/date information  
**Cause**: Session not properly initialized

**Debug**: Check session userid is set:
```php
var_dump($_SESSION['userid']);
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic CRUD Operations
```
1. Create new aid type with name "Test Guarantee"
2. Verify appears in listing
3. Edit name to "Modified Guarantee" 
4. Verify update appears correctly
5. Delete aid type
6. Verify no longer appears in active listing
```

### Test Case 2: AJAX Search Functionality
```
1. Create several aid types with different names
2. Test AJAX search with partial matches
3. Verify JSON response format correct
4. Test search limits (50 records max)
5. Test empty search terms
```

### Test Case 3: Audit Trail Verification
```
1. Create aid type and check addtoday/adduserid
2. Edit aid type and check updatetoday/updateuserid  
3. Delete aid type and check deltoday/deluserid
4. Verify all timestamps and user IDs correct
```

---

## 🔗 Integration Points

### Used By Other Controllers
```php
// In beneficiariesController.php Excel import:
$guarantee_type_id = $rowData[$col]; // References guaranteetype.id

// In subvention management:
// References guaranteetype.id in subvention.guarantee_type_id
```

### Template Integration
```html
<!-- In dropdown forms -->
<select name="guarantee_type_id">
  <!-- Populated via AJAX search -->
</select>
```

### API Endpoints
- `do=aidtypes` provides JSON data for frontend dropdowns
- Used by Select2 and similar dropdown enhancement libraries

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [beneficiariesController.md](beneficiariesController.md) - Main beneficiary management
- [subventionController.php](#) - Aid assignment and payment processing
- [Database Schema Documentation](#) - Table relationships

---

## 💡 Improvement Recommendations

### 1. **Add Duplicate Validation**
```php
// In savedata() function
$existing = R::count('guaranteetype', 'name = ? AND del < 2 AND id != ?', [$name, $id ?: 0]);
if ($existing > 0) {
    header("location:aidTypeController.php?error=duplicate");
    return;
}
```

### 2. **Add Referential Integrity Checks**
```php
// Before deletion
$references = R::count('subvention', 'guarantee_type_id = ? AND del < 2', [$id]);
if ($references > 0) {
    header("location:aidTypeController.php?error=in_use");
    return;
}
```

### 3. **Improve Error Handling**
```php
// Add specific error messages and validation
// Use JSON responses for AJAX operations
// Add client-side validation
```

---

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