# Properties Controller Documentation

**File**: `/controllers/propertiesController.php`  
**Purpose**: Manages system properties, permissions, and user group access rights  
**Last Updated**: December 20, 2024  
**Total Functions**: 4  
**Lines of Code**: 228

---

## 📋 Overview

The Properties Controller is a system administration module that handles application properties, permissions, and user group access control. It provides:
- System property definition and management
- User group permission assignment
- Property inheritance and defaults
- Multi-language property support
- Bulk permission operations
- Property-based access control
- Dynamic permission matrix

### Primary Functions
- [x] System property creation and editing
- [x] User group permission assignment
- [x] Property default value management
- [x] Multi-language property names
- [x] Bulk permission updates
- [x] Property hierarchy management
- [x] Access control matrix
- [x] Permission inheritance

### Related Controllers
- [firms.php](firms.md) - Company management
- [propertyrightsreport.php](propertyrightsreport.md) - Property rights reporting

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **properties** | System property definitions | propertyid, propertyname, propertyname_en, propertyurl, propertyparent, propertydefault |
| **relusergroupproperties** | User group property permissions | propertyid, usergroupid, propertyvalue |
| **usergroup** | User group definitions | usergroupid, usergroupname, description |

---

## 🔑 Key Functions

### 1. **Default Action / Property Management** - Property Administration Interface
**Location**: Line 73  
**Purpose**: Display property management interface with existing properties

**Process Flow**:
1. Load all existing properties via `loadproperity()`
2. Assign property data to Smarty template
3. Display via `propertiesview/add.html`
4. Provide interface for adding new properties

**Function Signature**:
```php
// Triggered when: $do is empty (default action)
$propertiesData = loadproperity();
$smarty->assign("propertiesData", $propertiesData);
```

**Features**:
- View all system properties
- Add new property form
- Property listing with hierarchy
- Multi-language support

---

### 2. **add()** - Create New System Property
**Location**: Line 84  
**Purpose**: Add new system property with automatic user group permission setup

**Function Signature**:
```php
elseif ($do == "add")
// Called via: POST request with property data
```

**Process Flow**:
1. Validate and extract POST data
2. Create new property record
3. Query all existing user groups
4. Auto-assign property to all user groups with default value
5. Handle success/error redirection

**Property Creation Logic**:
```php
$myProperities->propertyname = $propertyName;
$myProperities->propertyparent = $propertyParent;
$myProperities->propertydefault = $propertyDefault;
$myProperities->propertyurl = $propertyurl;
$myProperities->propertyname_en = $propertyname_en;
$propertyId = $myProperitiesRecord->insert($myProperities);
```

**Auto-Assignment Process**:
```php
foreach ($usergroupData as $usergroup) {
    $myRelusergroup->propertyid = $propertyId;
    $myRelusergroup->usergroupid = $usergroupId;
    $myRelusergroup->propertyvalue = $propertyDefault;
    $myRelusergroupRecord->insert($myRelusergroup);
}
```

---

### 3. **show()** - Property Listing View
**Location**: Line 106  
**Purpose**: Display all properties in listing format

**Process Flow**:
1. Query all properties from database
2. Load property data for form population
3. Display via `propertiesview/add.html` (same template as default)

---

### 4. **edit() / update()** - Property Modification
**Location**: Line 118 (edit), Line 129 (update)  
**Purpose**: Edit existing property details

**Edit Process Flow**:
```php
$theid = $_GET['id'];
$getallpropwithid = $myProperitiesRecord->load($theid);
$smarty->assign("getallpropwithid", $getallpropwithid);
```

**Update Process Flow**:
```php
$newprop = new Propertie;
$newprop->propertyid = $idprp;
$newprop->propertyname = $nameprp;
$newprop->propertyurl = $urlprp;
$myProperitiesRecord->updates($newprop);
```

---

## 🔄 Workflows

