# Government Controller Documentation

**File**: `/controllers/governmentController.php`  
**Purpose**: Manages government regions (provinces/governorates) and their associated client areas  
**Last Updated**: December 20, 2024  
**Total Functions**: 6  
**Lines of Code**: ~381

---

## 📋 Overview

The Government Controller is a geographical organization module that manages government regions (provinces/governorates) and links them to customer service areas. It handles:
- Government region master data (Arabic and English names)
- Mapping government regions to customer areas
- Government region activation/deactivation
- Hierarchical organization of customer service territories
- Multi-area assignment per government region
- Referential integrity between government regions and customer areas

### Primary Functions
- [x] Create government regions with bilingual names
- [x] Associate multiple customer areas to each government region
- [x] Edit and update government region configurations
- [x] Soft delete government regions with dependency checks
- [x] View all government regions and their areas
- [x] Manage government region status (active/inactive)
- [x] Prevent deletion when client companies are linked

### Related Controllers
- [clientareaController.php](#) - Customer area management
- [clientController.php](clientController.md) - Customer management
- [userController.php](userController.md) - User management with area restrictions

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **government** | Government regions master | governmetid, governmentname, governmentname_en, sys_date, user_id, is_active, is_del |
| **goverarea** | Government-to-area mapping | governmentid, clientareaid |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **clientarea** | Customer service areas | id, name, description |
| **youtubelink** | Tutorial/help links | youtubelinkid, title, url |
| **client** | Customer data (dependency check) | clientid, clientarea |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Government Region Form
**Location**: Lines 103-121  
**Purpose**: Display form to create new government region with area assignments

**Process Flow**:
1. Load all existing government regions
2. Extract their associated area IDs into array
3. Load all available customer areas
4. Display add form with available areas for selection

**Template Variables**:
- `$goverArray` - Array of area IDs already assigned to governments
- `$clientareaData` - All available customer areas

---

### 2. **add()** - Create New Government Region
**Location**: Lines 225-261  
**Purpose**: Insert new government region and link to selected customer areas

**Function Signature**:
```php
function add() {
    global $governArea, $governAreaDAO, $government, $governmentDAO;
}
```

**Process Flow**:
1. Extract government name (Arabic and English) from POST
2. Create government master record if name provided
3. Loop through area iteration count from form
4. Insert government-to-area mappings for selected areas
5. Skip areas with value '-1' (unselected)

**Key Variables**:
- `$area_itration` - Number of area selection fields in form
- `$governmentid` - Generated ID from government insert
- `$areaid_N` - Area ID from dynamic form fields

---

### 3. **show()** - Display All Government Regions
**Location**: Lines 282-296  
**Purpose**: Load and display all government regions in tabular format

**Process Flow**:
1. Query all government regions using DAO
2. Set count result flag for template conditional display
3. Assign data to Smarty template
4. Include YouTube tutorial links

**Template Variables**:
- `$governmentData` - All government records
- `$countResult` - Boolean flag for data existence
- `$youtubes` - Tutorial links

---

### 4. **delete($id)** - Soft Delete Government Region
**Location**: Lines 263-279  
**Purpose**: Safely remove government region with dependency validation

**Function Signature**:
```php
function delete($id) {
    global $governmentDAO, $governAreaDAO;
}
```

**Process Flow**:
1. Check for associated areas using `deleteByGovernmentid()`
2. If areas found, return policy validation error (code 1)
3. If safe to delete, soft delete government (set `is_del = 1`)
4. Display warning message if deletion blocked

**Dependency Check**:
```php
$loadgovernmentData = $governAreaDAO->deleteByGovernmentid($id);
if($loadgovernmentData == '') {
    return 1; // Has dependencies, cannot delete
}
```

---

### 5. **edit($id)** - Load Government for Editing
**Location**: Lines 313-338  
**Purpose**: Prepare government data and areas for edit form

**Process Flow**:
1. Load government master data by ID
2. Load all associated areas for this government
3. Load all available customer areas for selection
4. Calculate area count for dynamic form rendering
5. Assign all data to edit template

**Template Variables**:
- `$governmentData` - Government master record
- `$governmentClientareaData` - Currently associated areas
- `$loadAreaIds` - Count of associated areas (zero-indexed)
- `$allClientarea` - All available areas for selection

---

### 6. **update()** - Update Government Region
**Location**: Lines 341-379  
**Purpose**: Update government master data and area associations

**Process Flow**:
1. Extract updated government name and status from POST
2. Update government master record
3. Delete all existing area associations
4. Re-insert new area associations from form
5. Handle activation status changes

**Key Operations**:
```php
// Update master record
$governmentDAO->update($government);

// Clear old associations
$governAreaDAO->deleteByGovernmentid($oldGovernmentId);

// Re-create associations
for($i = 0; $i <= $area_itration; $i++) {
    // Insert valid area associations
}
```

---

## 🔄 Workflows

### Workflow 1: Create New Government Region
```
┌─────────────────────────────────────────────────────────────┐
│              START: Access Government Management            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Add Form                                           │
│     - Display government name fields (AR/EN)               │
│     - Load all available customer areas                    │
│     - Show areas not yet assigned to other governments     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Submit Government Data                                  │
│     - Validate government names                            │
│     - Select customer areas to associate                   │
│     - Set activation status                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Creation                                        │
│     - Insert government master record                      │
│     - Create government-to-area mappings                   │
│     - Set system date and user ID                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Success Confirmation                                    │
│     - Display success message                              │
│     - Return to government list                            │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Delete Government Region
```
┌─────────────────────────────────────────────────────────────┐
│              START: Select Government to Delete            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Dependency Check                                        │
│     - Check for client companies in linked areas           │
│     - Verify no active business relationships              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Deletion Decision                                       │
│   ┌─────────────────────────────────────────────────────────┤
│   │ IF dependencies exist:                                  │
│   │ ├─→ Display Arabic warning message                      │
│   │ ├─→ "Cannot delete - companies linked to this region"  │
│   │ └─→ Redirect to government list                         │
│   │                                                         │
│   │ IF safe to delete:                                      │
│   │ ├─→ Set is_del = 1 (soft delete)                      │
│   │ ├─→ Keep historical data integrity                      │
│   │ └─→ Display success message                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Return to Government List                               │
│     - Refresh government listing                           │
│     - Show updated status                                   │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display add government form |
| `do=add` | `add()` | Process new government creation |
| `do=show` | `show()` | Display all government regions |
| `do=delete&id=X` | `delete(X)` | Delete government region with validation |
| `do=edit&id=X` | `edit(X)` | Load government for editing |
| `do=update` | `update()` | Process government updates |
| `do=sucess` | Display success | Show success message |
| `do=error` | Display error | Show error message |

### Required Parameters by Action

**Add Government**:
- `governmentname` - Arabic name
- `governmentname_en` - English name  
- `area_itration` - Number of area selection fields
- `areaid_N` - Area IDs (N = 0 to area_itration)

**Edit Government** (`do=edit`):
- `id` - Government ID

**Update Government**:
- `oldGovernmentId` - Government ID
- `governmentname` - Updated Arabic name
- `governmentname_en` - Updated English name
- `is_active` - Activation status (0/1)
- `area_itration` - Number of area fields

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
// All actions require authentication except default form
include_once("../public/authentication.php");
```

### Input Validation
- All POST parameters processed without explicit sanitization
- Relies on DAO layer for SQL injection prevention
- Government ID cast to integer for delete operations

### Business Rules
1. **Government Names**: Arabic name required, English optional
2. **Area Assignment**: Multiple areas can be assigned to one government
3. **Deletion Policy**: Cannot delete if companies exist in linked areas
4. **Soft Delete**: Uses `is_del` flag instead of physical deletion
5. **Audit Trail**: Captures `sys_date` and `user_id` for all operations

---

## 📊 Data Relationships

### Government → Areas Mapping
```sql
-- One government can have multiple areas
SELECT g.governmentname, ca.name as area_name
FROM government g
JOIN goverarea ga ON g.governmetid = ga.governmentid  
JOIN clientarea ca ON ga.clientareaid = ca.id
WHERE g.is_del = 0 AND g.is_active = 1;
```

### Dependency Check Query
```sql
-- Check if government can be safely deleted
SELECT COUNT(*) as client_count
FROM client c
JOIN clientarea ca ON c.clientarea = ca.id
JOIN goverarea ga ON ca.id = ga.clientareaid
WHERE ga.governmentid = ?;
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Cannot Delete Government Region**
**Issue**: Error message in Arabic about linked companies  
**Cause**: Client companies exist in areas assigned to this government

**Debug**:
```sql
-- Find which clients are blocking deletion
SELECT c.clientname, ca.name as area_name
FROM client c
JOIN clientarea ca ON c.clientarea = ca.id  
JOIN goverarea ga ON ca.id = ga.clientareaid
WHERE ga.governmentid = [GOVERNMENT_ID];
```

### 2. **Area Selection Not Working**
**Issue**: Areas don't appear in dropdown  
**Cause**: Areas already assigned to other governments

**Fix**: Check `$goverArray` logic in default action to exclude assigned areas

### 3. **Bilingual Name Issues**
**Issue**: English names not displaying correctly  
**Cause**: Character encoding or empty `governmentname_en` field

**Debug**:
```sql
-- Check for empty English names
SELECT governmetid, governmentname, governmentname_en 
FROM government 
WHERE governmentname_en IS NULL OR governmentname_en = '';
```

---

## 🧪 Testing Scenarios

### Test Case 1: Government Creation
```
1. Access government management (empty do parameter)
2. Fill Arabic government name
3. Fill English government name
4. Select multiple customer areas
5. Submit form
6. Verify government created with selected areas
7. Check government appears in listing
```

### Test Case 2: Deletion Validation
```
1. Create government with areas
2. Create client in one of the assigned areas
3. Attempt to delete government
4. Verify deletion blocked with Arabic message
5. Remove client from area
6. Retry deletion - should succeed
```

### Test Case 3: Update Government
```
1. Edit existing government
2. Change Arabic/English names
3. Modify area assignments
4. Toggle activation status
5. Verify all changes saved correctly
6. Check area mappings updated
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientareaController.php](#) - Customer area management
- [clientController.php](clientController.md) - Customer management
- [Database Schema Documentation](#) - Table relationships

---

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