# Real Estate Units Owners Controller Documentation

**File**: `/controllers/realestateunitsowners.php`  
**Purpose**: Manages property ownership records, purchase payments, and installment tracking for real estate owners/suppliers  
**Last Updated**: December 20, 2024  
**Total Functions**: 8  
**Lines of Code**: ~482

---

## 📋 Overview

The Real Estate Units Owners Controller handles the management of property ownership transactions between suppliers (property owners) and the company. It manages property purchase agreements, advance payments, installment schedules, and payment tracking. This controller is specifically designed for tracking expenses related to property acquisitions.

### Primary Functions
- [x] Property purchase agreement management
- [x] Advance payment processing
- [x] Installment payment scheduling
- [x] Payment tracking and status updates
- [x] Property availability status management
- [x] Expense record integration
- [x] Payment history tracking
- [x] Installment consolidation and editing

### Related Controllers
- [expensesController.php](expensesController.md) - Expense processing via CURL
- [realestateunitsrenters.php](realestateunitsrenters.md) - Property rental management
- [realestateunitsreports.php](realestateunitsreports.md) - Property reporting

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **realestateunitspaids** | Main ownership payment records | id, supplierid, realestateid, valuerents, advancepayment, totalpaid, payed, numberinstallments, del |
| **realestateunitpaidinstallments** | Individual installment records | id, realestateunitpaidid, valuerent, totalpaid, installmentdate, payed, del |
| **realestateunitpaidhistorys** | Payment history tracking | id, realestateunitpaidid, realestateunitpaidinstallmentid, supplierid, advancepayment, expenseid |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **realestates** | Property master data | id, realestatename, savaible, expenstypeid |
| **supplier** | Property owners/suppliers | supplierid, suppliername |
| **expenses** | Generated expense records | expensesid, expensesdate, dailyentryid |
| **user** | System users | userid, employeename |

---

## 🔑 Key Functions

### 1. **savedata()** - Main Save Function
**Location**: Line 46  
**Purpose**: Creates or updates property ownership records with installment schedules

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

**Process Flow**:
1. Extract form data (supplier, property, amounts, installments)
2. Create/update main ownership record (`realestateunitspaids`)
3. Update property availability status
4. Process advance payment if provided
5. Loop through installment schedule
6. Create/update installment records
7. Process payments via expense system

**Payment Status Logic**:
```php
if ($totalpaid == 0) {
    $payed = 0; // No payment
} else if ($valuerents > $totalpaid) {
    $payed = 1; // Partial payment
} else {
    $payed = 2; // Fully paid
    // Set property as unavailable
}
```

**Key Variables**:
- `$supplierid` - Property owner ID
- `$realestateid` - Property ID
- `$valuerents` - Total property value
- `$advancepayment` - Initial advance payment
- `$numberinstallments` - Number of payment installments

---

### 2. **paieds()** - Payment Processing
**Location**: Line 198  
**Purpose**: Creates expense records and payment history for property payments

**Function Signature**:
```php
function paieds($supplierid, $realestateid, $advancepayment, $realestateunitpaidid, $realestateunitpaidinstallmentid)
```

**Process Flow**:
1. Load supplier and property information
2. Build expense description in Arabic
3. Prepare expense data array
4. Call expenses controller via CURL
5. Create payment history record
6. Link expense ID back to payment record

**Expense Description Format**:
```php
$expensesname = ' مصروف للعقار  ' . $realestates->realestatename;
$expensecomment = ' مصروف للعقار  ' . $realestates->realestatename . ' من  المأجر  ' . $supplier['suppliername'] . ' بتاريخ  ' . $today;
```

---

### 3. **savepayed()** - Additional Payment Processing
**Location**: Line 160  
**Purpose**: Processes additional payments for existing installments

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

**Process Flow**:
1. Get payment details from POST data
2. Update main payment record total
3. Update installment payment amount
4. Recalculate payment status
5. Update property availability if fully paid
6. Process expense via `paieds()` function

**Payment Status Update**:
```php
$realestateunitspaids->totalpaid = (int)$realestateunitspaids->totalpaid + (int)$payed;
if ($realestateunitspaids->valuerents > $realestateunitspaids->totalpaid) {
    $realestateunitspaids->payed = 1; // Still partial
} else {
    $realestateunitspaids->payed = 2; // Now fully paid
}
```

---

### 4. **showajax()** - Data Table Display
**Location**: Line 247  
**Purpose**: Provides AJAX data for DataTables display with filtering and pagination

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

**Process Flow**:
1. Define table columns for DataTables
2. Build search query with filters
3. Add permission-based restrictions
4. Execute paginated query with joins
5. Format data for JSON response
6. Include action buttons for each row

