# Beneficiaries Controller Documentation

**File**: `/controllers/beneficiariesController.php`  
**Purpose**: Manages charity beneficiaries database with comprehensive demographic, socioeconomic, and housing data  
**Last Updated**: December 20, 2024  
**Total Functions**: 15+  
**Lines of Code**: ~1,084

---

## 📋 Overview

The Beneficiaries Controller is a comprehensive beneficiary management module that handles detailed beneficiary registration, tracking, and reporting for charity organizations. It provides:
- Complete beneficiary profile management with demographics
- Detailed housing condition assessments
- Household inventory tracking (furniture, appliances)
- Family member information management
- Economic status documentation
- Excel import/export functionality
- Multi-charity support with permission controls
- Beneficiary search and verification system
- Subvention payment tracking

### Primary Functions
- [x] Create and edit comprehensive beneficiary profiles
- [x] Track household inventory (appliances, furniture)
- [x] Manage family member details
- [x] Document economic conditions
- [x] Excel bulk import with duplicate checking
- [x] Search beneficiaries by ID number
- [x] Multi-charity beneficiary assignment
- [x] Age calculation from ID numbers
- [x] Image upload and management
- [x] Payment history tracking

### Related Controllers
- [charityController.php](#) - Charity management
- [subventionController.php](#) - Payment processing
- [areaController.php](#) - Geographic areas
- [diseaseController.php](#) - Health conditions

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **beneficiaries** | Main beneficiary data | id, name, idnumber, phone_no, address, charity_id, area_id, age, diseas, work, workplace, del, sysdate, user_id |
| **beneficiaries_family** | Family member details | id, beneficiaries_id, name, relation, age, id_number, status, job, salary, health_status, education_status |
| **beneficiaries_eco** | Economic data | id, beneficiaries_id, income, paying |
| **area** | Geographic areas | id, name, user_id, sysdate |
| **disease** | Health conditions | id, name, del, user_id, sysdate |

### Support Tables (Referenced)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **charities** | Charity organizations | id, charityname, charityphone, del |
| **subvention** | Aid assignments | id, beneficier_id, charity_id, financial_aid, inkind_aid, guarantee_type_id, notes, del, sysdate |
| **subventionpay** | Payment records | id, benefeciary_id, charity_id, month, financial_aid, inkind_aid, notes, del, sysdate |
| **charitysearchlog** | Search activity log | id, user_id, charity_id, sysdate, idnumber, benefeciary_id |
| **charityaddsubjectdetails** | Charity subject relations | charitysubjectid, charityid, del |

### System Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, username, charityids (session filter) |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Beneficiary Form
**Location**: Line 10  
**Purpose**: Display add beneficiary form with all required dropdowns

**Process Flow**:
1. Load areas for area dropdown
2. Load diseases for disease dropdown  
3. Apply charity session filter
4. Load charities for charity dropdown
5. Display add form template

**Template Variables**:
- `$allAreas` - Available areas
- `$allDisease` - Available diseases
- `$allCharities` - Filtered charities
- `$charity` - Flag for charity mode

---

### 2. **addSimple** - Simplified Add Form
**Location**: Line 28  
**Purpose**: Display simplified beneficiary add form

**Process Flow**:
1. Apply charity session filter
2. Load filtered charities
3. Display simplified template (`add_smpl.html`)

---

### 3. **show** - List Beneficiaries
**Location**: Line 41  
**Purpose**: Display beneficiaries listing with search and filtering

**Process Flow**:
1. Check authentication
2. Apply charity session filter
3. Load charities for filter dropdown
4. Display listing template with DataTables

---

### 4. **edit** - Edit Beneficiary
**Location**: Line 56  
**Purpose**: Load and display beneficiary editing form with all related data

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

**Process Flow**:
1. Load beneficiary by ID
2. Load areas, diseases, charities
3. Load family members for this beneficiary
4. Load economic data for this beneficiary
5. Display edit template with all data

**Related Data Loading**:
```php
$allFamily = R::getAll('select * from beneficiaries_family where beneficiaries_id = ' . $id);
$allEco = R::getAll('select * from beneficiaries_eco where beneficiaries_id = ' . $id);
```

---

### 5. **savedata()** - Save Beneficiary Data
**Location**: Line 239  
**Purpose**: Comprehensive beneficiary data save with image upload

**Function Signature**:
```php
function savedata()
```

**Process Flow**:
1. Extract 80+ form fields (demographics, housing, inventory)
2. Handle image upload/update
3. Create new or load existing beneficiary record
4. Save main beneficiary data
5. Call `saveFamilyData()` to save family members
6. Call `saveEcoData()` to save economic data
7. Return success/error response

**Key Features**:
- Image upload with resize (300x300)
- Age validation and room/rent conditioning
- Comprehensive housing condition tracking
- Appliance and furniture inventory
- Audit trail with user and date tracking

**Data Categories Saved**:
- **Demographics**: name, nickname, age, ID number, phone, address
- **Social**: marital status, work, workplace, diseases, health status
- **Housing**: floors, rooms, rent, bathroom, flooring, ceiling, walls, lighting
- **Appliances**: cooker, washer, fridge, fan, phone, casset, blender, TV
- **Furniture**: bed, wardrobe, couch, salon, chair, library, carpet, mat, blanket
- **Assessment**: beneficiary needs, observer needs, opinions, final recommendations

---

### 6. **showajax()** - DataTables AJAX
**Location**: Line 503  
**Purpose**: Provide paginated, searchable beneficiary data for DataTables

**Function Signature**:
```php
function showajax()
```

**Parameters**:
- `start_date`, `end_date` - Date range filter
- `del` - Deletion status filter
- `data1` - Beneficiary ID search
- `data2` - ID number search  
- `data3` - Beneficiary ID filter
- `chID` - Charity ID filter

**Process Flow**:
1. Build dynamic WHERE clause based on filters
2. Apply charity session permissions
3. Execute search with pagination
4. Format data for DataTables JSON response
5. Include action buttons (edit/delete) based on deletion status

**Search Fields**:
```php
OR beneficiaries.id LIKE "%{search}%" 
OR beneficiaries.phone_no LIKE "%{search}%"
OR beneficiaries.idnumber LIKE "%{search}%"
OR beneficiaries.name LIKE "%{search}%"
```

---

### 7. **removecontroller()** - Soft Delete
**Location**: Line 612  
**Purpose**: Soft delete beneficiary record

**Function Signature**:
```php
function removecontroller()
```

**Process Flow**:
1. Load beneficiary by POST ID
2. Set `del = 2` (soft delete)
3. Record deletion date and user
4. Save changes
5. Return success/error status

---

### 8. **saveFamilyData()** - Family Members Management
**Location**: Line 631  
**Purpose**: Save and update family member information

**Function Signature**:
```php
function saveFamilyData($beneficiariesid, $edit)
```

**Process Flow**:
1. Loop through family iteration count (`familyItr`)
2. For each family member:
   - Extract family data (name, relation, age, ID, status, job, salary, health, education)
   - Create new or load existing family record
   - Save family member data
   - Collect saved IDs
3. Delete family members not in current list

**Family Data Fields**:
- Personal: name, relation, age, id_number
- Status: status, job, salary
- Health: health_status, education_status

---

### 9. **saveEcoData()** - Economic Data Management
**Location**: Line 674  
**Purpose**: Save household economic information

**Function Signature**:
```php
function saveEcoData($beneficiariesid, $edit)
```

**Process Flow**:
1. Loop through economic iteration count (`ecoItr`)
2. For each economic entry:
   - Extract income and paying fields
   - Create new or load existing eco record
   - Save economic data
   - Collect saved IDs
3. Delete economic records not in current list

---

### 10. **getBenData()** - Beneficiary Search
**Location**: Line 123  
**Purpose**: Search beneficiary by ID number and display aid history

**Function Signature**:
```php
$idNo = filter_input(INPUT_POST, 'idno');
```

**Process Flow**:
1. Log search activity to `charitysearchlog`
2. Search beneficiary by ID number
3. Load aid history from `subventionpay` with charity details
4. Display search results or -1 if not found

**Aid History Query**:
```sql
SELECT charityname, charityphone, p.financial_aid, p.inkind_aid, p.month
FROM subventionpay p 
JOIN charities ON p.charity_id = charities.id 
WHERE p.benefeciary_id = {beneficiary_id}
```

---

### 11. **addFromExcel()** - Excel Import
**Location**: Line 837  
**Purpose**: Bulk import beneficiaries from Excel file with duplicate handling

**Function Signature**:
```php
function addFromExcel()
```

**Process Flow**:
1. Upload and identify Excel file
2. Read worksheet starting from row 4
3. For each row:
   - Extract: name, address, phone, ID number, financial aid, in-kind aid, guarantee type, comment
   - Check for existing beneficiary by ID number
   - If exists and different charity: add payment record only
   - If new: create beneficiary and subvention records
   - Calculate age from ID number millennium/year
4. Create monthly payment record
5. Use transactions for data integrity

**Excel Column Mapping**:
```php
$col=0: name
$col=1: address  
$col=2: phone
$col=3: idNo
$col=4: money (financial aid)
$col=5: value (in-kind aid)
$col=6: guarantee_type_id
$col=7: comment
```

**Age Calculation Logic**:
```php
$millenium = substr($idNo, 0, 1);
$birthyear = substr($idNo, 1, 2);
if ($millenium == 2) $year = $birthyear + 1900;
if ($millenium == 3) $year = $birthyear + 2000;
$age = $thisYear - $year;
```

---

### 12. **addFromExcelTkafol()** - Special Excel Import
**Location**: Line 971  
**Purpose**: Excel import for "Tkafol" charity (ID=0) with different logic

**Key Differences from Regular Import**:
- Sets `charity_id = 0` for all beneficiaries
- Checks for duplicates within same charity only
- Uses different duplicate checking logic

---

### 13. **savearea()** - Area Management
**Location**: Line 702  
**Purpose**: Add or update geographic areas

**Returns**: JSON with new area data for dropdown population

---

### 14. **savedisease()** - Disease Management
**Location**: Line 731  
**Purpose**: Add or update health conditions

**Returns**: JSON with new disease data for dropdown population

---

### 15. **Utility Functions**
**Various Locations**: Support functions for data management

- `gettabledata()` - Generic table data retrieval
- `getselectdata()` - Dropdown data with search
- `getselectmultiple()` - Multi-select dropdown data
- `getMultipledit()` - Multiple disease data for editing
- `getMultidata()` - Multi-record modal display
- `updateVal()` - Update disease names with duplicate checking

---

## 🔄 Workflows

### Workflow 1: Complete Beneficiary Registration
```
┌─────────────────────────────────────────────────────────────┐
│                START: New Beneficiary Form                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Form Dependencies                                  │
│     - Load areas dropdown                                   │
│     - Load diseases dropdown                                │
│     - Load charities (with session filter)                 │
│     - Display add.html template                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Fills Comprehensive Form                           │
│     - Basic demographics (name, age, ID, phone, address)   │
│     - Social info (marital status, work, workplace)        │
│     - Health conditions (diseases, health status)          │
│     - Housing details (floors, rooms, rent, conditions)    │
│     - Appliance inventory (cooker, washer, fridge, etc.)   │
│     - Furniture inventory (bed, wardrobe, couch, etc.)     │
│     - Family members (dynamic rows)                         │
│     - Economic data (income/expenses, dynamic rows)        │
│     - Assessment (needs, opinions, recommendations)        │
│     - Upload photo                                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Form Submission (savedata)                     │
│     - Extract 80+ form fields                              │
│     - Handle image upload with resize                      │
│     - Create beneficiary record                            │
│     - Save main beneficiary data                           │
│     - Call saveFamilyData() for family members             │
│     - Call saveEcoData() for economic data                 │
│     - Return success/error response                         │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Excel Bulk Import Process
```
┌─────────────────────────────────────────────────────────────┐
│           START: Excel File Upload                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. File Processing                                         │
│     - Upload Excel file temporarily                         │
│     - Identify file type (XLS/XLSX)                        │
│     - Load with PHPExcel                                   │
│     - Get worksheet dimensions                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Each Row (Starting Row 4)                      │
│     FOR EACH row in Excel:                                  │
│       │                                                     │
│       ├─→ Extract: name, address, phone, ID, aid amounts   │
│       │                                                     │
│       ├─→ Check for existing beneficiary by ID number      │
│       │                                                     │
│       ├─→ IF EXISTS:                                       │
│       │   └─ Different charity? Add payment record only    │
│       │                                                     │
│       ├─→ IF NEW:                                          │
│       │   ├─ Calculate age from ID number                  │
│       │   ├─ Create beneficiary record                     │
│       │   ├─ Create subvention record                      │
│       │   └─ Create monthly payment record                 │
│       │                                                     │
│       └─→ Use database transactions for integrity          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Finalization                                           │
│     - Delete temporary Excel file                          │
│     - Commit all database transactions                     │
│     - Redirect to show page                                │
│     - Handle any errors with rollback                      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display add beneficiary form |
| `do=addSimple` | Simple form | Display simplified add form |
| `do=show` | Listing | Display beneficiaries list with search |
| `do=edit&id=X` | Edit form | Display edit form for beneficiary X |
| `do=savedata` | `savedata()` | Save beneficiary data (POST) |
| `do=showajax` | `showajax()` | DataTables AJAX data (POST) |
| `do=removecontroller` | `removecontroller()` | Soft delete beneficiary (POST) |
| `do=addexcel` | Excel form | Display Excel upload form |
| `do=addexceltkafol` | Tkafol Excel | Display Tkafol Excel upload form |
| `do=addfromexcel` | `addFromExcel()` | Process Excel import (POST) |
| `do=search` | Search form | Display beneficiary search form |
| `do=getBenData` | `getBenData()` | Search beneficiary by ID (POST) |
| `do=searchLog` | Search log | Display search activity log |
| `do=savearea` | `savearea()` | Add/update area (POST) |
| `do=savedisease` | `savedisease()` | Add/update disease (POST) |

---

## 🧮 Data Management Features

### Multi-Charity Support
```php
// Session-based charity filtering
if ($_SESSION['charityids'])
    $searchQuery .= ' and charities.id in(' . $_SESSION['charityids'] . ')';
```

### Soft Delete System
```php
// Deletion levels:
// del = 0: Active
// del = 1: Updated (edit mode)  
// del = 2: Soft deleted
// del = 5: Special status
```

### Dynamic Family/Economic Data
- Family members: Dynamic form rows with individual save/delete
- Economic data: Income/expense pairs with dynamic management
- Cleanup: Removes records not in current submission

### Image Management
```php
// Upload with automatic resize
$image = uploadImages($handle, "../views/default/images/beneficiaries", 300, 300);

// Update with old image cleanup
$image = updateImages($handle, "oldimage", "../views/default/images/beneficiaries", 300, 300);
unlink("../views/default/images/beneficiaries" . $beneficiaries->image);
```

---

## 🔒 Security & Permissions

### Charity Access Control
```php
// Session-based charity filtering limits access to assigned charities
if ($_SESSION['charityids'] && !$data1 && !$data2 && !$data3 && !$chID)
    $searchQuery .= ' and beneficiaries.charity_id in(' . $_SESSION['charityids'] . ')';
```

### Input Filtering
```php
// All inputs filtered through filter_input
$name = filter_input(INPUT_POST, 'b_name');
$age = filter_input(INPUT_POST, 'age');
$idnumber = filter_input(INPUT_POST, 'idnumber');
```

### Search Activity Logging
```php
// Log all beneficiary searches
$log = R::dispense('charitysearchlog');
$log->user_id = $_SESSION['userid'];
$log->charity_id = $_SESSION['charityids'];
$log->sysdate = date("Y-m-d H:i:s");
$log->idnumber = $idNo;
```

---

## 📊 Performance Considerations

### Database Optimization
1. **Required Indexes**:
   - `beneficiaries(idnumber)` - For duplicate checking
   - `beneficiaries(charity_id)` - For charity filtering
   - `beneficiaries(del, sysdate)` - For listing queries
   - `beneficiaries_family(beneficiaries_id)` - For family lookups
   - `subventionpay(benefeciary_id, charity_id, month)` - For aid history

2. **Large Form Handling**:
   - 80+ fields in main form
   - Dynamic family/economic sections
   - Image upload processing
   - Consider form chunking for very large families

### Excel Import Performance
- Uses transactions for data integrity
- Processes row by row to manage memory
- Duplicate checking on each row (consider batch optimization)
- File cleanup after processing

---

## 🐛 Common Issues & Troubleshooting

### 1. **Age Calculation Errors**
**Issue**: Incorrect ages calculated from ID numbers  
**Cause**: ID number format assumptions

**Debug**:
```php
// Check ID number format
$millenium = substr($idNo, 0, 1);
$birthyear = substr($idNo, 1, 2);
// Expected: 2YYMMDDXXXX or 3YYMMDDXXXX
```

### 2. **Excel Import Failures**
**Issue**: Excel import stops or creates incomplete data  
**Cause**: File format, memory limits, or data validation

**Debug**:
```php
// Check Excel file structure
// Verify data starts at row 4
// Check column mapping matches expected format
```

### 3. **Family/Economic Data Loss**
**Issue**: Family or economic data disappears on edit  
**Cause**: ID mismatch in dynamic form processing

**Fix**: Verify family_id and eco_id hidden fields in forms

### 4. **Charity Permission Issues**  
**Issue**: Users see wrong beneficiaries or get access denied
**Cause**: Session charity IDs not properly set

**Debug**:
```php
// Check session charity assignment
var_dump($_SESSION['charityids']);
```

---

## 🧪 Testing Scenarios

### Test Case 1: Complete Beneficiary Registration
```
1. Fill all form sections (demographics, housing, family, economic)
2. Upload photo
3. Add 3+ family members
4. Add 2+ economic entries
5. Submit and verify all data saved correctly
6. Check image uploaded and resized properly
```

### Test Case 2: Excel Import with Duplicates
```
1. Create Excel with mix of new and existing beneficiaries
2. Include different charity assignments
3. Process import
4. Verify new beneficiaries created
5. Verify existing beneficiaries get payment records only
6. Check age calculations correct
```

### Test Case 3: Multi-Charity Access Control
```
1. Login with restricted charity access
2. Try to view/edit beneficiaries from other charities
3. Verify access properly restricted
4. Test search functionality respects restrictions
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [charityController.php](#) - Charity management
- [subventionController.php](#) - Aid and payment processing
- [Excel Import Documentation](#) - Bulk import procedures

---

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