### Workflow 1: New Property Creation
```
┌─────────────────────────────────────────────────────────────┐
│                START: Add New Property                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Property Definition                                     │
│     - Property name (Arabic)                               │
│     - Property name (English)                              │
│     - Property URL/controller                              │
│     - Parent property (hierarchy)                          │
│     - Default value (0/1)                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Property Creation                                       │
│     INSERT INTO properties:                                 │
│       │                                                     │
│       ├─→ propertyname                                     │
│       ├─→ propertyname_en                                  │
│       ├─→ propertyurl                                      │
│       ├─→ propertyparent                                   │
│       └─→ propertydefault                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Auto-Assignment to User Groups                          │
│     FOR EACH existing user group:                           │
│       │                                                     │
│       ├─→ Create relusergroupproperties record             │
│       ├─→ Set propertyvalue = propertydefault              │
│       └─→ Link property to user group                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Complete                                                │
│     - Property created and available                        │
│     - All user groups have default access                   │
│     - Property appears in permission matrix                 │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Property Permission Management
```
┌─────────────────────────────────────────────────────────────┐
│           START: Manage Property Permissions                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Property Matrix                                    │
│     - Query all properties                                  │
│     - Query all user groups                                 │
│     - Load current permission assignments                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Permission Matrix                               │
│     Properties (rows) × User Groups (columns)               │
│       │                                                     │
│       ├─→ Show current permissions (0/1)                   │
│       ├─→ Enable bulk editing                              │
│       └─→ Highlight inherited permissions                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Permission Updates                                      │
│     UPDATE relusergroupproperties:                          │
│       │                                                     │
│       ├─→ Change propertyvalue (0 = deny, 1 = allow)      │
│       ├─→ Apply to multiple groups if bulk operation       │
│       └─→ Validate permission hierarchy                    │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Property management interface |
| `do=add` | `add()` | Create new property |
| `do=show` | `show()` | List all properties |
| `do=edit` | `edit()` | Edit property form |
| `do=update` | `update()` | Update property data |
| `do=sucess` | Success page | Operation completed |
| `do=error` | Error page | Operation failed |

### Required Parameters by Action

**Add Property** (`do=add`):
- `propertyname` - Property name (Arabic)
- `propertyname_en` - Property name (English)
- `propertyparent` - Parent property ID
- `propertydefault` - Default permission value
- `propertyurl` - Controller URL

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

**Update Property** (`do=update`):
- `propertyid` - Property ID
- `propertyname` - Updated name
- `propertyurl` - Updated URL

---

## 🔒 Security & Permissions

### Access Control
```php
// Authentication required for all operations
// include_once("../public/authentication.php");
```

### Input Sanitization
- All POST data accessed through `$_POST` arrays
- Property IDs cast to integers where appropriate
- SQL injection prevention via DAO layer

### Permission Inheritance
- New properties auto-assigned to all user groups
- Default values applied consistently
- Hierarchical permission structure supported

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `properties(propertyparent)`
   - `relusergroupproperties(propertyid, usergroupid)`
   - `usergroup(usergroupid)`

2. **Query Optimization**:
   - Batch inserts for user group assignments
   - Efficient property hierarchy queries
   - Minimal database calls in loops

### Memory Management
- Large user group counts may impact auto-assignment
- Property hierarchy depth should be limited
- Consider caching for frequently accessed properties

---

## 🐛 Common Issues & Troubleshooting

### 1. **Property Auto-Assignment Failures**
**Issue**: New properties not assigned to all user groups  
**Cause**: Transaction failures or missing user groups

**Debug**:
```php
// Check user group count
$usergroupData = $myUserGroupRecord->queryAll();
echo "User groups found: " . count($usergroupData);

// Verify assignments after creation
$assignments = $myRelusergroupRecord->queryByPropertyId($propertyId);
```

### 2. **Property Hierarchy Issues**
**Issue**: Parent-child relationships not working  
**Cause**: Circular references or invalid parent IDs

**Debug**:
```sql
-- Check for circular references
WITH RECURSIVE prop_tree AS (
  SELECT propertyid, propertyparent, 1 as level
  FROM properties WHERE propertyparent = 0
  UNION ALL
  SELECT p.propertyid, p.propertyparent, pt.level + 1
  FROM properties p
  JOIN prop_tree pt ON p.propertyparent = pt.propertyid
  WHERE pt.level < 10
)
SELECT * FROM prop_tree WHERE level > 5;
```

### 3. **Permission Matrix Performance**
**Issue**: Slow loading with many properties/groups  
**Cause**: N+1 query problems or missing indexes

**Solution**:
- Implement JOIN-based queries for permission matrix
- Add database indexes on foreign key columns
- Consider pagination for large permission sets

---

## 🧪 Testing Scenarios

### Test Case 1: Property Creation
```
1. Access property management interface
2. Fill out new property form
3. Submit and verify success redirect
4. Check property appears in listing
5. Verify all user groups have default permission
```

### Test Case 2: Property Hierarchy
```
1. Create parent property
2. Create child property with parent reference
3. Verify hierarchy displays correctly
4. Test permission inheritance
```

### Test Case 3: Permission Management
```
1. Access permission matrix
2. Change property permissions for user group
3. Verify changes saved correctly
4. Test user access with new permissions
```

### Test Case 4: Multi-language Support
```
1. Create property with Arabic and English names
2. Verify both names stored correctly
3. Test display in different language contexts
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [propertyrightsreport.md](propertyrightsreport.md) - Property rights reporting
- [User Group Management](#) - User group administration

---

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