# Premium Controller Documentation

**File**: `/controllers/premiumController.php`  
**Purpose**: Manages client premium/installment payment schedules and processing in the ERP system  
**Last Updated**: December 20, 2024  
**Total Functions**: 9  
**Lines of Code**: ~550

---

## 📋 Overview

The Premium Controller handles the complete lifecycle management of premium/installment payment systems for clients. It manages payment schedules, installment tracking, payment deferrals, and premium modifications. This system appears to be designed for subscription-based or installment payment business models where clients make regular scheduled payments.

### Primary Functions
- [x] Create client premium payment schedules
- [x] Generate multiple installment payments
- [x] Track payment status and completion
- [x] Handle payment deferrals and rescheduling  
- [x] View premium details and payment histories
- [x] Edit and update premium schedules
- [x] Delete premium records and associated payments
- [x] Client type integration for premium categories
- [x] User tracking and audit trails

### Related Controllers
- [premiumReportController.php](premiumReportController.md) - Premium reporting
- [premiumautomaticController.php](premiumautomaticController.md) - Automatic premium generation
- [allpremiumReportController.php](#) - Comprehensive premium reports
- [clientController.php](#) - Client management
- [typeClientController.php](#) - Client type definitions

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **premiumclient** | Premium client master records | id, clientId, userid, date |
| **premium** | Individual premium/installment records | id, date, value, premiumclientId, payed, rest, conditions |
| **client** | Customer information | clientid, clientname, typeclientid |
| **typeclient** | Client type definitions | typeId, typeName |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, username |
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |
| **premiumautomatic** | Automated premium settings | id, totalinstallment, presenterDir, presenterPer, remainAmount, installmentNos, clientId |

### Table Structure Details

**premiumclient**:
- `id` - Primary key, auto-increment
- `clientId` - Reference to client table
- `userid` - User who created the premium schedule
- `date` - Creation date of premium plan

**premium**:
- `id` - Primary key, auto-increment  
- `date` - Payment due date
- `value` - Payment amount
- `premiumclientId` - Reference to premiumclient table
- `payed` - Payment status (0=unpaid, 1=paid)
- `rest` - Remaining amount to be paid
- `conditions` - Payment condition (0=active, 1=deferred/cancelled)

---

## 🔑 Key Functions

### 1. **Default Action** - Add Premium Form
**Location**: Lines 106-115  
**Purpose**: Display form for creating new premium payment schedules

**Process Flow**:
1. Check authentication
2. Load all clients for dropdown selection
3. Assign client data to template
4. Display premium creation form via `premiumview/add.html`
5. Set client premium flag for template customization

---

### 2. **add()** - Create Premium Schedule
**Location**: Lines 332-343  
**Purpose**: Create new premium client record and generate payment schedule

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

**Input Parameters**:
- `$_POST['clientID']` - Selected client ID
- `$_POST['premiumItr']` - Number of installments
- `$_POST['date1'], $_POST['date2']...` - Payment due dates
- `$_POST['Amount1'], $_POST['Amount2']...` - Payment amounts

**Process Flow**:
1. Extract client ID from POST data with input filtering
2. Create premium client master record
3. Store user ID and creation timestamp
4. Call `addPremium()` to generate installment schedule
5. Redirect to success page

**Master Record Creation**:
```php
$Premiumclient->clientId = $client;
$Premiumclient->userid = $_SESSION['userid'];
$Premiumclient->date = date("Y-m-d h:i:sa");
$premiumClientid = $PremiumclientDAO->insert($Premiumclient);
```

---

### 3. **addPremium()** - Generate Installment Schedule
**Location**: Lines 345-365  
**Purpose**: Create individual premium payment records for a schedule

**Function Signature**:
```php
function addPremium($premiumClientid)
```

**Parameters**:
- `$premiumClientid` - Master premium client ID

**Process Flow**:
1. Extract number of installments from POST
2. Loop through each installment (1 to N)
3. Extract date and amount for each payment
4. Create premium record for each installment
5. Set default values (unpaid, no rest, active condition)

**Installment Creation Loop**:
```php
for ($i = 1; $i <= $premiumItr; $i++) {
    $date = filter_input(INPUT_POST, 'date' . $i);
    $amount = filter_input(INPUT_POST, 'Amount' . $i);
    if (!empty($date)) {
        $premium->date = $date;
        $premium->value = $amount;
        $premium->premiumclientId = $premiumClientid;
        $premium->payed = 0;
        $premium->rest = 0;
        $premium->conditions = 0;
        $premiumDAO->insert($premium);
    }
}
```

---

### 4. **show()** - List Premium Schedules
**Location**: Lines 367-385  
**Purpose**: Display all premium client schedules with user and client details

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

**Process Flow**:
1. Query all premium client records
2. For each record:
   - Load user details (username)
   - Load client details (client name)
   - Assign enriched data to record object
3. Return enriched premium data array

**Data Enrichment**:
```php
foreach ($allpremiums as $item) {
    $user = $userDAO->load($item->userid);
    $item->username = $user->username;
    
    $client_id = $item->clientId;
    $clientData = $clientExt->loadExt($client_id);
    foreach ($clientData as $single)
        $item->clientname = $single->clientname;
}
```

---

### 5. **details()** - Premium Details View
**Location**: Lines 140-185  
**Purpose**: Display detailed view of specific premium schedule with payment breakdown

**Process Flow**:
1. Get premium client ID from URL
2. Load premium client master data
3. Load all associated premium payment records
4. Calculate total unpaid amounts
5. Load and process client type information
6. Display detailed view with payment grid

**Total Calculation**:
```php
foreach ($alldataclient as $item) {
    if ($item->conditions == 0 && $item->payed == 0) {
        $total += $item->value - $item->rest;
    }
}
```

**Client Type Processing**:
```php
$clientData->typeclientid = explode(',', $clientData->typeclientid);
$azmy = array();
foreach ($typeClient as $item) {
    if (in_array($item->typeId, $clientData->typeclientid)) {
        array_push($azmy, $item->typeName);
    }
}
if (in_array('-20', $clientData->typeclientid)) {
    array_push($azmy, "كل انواع العملاء");
}
```

---

### 6. **edit()** - Edit Premium Schedule Form
**Location**: Lines 198-248  
**Purpose**: Load premium schedule for editing with current payment status

**Process Flow**:
1. Load all clients for dropdown
2. Get premium client ID from URL
3. Load premium master record
4. Load associated payment records (active only)
5. Calculate totals and payment count
6. Process client type information
7. Display edit form with current data

**Active Payments Query**:
```php
$alldata = $premiumExt->queryByPremiumclientConditionPayed($id);
```

---

### 7. **update()** - Update Premium Schedule
**Location**: Lines 388-412  
**Purpose**: Update existing premium schedule by recreating payment records

**Function Signature**:
```php
function update($today)
```

**Process Flow**:
1. Extract premium client ID and new client ID
2. Update premium client master record
3. Delete all existing premium payment records
4. Recreate payment schedule via `addPremium()`
5. Redirect to success page

**Record Recreation**:
```php
$PremiumclientDAO->update($Premiumclient);
$premiumDAO->deleteByPremiumclientId($Premiumclient->id);
addPremium($Premiumclient->id);
```

---

### 8. **addPremiumformreport()** - Defer Payment
**Location**: Lines 425-455  
**Purpose**: Handle payment deferral by marking current payment as deferred and creating new due date

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

**Input Parameters**:
- `$_POST['id']` - Premium payment ID to defer
- `$_POST['delayDate']` - New due date
- Various payment details

**Process Flow**:
1. Extract payment details and new date
2. Update original payment with `conditions = 1` (deferred)
3. Create new payment record with delay date
4. Maintain same amount and client association

**Deferral Implementation**:
```php
// Mark original as deferred
$premium->conditions = 1;
$premiumDAO->update($premium);

// Create new payment with delay date
$premium->date = $delayDate;
$premium->conditions = 0;
$premiumDAO->insert($premium);
```

---

### 9. **delete()** - Delete Premium Schedule
**Location**: Lines 415-422  
**Purpose**: Complete deletion of premium schedule and all associated payments

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

**Process Flow**:
1. Get premium client ID from URL
2. Delete all associated premium payment records
3. Delete premium client master record
4. Cascade deletion maintains data integrity

**Cascade Deletion**:
```php
$id = $_GET['id'];
$premiumDAO->deleteByPremiumclientId($id);
$PremiumclientDAO->delete($id);
```

---

## 🔄 Workflows

### Workflow 1: Create Premium Payment Schedule
```
┌─────────────────────────────────────────────────────────────┐
│             START: Create Premium Schedule                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Creation Form                                   │
│     - Load all clients for selection                       │
│     - Show dynamic installment form                        │
│     - Include date and amount fields for each installment  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Form Submission (do=add)                       │
│     - Extract selected client ID                           │
│     - Extract number of installments                       │
│     - Validate payment dates and amounts                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Premium Client Master Record                    │
│     - Insert premiumclient record                          │
│     - Record creator user ID                               │
│     - Set creation timestamp                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Generate Individual Payment Records                    │
│     FOR EACH installment (1 to N):                         │
│       │                                                     │
│       ├─→ Extract payment date and amount                  │
│       │                                                     │
│       ├─→ Create premium payment record                    │
│       │   ├─ Set due date and amount                       │
│       │   ├─ Link to premium client ID                     │
│       │   └─ Set as unpaid (payed=0, rest=0)              │
│       │                                                     │
│       └─→ Insert payment record                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Redirect to Success Page                               │
│     - Show confirmation of schedule creation               │
│     - Link to view created schedule                        │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Payment Deferral Process
```
┌─────────────────────────────────────────────────────────────┐
│               START: Defer Payment                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Payment to Defer                                │
│     - From premium report or payment list                  │
│     - Specify new due date                                 │
│     - Enter reason for deferral                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Mark Original Payment as Deferred                      │
│     - Load existing payment record                         │
│     - Set conditions = 1 (deferred status)                │
│     - Update record in database                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create New Payment Record                              │
│     - Same amount as original payment                      │
│     - New due date (delayDate)                            │
│     - Set conditions = 0 (active)                         │
│     - Link to same premium client                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update Payment Schedule                                 │
│     - Payment schedule now shows new due date              │
│     - Original payment marked as deferred                  │
│     - Total outstanding amount unchanged                    │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description | Authentication |
|---------------|----------------|-------------|----------------|
| `do=` (empty) | Default | Display add premium form | Required |
| `do=add` | `add()` | Create new premium schedule | Required |
| `do=show` | `show()` | List all premium schedules | Required |
| `do=details` | `details()` | View premium schedule details | Required |
| `do=edit` | `edit()` | Display edit premium form | Required |
| `do=update` | `update()` | Update premium schedule | Required |
| `do=delete` | `delete()` | Delete premium schedule | Required |
| `do=addPremiumformreport` | `addPremiumformreport()` | Defer payment | Required |
| `do=updatefromreport` | `updatefromreport()` | Update from report view | Required |
| `do=deletefromRemport` | `deletefromRemport()` | Delete from report view | Required |
| `do=sucess` | - | Success confirmation page | No |
| `do=error` | - | Error display page | No |

### Required Parameters by Action

**Create Premium** (`do=add`):
- `clientID` - Selected client ID (required)
- `premiumItr` - Number of installments (required)
- `date1`, `date2`... - Due dates for each installment
- `Amount1`, `Amount2`... - Amount for each installment

**View Details** (`do=details`):
- `id` - Premium client ID (URL parameter, required)

**Edit Premium** (`do=edit`):
- `id` - Premium client ID (URL parameter, required)

**Update Premium** (`do=update`):
- `Premiumclient` - Premium client ID to update
- `clientID` - Updated client ID
- Updated installment data

**Defer Payment** (`do=addPremiumformreport`):
- `id` - Premium payment ID to defer
- `delayDate` - New due date
- Payment details for deferral

---

## 🧮 Calculation Methods

### Total Outstanding Amount Calculation
```php
foreach ($alldataclient as $item) {
    if ($item->conditions == 0 && $item->payed == 0) {
        $total += $item->value - $item->rest;
    }
}
```

**Calculation Logic**:
- Only include active payments (`conditions = 0`)
- Only include unpaid payments (`payed = 0`)
- Calculate as: `payment_value - amount_already_paid`
- Sum across all qualifying payments

### Payment Status Tracking
```php
// Payment states
$premium->payed = 0;      // 0 = unpaid, 1 = paid
$premium->rest = 0;       // Remaining amount on partial payment
$premium->conditions = 0; // 0 = active, 1 = deferred/cancelled
```

### Client Type Processing
```php
// Parse comma-separated client types
$clientData->typeclientid = explode(',', $clientData->typeclientid);

// Special handling for "all client types"
if (in_array('-20', $clientData->typeclientid)) {
    array_push($azmy, "كل انواع العملاء");
}
```

---

## 🔒 Security & Permissions

### Authentication & Session Management
```php
include_once("../public/authentication.php");
```

**Security Features**:
- Authentication required for all operations
- Session-based user tracking
- Input filtering using `filter_input()` consistently
- Exception handling prevents error exposure

### Input Validation & Sanitization
```php
// Secure input filtering throughout
$client = filter_input(INPUT_POST, 'clientID');
$date = filter_input(INPUT_POST, 'date' . $i);
$amount = filter_input(INPUT_POST, 'Amount' . $i);
```

**Security Strengths**:
1. Consistent use of `filter_input()` for all inputs
2. User ID tracking for audit trails
3. Transaction-like operations (delete cascades)
4. DAO pattern prevents SQL injection

**Security Considerations**:
- No explicit permission level checking beyond authentication
- Amount validation should include range checking
- Date validation should ensure future dates for new payments

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Recommended**:
   - `premiumclient(clientId)` - For client-based queries
   - `premium(premiumclientId)` - For installment queries
   - `premium(date, payed, conditions)` - For due payment reports
   - `premium(conditions, payed)` - For status filtering

2. **Query Patterns**:
   - Master-detail relationships (premiumclient → premium)
   - Cascade operations for delete/update
   - Client enrichment requires joins

### Memory Management
- Multiple DAO object instantiation could be optimized
- Client type processing involves multiple loops
- Large premium schedules may impact memory

**Performance Characteristics**:
- Moderate database load due to multiple table operations
- Client type processing adds overhead
- Update operations rebuild entire payment schedules

---

## 🐛 Common Issues & Troubleshooting

### 1. **Update Function Recreates All Payments**
**Issue**: Editing premium deletes and recreates all payments, losing payment history  
**Cause**: `update()` function does complete recreation

**Impact**:
```php
// DESTROYS payment history
$premiumDAO->deleteByPremiumclientId($Premiumclient->id);
addPremium($Premiumclient->id);
```

**Better Approach**: Selective update preserving paid installments

### 2. **Date Format Inconsistencies**
**Issue**: Mixed date formats between creation and display  
**Cause**: `date("Y-m-d h:i:sa")` vs standard formats

**Fix**:
```php
// Use consistent format
$Premiumclient->date = date("Y-m-d H:i:s");
```

### 3. **Client Type Processing Performance**
**Issue**: Multiple loops for client type name resolution  
**Cause**: N+1 query pattern for type lookups

**Optimization**:
```php
// Pre-load all types into associative array
$typeMap = array();
foreach ($typeClient as $type) {
    $typeMap[$type->typeId] = $type->typeName;
}
```

### 4. **Global Variable Dependencies**
**Issue**: Heavy reliance on global variables creates coupling  
**Cause**: Functions expect global DAO objects

**Enhancement**: Pass dependencies as parameters

### 5. **Exception Handling Inconsistencies**
**Issue**: Some functions show errors, others hide them  
**Example**:
```php
// Inconsistent error handling
} catch (Exception $e) {
    echo $e;              // Shows error
//  header("location:?do=error"); // Hidden error
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Create Premium Schedule
```
1. Navigate to /controllers/premiumController.php
2. Select client from dropdown
3. Add multiple installments with dates and amounts
4. Submit form
5. Verify premium client record created
6. Verify all installment records created correctly
7. Check total calculations
```

### Test Case 2: Payment Deferral
```
1. Create premium schedule with near due dates
2. Go to premium reports
3. Select payment to defer
4. Set new due date
5. Verify original marked as deferred (conditions=1)
6. Verify new payment created with delay date
7. Check total outstanding unchanged
```

### Test Case 3: Schedule Editing
```
1. Edit existing premium schedule
2. Modify client, dates, or amounts
3. Submit update
4. Verify all old payments deleted
5. Verify new payments created correctly
6. Note: Payment history lost
```

### Test Case 4: Client Type Display
```
1. Create client with multiple types
2. Create premium for that client
3. View premium details
4. Verify client types displayed correctly
5. Test special "-20" all types handling
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [premiumReportController.md](premiumReportController.md) - Premium reporting
- [premiumautomaticController.md](premiumautomaticController.md) - Automated premiums
- [clientController.php](#) - Client management
- [DAO Pattern Documentation](#) - Database access layer

---

**Documented By**: AI Assistant  
**Review Status**: ⚠️ Contains design issues with update function  
**Next Review**: After payment history preservation implemented