**Search Filters**:
- Date range (`start_date`, `end_date`)
- Supplier filter (`supplierid`)
- Property filter (`realestateid`)
- Deletion status (`del`)

**SQL Query Structure**:
```sql
SELECT realestateunitspaids.*, employeename, suppliername, realestatename 
FROM realestateunitspaids 
LEFT JOIN user ON realestateunitspaids.adduserid = user.userid 
LEFT JOIN supplier ON realestateunitspaids.supplierid = supplier.supplierid
LEFT JOIN realestates ON realestateunitspaids.realestateid = realestates.id
WHERE realestateunitspaids.clientid = 0 [filters]
```

---

### 5. **removecontroller()** - Soft Delete
**Location**: Line 380  
**Purpose**: Soft deletes ownership records and reverses related transactions

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

**Process Flow**:
1. Load ownership record by ID
2. Set deletion flags and timestamps
3. Reset property availability
4. Delete related expense via CURL
5. Mark installments as deleted
6. Delete installment expenses
7. Update payment history status

---

### 6. **removeappend()** - Remove Installment
**Location**: Line 421  
**Purpose**: Removes individual installment records

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

**Process Flow**:
1. Load installment record
2. Set deletion status
3. Reset property availability
4. Delete related expense
5. Update parent payment totals
6. Decrease installment count

---

### 7. **editid()** - Consolidate Installments
**Location**: Line 348  
**Purpose**: Consolidates unpaid installments into the last installment

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

**Process Flow**:
1. Find all unpaid installments for the ownership record
2. Calculate total unpaid amount
3. Delete unpaid installments (set del = 2)
4. Add total to the last installment
5. Update installment count

**Consolidation Logic**:
```php
foreach($realestateunitpaidinstallments as $installment) {
    if ($installment->totalpaid == 0) {
        $valuerent += $installment->valuerent;
        $installment->del = 2; // Mark for deletion
    }
}
// Add accumulated amount to last installment
```

---

### 8. **CURL_IT2()** - External API Communication
**Location**: Line 454  
**Purpose**: Handles CURL requests to other controllers (primarily expenses)

**Function Signature**:
```php
function CURL_IT2($data_arr = array(), $url)
```

**Process Flow**:
1. Build full URL to target controller
2. Add session data to request
3. Execute CURL POST request
4. Return response from target controller

---

## 🔄 Workflows

### Workflow 1: New Property Purchase Agreement
```
┌─────────────────────────────────────────────────────────────┐
│           START: Create Property Purchase Agreement         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Enter Purchase Details                                  │
│     - Select property                                       │
│     - Select supplier/owner                                 │
│     - Enter total value                                     │
│     - Set advance payment                                   │
│     - Define installment schedule                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Create Ownership Record                                 │
│     - Insert into realestateunitspaids                     │
│     - Set property as unavailable (savaible = 1)           │
│     - Calculate payment status                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Advance Payment (if any)                       │
│     - Call paieds() function                               │
│     - Create expense record via CURL                       │
│     - Update payment history                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Create Installment Schedule                             │
│     FOR EACH installment:                                   │
│       ├─→ Insert installment record                        │
│       ├─→ Set due date                                     │
│       ├─→ Process payment if amount > 0                    │
│       └─→ Create expense record if paid                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Update Final Status                                     │
│     - Check if fully paid                                  │
│     - Update property availability if needed               │
│     - Return success confirmation                          │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default display | Show add form |
| `do=show` | Display template | Show data table view |
| `do=edit&id=X` | Display template | Edit existing ownership record |
| `do=savedata` | `savedata()` | Create/update ownership record |
| `do=showajax` | `showajax()` | AJAX data for DataTables |
| `do=removeappend` | `removeappend()` | Remove installment record |
| `do=removecontroller` | `removecontroller()` | Soft delete ownership record |
| `do=savepayed` | `savepayed()` | Process additional payment |
| `do=editid` | `editid()` | Consolidate installments |

### Required Parameters by Action

**Save Data** (`do=savedata`):
- `supplierid` - Property owner ID
- `realestateid` - Property ID
- `valuerents` - Total property value
- `advancepayment` - Initial payment amount
- `numberinstallments` - Number of installments
- `valuerent_N` - Amount for each installment N
- `installmentdate_N` - Due date for installment N

**Edit View** (`do=edit`):
- `id` - Ownership record ID

**Additional Payment** (`do=savepayed`):
- `realestateunitpaidid` - Main payment record ID
- `realestateunitpaidinstallmentid` - Installment record ID
- `payed` - Additional payment amount

---

## 🧮 Calculation Methods

### Payment Status Calculation
```php
if ($totalpaid == 0) {
    $payed = 0; // No payment made
} else if ($valuerents > $totalpaid) {
    $payed = 1; // Partially paid
} else {
    $payed = 2; // Fully paid
    // Property becomes unavailable for new transactions
}
```

### Property Availability Management
```php
// When creating new ownership record
R::exec("UPDATE `realestates` SET `savaible`= 1 WHERE id = '" . $realestateid . "'");

