# Charity Controller Documentation

**File**: `/controllers/charityController.php`  
**Purpose**: Manages charity organizations and their beneficiaries within the ERP system  
**Last Updated**: December 20, 2024  
**Total Functions**: 5  
**Lines of Code**: ~234

---

## 📋 Overview

The Charity Controller is a specialized module for managing charitable organizations and their associated beneficiaries. It handles:
- Charity organization registration and management
- Image upload for charity profiles
- Charity center associations
- Beneficiary tracking and management
- Ajax-powered data tables with filtering
- Soft delete functionality
- Mass operations on beneficiaries

### Primary Functions
- [x] Add and edit charity organizations
- [x] Image upload and management for charity profiles
- [x] Associate charities with centers
- [x] Track beneficiary counts per charity
- [x] Mass delete all beneficiaries for a charity
- [x] Ajax data table with search and pagination
- [x] Soft delete with audit trail

### Related Controllers
- [beneficiariesController.php](beneficiariesController.md) - Beneficiary management
- [subventionController.php](#) - Charity subsidies
- [clientController.php](clientController.md) - Client management (similar structure)

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **charities** | Charity organization master | id, charityname, charitynumber, charityphone, charityaddress, charityimage, charitynote, center_id, createdate, del, sysdate, user_id |
| **charitiescenter** | Charity centers/locations | id, name, description, del |

### Related Tables (Referenced)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **beneficiaries** | Charity beneficiaries | id, charity_id, del |
| **subvention** | Charity subsidies | id, charity_id |
| **subventionpay** | Subsidy payments | id, charity_id, benefeciary_id, del |
| **user** | System users | userid, employeename, username |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Charity Form
**Location**: Lines 9-18  
**Purpose**: Display the charity registration form

**Process Flow**:
1. Load available charity centers
2. Display header template
3. Show charity add form
4. Display footer with charity menu active

**Template**: `charityview/add.html`

---

### 2. **show()** - List Charities
**Location**: Lines 18-30  
**Purpose**: Display charity listing page with data tables

**Process Flow**:
1. Check authentication
2. Set display mode if specified (`show=2`)
3. Assign current date
4. Display charity show template

**Template**: `charityview/show.html`

---

### 3. **edit()** - Edit Charity Form
**Location**: Lines 30-44  
**Purpose**: Display charity editing form with existing data

**Process Flow**:
1. Check authentication
2. Load charity record by ID
3. Load available charity centers
4. Assign data to template
5. Display edit form

**Template**: `charityview/edit.html`

---

### 4. **savedata()** - Save/Update Charity
**Location**: Lines 55-102  
**Purpose**: Create new charity or update existing charity record

**Function Flow**:
```php
function savedata() {
    // Get form data
    $charityname = filter_input(INPUT_POST, 'charityname');
    $createdate = filter_input(INPUT_POST, 'createdate');
    $charityphone = filter_input(INPUT_POST, 'charityphone');
    $charitynumber = filter_input(INPUT_POST, 'charitynumber');
    $charityaddress = filter_input(INPUT_POST, 'charityaddress');
    $charitynote = filter_input(INPUT_POST, 'charitynote');
    $center_id = filter_input(INPUT_POST, 'center_id');
    $charityid = filter_input(INPUT_POST, 'charityid');
    
    if (!$charityid) {
        // Create new charity
        $charities = R::dispense('charities');
        $charityimage = uploadImages($handle, "../views/default/images/charities", 300, 300);
    } else {
        // Update existing charity
        $charities = R::load('charities', $charityid);
        $charityimage = updateImages($handle, "oldcharityimage", "../views/default/images/charities", 300, 300);
        unlink("../views/default/images/charities" . $charities->charityimage);
    }
    
    // Save charity data
    R::store($charities);
}
```

**Image Handling**:
- Upload path: `../views/default/images/charities`
- Image resize: 300x300 pixels
- Old image cleanup on update

---

### 5. **showajax()** - Ajax Data Table
**Location**: Lines 103-201  
**Purpose**: Provide data for charity listing with search, pagination, and filtering

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

**Search Filters**:
- Date range filtering (`start_date`, `end_date`)
- Charity ID filtering (`data1`)
- Branch filtering (`data3`)
- Status filtering (`del`)
- Session-based charity restrictions (`$_SESSION['charityids']`)

**Columns Returned**:
1. ID
2. Charity image (40x40px with fallback)
3. Charity name
4. Charity number
5. Phone number
6. System date
7. Total beneficiaries count
8. Paid beneficiaries count
9. Edit button (if active)
10. Delete button (if active)

**Special Features**:
- Dynamic beneficiary counts via sub-queries
- Image display with blank fallback
- Status-based action buttons
- Session-based access control

---

### 6. **removecontroller()** - Soft Delete Charity
**Location**: Lines 204-220  
**Purpose**: Mark charity as deleted (soft delete)

**Process Flow**:
1. Get charity ID from POST
2. Load charity record
3. Set `del = 2` (deleted status)
4. Record deletion timestamp and user
5. Save changes

**Audit Fields Updated**:
- `del = 2`
- `del_date = current timestamp`
- `deluserid = current user ID`

---

### 7. **removeAllBen()** - Mass Delete Beneficiaries
**Location**: Lines 222-233  
**Purpose**: Remove all beneficiaries associated with a charity (hard delete)

**Tables Affected**:
```sql
DELETE FROM beneficiaries WHERE charity_id = ?
DELETE FROM subvention WHERE charity_id = ?
DELETE FROM subventionpay WHERE charity_id = ?
```

**Warning**: This is a hard delete operation that permanently removes data.

---

## 🔄 Workflows

### Workflow 1: Charity Registration
```
┌─────────────────────────────────────────────────────────────┐
│                    START: Charity Registration              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Registration Form                               │
│     - Load charity centers                                  │
│     - Show form template                                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Fills Form                                         │
│     - Basic charity information                             │
│     - Upload charity image                                  │
│     - Select charity center                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Form Submission                                 │
│     - Validate input data                                   │
│     - Process image upload (300x300)                       │
│     - Create charity record                                 │
│     - Set audit fields                                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save and Respond                                        │
│     - Store charity in database                             │
│     - Return success/failure status                         │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Charity Management
```
┌─────────────────────────────────────────────────────────────┐
│                    START: Charity Management                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Charity List                                       │
│     - Apply user permissions                                │
│     - Load active charities                                 │
│     - Display with data table                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Actions                                            │
│     ├─→ Edit charity details                               │
│     ├─→ Delete charity (soft delete)                       │
│     ├─→ Mass delete beneficiaries                          │
│     └─→ Filter/search charities                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Actions                                         │
│     - Update charity records                                │
│     - Maintain audit trail                                  │
│     - Update beneficiary counts                             │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display charity add form |
| `do=show` | Show view | Display charity listing page |
| `do=edit&id={id}` | Edit view | Display charity edit form |
| `do=savedata` | `savedata()` | Process charity save/update |
| `do=showajax` | `showajax()` | Ajax data for charity table |
| `do=removecontroller` | `removecontroller()` | Soft delete charity |
| `do=removeAllBen` | `removeAllBen()` | Mass delete beneficiaries |

---

## 🔒 Security & Permissions

### Session-Based Access Control
```php
// Charity access restriction
if ($_SESSION['charityids'] && !$data1)
    $searchQuery .= ' and charities.id in(' . $_SESSION['charityids'] . ')';
```

### Input Sanitization
- All form inputs filtered with `filter_input()`
- File uploads validated through upload library
- SQL injection prevented by RedBean ORM

### Audit Trail
- Creation tracking: `sysdate`, `user_id`
- Update tracking: `update_date`, `updateuserid`  
- Deletion tracking: `del_date`, `deluserid`

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Required**:
   - `charities(del, sysdate)`
   - `charities(center_id)`
   - `beneficiaries(charity_id, del)`

2. **Query Optimization**:
   - Beneficiary counts calculated via sub-queries
   - Efficient WHERE clause filtering
   - Pagination support

### Image Management
- Automatic image resizing (300x300)
- Old image cleanup on updates
- Fallback to blank.png for missing images

---

## 🐛 Common Issues & Troubleshooting

### 1. **Image Upload Failures**
**Issue**: Images not uploading or displaying  
**Cause**: File permissions or path issues

**Debug**:
```php
// Check image path permissions
ls -la ../views/default/images/charities/
chmod 755 ../views/default/images/charities/
```

### 2. **Beneficiary Count Mismatch**
**Issue**: Counts don't match actual beneficiaries  
**Cause**: Soft delete status confusion

**Fix**:
```sql
-- Check beneficiary soft delete status
SELECT COUNT(*) FROM beneficiaries WHERE del < 2 AND charity_id = {id};
SELECT COUNT(DISTINCT benefeciary_id) FROM subventionpay WHERE del < 2 AND charity_id = {id};
```

### 3. **Session Restrictions Not Working**
**Issue**: Users see charities they shouldn't  
**Cause**: Session charityids not set properly

**Debug**:
```php
// Check session values
var_dump($_SESSION['charityids']);
// Should contain comma-separated charity IDs
```

---

## 🧪 Testing Scenarios

### Test Case 1: Charity Registration
```
1. Navigate to charity controller (empty do parameter)
2. Fill charity form with all required fields
3. Upload charity image (JPG/PNG)
4. Submit form
5. Verify charity created with correct data
6. Check image uploaded and resized correctly
```

### Test Case 2: Beneficiary Count Accuracy
```
1. Create charity with known beneficiaries
2. Add/remove beneficiaries through beneficiaries controller
3. Check charity listing shows correct counts
4. Verify paid vs total beneficiary counts match
```

### Test Case 3: Mass Delete Operation
```
1. Create charity with multiple beneficiaries
2. Use removeAllBen function
3. Verify all related records deleted
4. Check data integrity maintained
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [beneficiariesController.md](beneficiariesController.md) - Beneficiary management
- [Image Upload Library](#) - File upload handling

---

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