# Payment Networks Controller Documentation

**File**: `/controllers/paymentnetworks.php`  
**Purpose**: Manages payment network configurations with discount percentages for transaction processing  
**Last Updated**: December 20, 2024  
**Total Functions**: 2  
**Lines of Code**: ~159

---

## 📋 Overview

The Payment Networks Controller manages the configuration and administration of payment networks within the ERP system. Payment networks represent different payment processing companies or gateways (like Visa, MasterCard, PayPal, etc.) with their associated discount percentages and fees. This controller handles the complete lifecycle of payment network management including creation, editing, listing, and soft deletion.

### Primary Functions
- [x] Create new payment networks with discount rates
- [x] View/list all active payment networks
- [x] Edit existing payment network details
- [x] Soft delete payment networks (mark as deleted)
- [x] Multilingual support (Arabic/English names)
- [x] Discount percentage management for fee calculations
- [x] Network-based transaction fee processing

### Related Controllers
- [paymentMethodsController.php](paymentMethodsController.md) - Payment method configuration
- [sellbillController.php](#) - Sales transactions with payment networks
- [clientPayedDeptController.php](#) - Customer payments through networks
- [buyBillController.php](#) - Purchase payments with network fees

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **paymentnetwork** | Payment network definitions | paymentnetworkid, name, nameen, discountpercent, deleted |

### Table Structure Details
**paymentnetwork**:
- `paymentnetworkid` - Primary key, auto-increment
- `name` - Arabic payment network name
- `nameen` - English payment network name
- `discountpercent` - Discount/fee percentage charged by network
- `deleted` - Soft delete flag (0=active, 1=deleted)

### Usage in Other Tables
Payment networks are likely referenced in:
- Sales bill tables for network fee calculations
- Payment transaction tables for processing fees
- Customer payment records for network selection

---

## 🔑 Key Functions

### 1. **Default Action** - Add Payment Network Form
**Location**: Lines 40-46  
**Purpose**: Display form for creating new payment networks

**Process Flow**:
1. Check authentication status
2. Load payment network creation form
3. Display via `paymentnetworksview/add.html` template
4. Form includes fields for names and discount percentage

---

### 2. **add()** - Create New Payment Network
**Location**: Lines 125-139  
**Purpose**: Process new payment network creation with discount configuration

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

**Input Parameters**:
- `$_POST['networkName']` - Arabic network name
- `$_POST['networkNameEn']` - English network name
- `$_POST['discountpercent']` - Network discount/fee percentage

**Process Flow**:
1. Extract POST data using `filter_input()` for security
2. Assign values to global payment network object
3. Set deleted flag to 0 (active)
4. Insert new record via DAO
5. Redirect to success page

**Data Assignment**:
```php
$paymentNetworks->name = $networkName;
$paymentNetworks->nameen = $networkNameEn;
$paymentNetworks->discountpercent = $discountpercent;
$paymentNetworks->deleted = 0;
```

**Input Filtering**:
```php
$networkName = filter_input(INPUT_POST, "networkName");
$networkNameEn = filter_input(INPUT_POST, "networkNameEn");
$discountpercent = filter_input(INPUT_POST, "discountpercent");
```

---

### 3. **show()** - List Payment Networks
**Location**: Lines 59-66  
**Purpose**: Display list of all payment networks (active and deleted)

**Process Flow**:
1. Check authentication
2. Query all payment networks via DAO
3. Assign data to Smarty template
4. Display via `paymentnetworksview/show.html`

**Query Details**:
```php
$paymentNetworks = $paymentNetworksDAO->queryAll();
```

**Note**: This queries ALL records including deleted ones. Filtering for active networks should be implemented in the template or DAO query.

---

### 4. **edit()** - Edit Payment Network Form
**Location**: Lines 83-91  
**Purpose**: Load existing payment network data for editing

**Function Signature**:
```php
// Triggered by: do=edit&id=X
$networkId = filter_input(INPUT_GET, "id");
```

**Process Flow**:
1. Check authentication
2. Get network ID from URL parameter with input filtering
3. Load existing record from database via DAO
4. Assign data to Smarty template as 'network'
5. Display edit form via `paymentnetworksview/edit.html`

---

### 5. **update()** - Update Payment Network
**Location**: Lines 141-158  
**Purpose**: Process payment network updates

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

**Input Parameters**:
- `$_POST['networkId']` - Network ID to update
- `$_POST['networkName']` - Updated Arabic name
- `$_POST['networkNameEn']` - Updated English name
- `$_POST['discountpercent']` - Updated discount percentage

**Process Flow**:
1. Extract POST data with input filtering
2. Load existing record by ID via DAO
3. Update all modifiable fields
4. Save updated record via DAO
5. Redirect to success page

**Update Implementation**:
```php
$paymentNetworks = $paymentNetworksDAO->load($networkId);
$paymentNetworks->name = $networkName;
$paymentNetworks->nameen = $networkNameEn;
$paymentNetworks->discountpercent = $discountpercent;
$paymentNetworksDAO->update($paymentNetworks);
```

---

### 6. **delete()** - Soft Delete Payment Network
**Location**: Lines 68-80  
**Purpose**: Mark payment network as deleted without physical removal

**Function Signature**:
```php
// Triggered by: do=delete&id=X
$networkId = filter_input(INPUT_GET, "id");
```

**Process Flow**:
1. Check authentication
2. Get network ID from URL with input filtering
3. Load existing record via DAO
4. Set `deleted = 1` (soft delete)
5. Update record via DAO
6. Redirect to success page

**Soft Delete Implementation**:
```php
$paymentNetworks = $paymentNetworksDAO->load($networkId);
$paymentNetworks->deleted = 1;
$paymentNetworksDAO->update($paymentNetworks);
```

---

## 🔄 Workflows

### Workflow 1: Create New Payment Network
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Payment Network                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Creation Form                                   │
│     - Check authentication                                  │
│     - Load paymentnetworksview/add.html                    │
│     - Include fields for names and discount rate           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Form Submission (do=add)                       │
│     - Extract POST data with input filtering               │
│     - Validate required fields                             │
│     - Set deleted flag to 0                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Insert Database Record                                  │
│     - Assign values to global DTO object                   │
│     - Insert via DAO layer                                 │
│     - Handle any insertion exceptions                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Redirect to Success Page                               │
│     - Success: Redirect to ?do=sucess                     │
│     - Error: Redirect to ?do=error                        │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Edit Payment Network
```
┌─────────────────────────────────────────────────────────────┐
│              START: Edit Payment Network                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Edit Form (do=edit&id=X)                          │
│     - Check authentication                                  │
│     - Extract and filter network ID from URL               │
│     - Load existing data via DAO                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Edit Form                                       │
│     - Populate form with current values                    │
│     - Assign data to template as 'network'                 │
│     - Show paymentnetworksview/edit.html                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Update (do=update)                             │
│     - Extract updated data from POST                       │
│     - Load existing record by ID                           │
│     - Update all modifiable fields                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Changes and Redirect                              │
│     - Update via DAO layer                                 │
│     - Redirect to success/error page                       │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description | Authentication |
|---------------|----------------|-------------|----------------|
| `do=` (empty) | Default | Display add form | Required |
| `do=add` | `add()` | Create new payment network | Required |
| `do=show` | `show()` | List all payment networks | Required |
| `do=edit` | `edit()` | Display edit form | Required |
| `do=update` | `update()` | Update existing network | Required |
| `do=delete` | `delete()` | Soft delete network | Required |
| `do=sucess` | - | Success confirmation page | No |
| `do=error` | - | Error display page | No |

### Required Parameters by Action

**Create Payment Network** (`do=add`):
- `networkName` - Arabic network name (required)
- `networkNameEn` - English network name (required)
- `discountpercent` - Network discount percentage (required)

**Edit Payment Network** (`do=edit`):
- `id` - Payment network ID (URL parameter, required)

**Update Payment Network** (`do=update`):
- `networkId` - Network ID (required)
- `networkName` - Updated Arabic name
- `networkNameEn` - Updated English name
- `discountpercent` - Updated discount percentage

**Delete Payment Network** (`do=delete`):
- `id` - Payment network ID (URL parameter, required)

---

## 🧮 Calculation Methods

### Discount/Fee Percentage Handling
Payment networks store discount percentages that are used for fee calculations in transaction processing:

```php
// Example fee calculation (would be in other controllers)
$transactionAmount = 1000.00;
$networkDiscountPercent = 2.5; // From payment network
$networkFee = $transactionAmount * ($networkDiscountPercent / 100);
$netAmount = $transactionAmount - $networkFee;
```

**Network Fee Application**:
- Stored as percentage in `discountpercent` field
- Applied to transaction amounts for fee calculation
- Reduces net amount received by merchant
- Used in sales and purchase transaction processing

---

## 🔒 Security & Permissions

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

**Security Features**:
- Authentication required for all operations
- Input filtering using `filter_input()` for security
- Exception handling with try-catch blocks
- Clean URL parameter processing

### Input Validation & Sanitization
```php
// Secure input filtering
$networkName = filter_input(INPUT_POST, "networkName");
$networkId = filter_input(INPUT_GET, "id");
```

**Security Strengths**:
1. `filter_input()` used consistently for all inputs
2. Exception handling prevents error exposure
3. DAO pattern prevents SQL injection
4. Soft delete maintains data integrity

**Security Considerations**:
- No explicit permission level checking beyond authentication
- Discount percentage validation should include range checking
- No CSRF token protection visible

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Recommended**:
   - `paymentnetwork(deleted)` - For active network filtering
   - `paymentnetwork(discountpercent)` - If used for fee range queries

2. **Query Patterns**:
   - Simple single-table operations
   - DAO layer provides SQL optimization
   - No complex joins or aggregations

### Memory Usage
- Single record operations (create, edit, update)
- Small data structures for network lists
- Minimal memory footprint

**Performance Characteristics**:
- Fast CRUD operations
- Low database load
- Simple template rendering

---

## 🐛 Common Issues & Troubleshooting

### 1. **Show Action Lists Deleted Networks**
**Issue**: Deleted networks appear in the list view  
**Cause**: `queryAll()` returns all records without filtering

**Fix**:
```php
// In DAO or controller, filter out deleted
$paymentNetworks = $paymentNetworksDAO->queryByDeleted(0);
// OR modify query in DAO:
// SELECT * FROM paymentnetwork WHERE deleted = 0
```

### 2. **Discount Percentage Validation**
**Issue**: Invalid discount percentages accepted  
**Cause**: No validation on percentage range

**Enhancement**:
```php
// Add validation in add() and update()
if ($discountpercent < 0 || $discountpercent > 100) {
    throw new Exception("Discount percentage must be between 0 and 100");
}
```

### 3. **Global Variable Issues**
**Issue**: Global variables may cause conflicts  
**Cause**: Global DTO and DAO objects

**Better Practice**:
```php
// Instead of global variables
function add() {
    $paymentNetworks = new Paymentnetwork();
    $paymentNetworksDAO = new PaymentnetworksMySqlDAO();
    // ... rest of function
}
```

### 4. **Input Filtering Edge Cases**
**Issue**: `filter_input()` may return NULL for valid data  
**Debug**:
```php
$networkName = filter_input(INPUT_POST, "networkName");
if ($networkName === NULL) {
    echo "Input filtering failed";
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Create Payment Network
```
1. Navigate to /controllers/paymentnetworks.php
2. Fill in Arabic and English network names
3. Set discount percentage (e.g., 2.5%)
4. Submit form
5. Verify record created in database
6. Check success page displays
```

### Test Case 2: Edit Payment Network
```
1. Go to payment networks list (do=show)
2. Click edit on existing network
3. Modify name and discount percentage
4. Submit update
5. Verify changes saved correctly
6. Check updated values in list view
```

### Test Case 3: Soft Delete
```
1. Delete payment network via delete action
2. Verify deleted flag set to 1 in database
3. Check if still appears in show list (bug test)
4. Confirm record preserved but marked deleted
```

### Test Case 4: Input Validation
```
1. Try creating network with empty names
2. Test with negative discount percentage
3. Test with percentage > 100%
4. Verify appropriate error handling
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [paymentMethodsController.md](paymentMethodsController.md) - Payment methods management
- [DAO Pattern Documentation](#) - Database access layer
- [Input Filtering Security Guide](#) - PHP security practices
- [Smarty Template System](#) - Template documentation

---

**Documented By**: AI Assistant  
**Review Status**: ⚠️ Needs enhancement for deleted record filtering  
**Next Review**: After filtering improvements implemented