// When fully paid
if ($payed == 2) {
    R::exec("UPDATE `realestates` SET `savaible`= 0 WHERE id = '" . $realestateid . "'");
}
```

### Installment Consolidation
```php
$totalUnpaid = 0;
foreach($installments as $installment) {
    if ($installment->totalpaid == 0) {
        $totalUnpaid += $installment->valuerent;
        $installment->del = 2; // Mark as deleted
    }
}
// Add total to last remaining installment
```

---

## 🔒 Security & Permissions

### Input Validation
```php
$supplierid = filter_input(INPUT_POST, 'supplierid');
$realestateid = filter_input(INPUT_POST, 'realestateid');
$valuerents = filter_input(INPUT_POST, 'valuerents');
$id = filter_input(INPUT_POST, 'id');
```

### Session Management
- All functions use `$_SESSION['userid']` for audit trails
- Session data passed via CURL to expense controller
- User ID recorded in add/update/delete operations

### Data Integrity
- Soft delete pattern (del = 0,1,2)
- Audit trail with timestamps and user IDs
- Property availability status consistency
- Expense reversal on deletion

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Recommended**:
   - `realestateunitspaids(supplierid, realestateid)`
   - `realestateunitpaidinstallments(realestateunitpaidid)`
   - `realestateunitspaids(del, addtoday)`

2. **Query Patterns**:
   - Date range filtering for reports
   - Supplier-based filtering
   - Property availability lookups

### CURL Performance
- Expense controller calls may add latency
- Consider batching multiple expense operations
- Error handling for failed CURL requests

---

## 🐛 Common Issues & Troubleshooting

### 1. **Property Availability Inconsistency**
**Issue**: Property shows as available but has active ownership records  
**Cause**: Missing property status updates in save/delete operations

**Debug**:
```sql
SELECT r.id, r.realestatename, r.savaible, COUNT(p.id) as active_ownerships
FROM realestates r
LEFT JOIN realestateunitspaids p ON r.id = p.realestateid AND p.del < 2
GROUP BY r.id
HAVING r.savaible != (CASE WHEN active_ownerships > 0 THEN 1 ELSE 0 END);
```

### 2. **Installment Total Mismatch**
**Issue**: Sum of installments doesn't match total property value  
**Cause**: Manual installment editing without validation

**Fix**:
```sql
SELECT 
    p.id, 
    p.valuerents as total_value,
    SUM(i.valuerent) as installment_total
FROM realestateunitspaids p
LEFT JOIN realestateunitpaidinstallments i ON p.id = i.realestateunitpaidid AND i.del < 2
GROUP BY p.id
HAVING total_value != COALESCE(installment_total, 0);
```

### 3. **Missing Expense Records**
**Issue**: Payments recorded but no expense entries created  
**Cause**: CURL failure to expense controller

**Debug**:
```sql
SELECT p.*, h.expenseid, e.expensesid
FROM realestateunitspaids p
LEFT JOIN realestateunitpaidhistorys h ON p.realestateunitpaidhistoryid = h.id
LEFT JOIN expenses e ON h.expenseid = e.expensesid
WHERE p.advancepayment > 0 AND e.expensesid IS NULL;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Complete Property Purchase
```
1. Create new property ownership with advance payment
2. Verify property status changes to unavailable
3. Check expense record creation
4. Add installment payments
5. Verify payment status calculations
6. Confirm full payment marks property as unavailable
```

### Test Case 2: Installment Management
```
1. Create ownership with multiple installments
2. Pay some installments partially
3. Use editid() to consolidate unpaid installments
4. Verify installment count and amounts
5. Test removeappend() on individual installments
```

### Test Case 3: Data Integrity
```
1. Create ownership record
2. Delete using removecontroller()
3. Verify all related records marked as deleted
4. Check expense records are cancelled
5. Confirm property availability reset
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [realestateunitsrenters.md](realestateunitsrenters.md) - Rental management
- [realestateunitsreports.md](realestateunitsreports.md) - Reporting system
- [expensesController.md](expensesController.md) - Expense processing

---

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